diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..229cd04f20 --- /dev/null +++ b/.clang-format @@ -0,0 +1,28 @@ +--- +BasedOnStyle: LLVM +Language: Cpp + +ColumnLimit: 100 +IndentWidth: 4 +TabWidth: 4 +UseTab: ForIndentation + +ContinuationIndentWidth: 4 +ConstructorInitializerIndentWidth: 4 + +AlignAfterOpenBracket: BlockIndent + +# Put long return types on their own line +BreakAfterReturnType: Automatic + +# Put all initializers onto their own lines. +PackConstructorInitializers: CurrentLine + +# Put all function arguments on their own lines. +BinPackArguments: false +BinPackParameters: false + +# Format braces as {1, 2, 3}, not as { 1, 2, 3 }. +Cpp11BracedListStyle: true + +InsertNewlineAtEOF: true diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml new file mode 100644 index 0000000000..d8acac2eac --- /dev/null +++ b/.github/workflows/pre-commit.yml @@ -0,0 +1,21 @@ +name: pre-commit + +on: [merge_group, pull_request] + +jobs: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + # Check .clang-format is up to date + - uses: actions/checkout@v4 + with: + repository: 'managarm/common-config' + path: common-config + - run: 'cmp .clang-format common-config/.clang-format' + name: 'Check .clang-format is up to date' + + # Check formatting + - uses: actions/setup-python@v3 + - uses: pre-commit/action@v3.0.1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..57cb12ff68 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,14 @@ +fail_fast: false +repos: + - repo: https://github.com/pocc/pre-commit-hooks + rev: 336fdd7c3cab698ead0b1c95157b9e74d3906b62 + hooks: + - id: clang-format + additional_dependencies: [clang-format==19.1.3] + args: ["-i"] + exclude: > + (?x)^( + options/ansi/musl-generic-math/.*| + options/ansi/generic/complex/.*| + options/posix/musl-generic-regex/.* + ) diff --git a/README.md b/README.md index 12db9505bc..c459f9fa03 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,10 @@ The type of library to be built (static, shared, or both) is controlled by meson We also support building with `-Db_sanitize=undefined` to use UBSan inside mlibc. Note that this does not enable UBSan for external applications which link against `libc.so`, but it can be useful during development to detect internal bugs (e.g when adding new sysdeps). +## Running pre-commit hooks + +To format your code before submitting a PR, you should install [`pre-commit`](https://pre-commit.com/). Then do `pre-commit install` to install the git hook which runs each time you commit. Alternatively, you can do `pre-commit run -a` to manually format all files. + ## Running Tests The `mlibc` test suite can be run under a Linux host. To do this, first install a set of kernel headers (as described [here](https://docs.kernel.org/kbuild/headers_install.html)), then run from the project root: diff --git a/abis/dripos/errno.h b/abis/dripos/errno.h index 03750240aa..b03483b27a 100644 --- a/abis/dripos/errno.h +++ b/abis/dripos/errno.h @@ -1,149 +1,148 @@ #ifndef _ABIBITS_ERRNO_H #define _ABIBITS_ERRNO_H -#define EPERM 1 /* Operation not permitted */ -#define ENOENT 2 /* No such file or directory */ -#define ESRCH 3 /* No such process */ -#define EINTR 4 /* Interrupted system call */ -#define EIO 5 /* Input/output error */ -#define ENXIO 6 /* Device not configured */ -#define E2BIG 7 /* Argument list too long */ -#define ENOEXEC 8 /* Exec format error */ -#define EBADF 9 /* Bad file descriptor */ -#define ECHILD 10 /* No child processes */ -#define EDEADLK 11 /* Resource deadlock avoided */ - /* 11 was EAGAIN */ - -#define ENOMEM 12 /* Cannot allocate memory */ -#define EACCES 13 /* Permission denied */ -#define EFAULT 14 /* Bad address */ - -#define ENOTBLK 15 /* Block device required */ -#define EBUSY 16 /* Device busy */ - -#define EEXIST 17 /* File exists */ -#define EXDEV 18 /* Cross-device link */ -#define ENODEV 19 /* Operation not supported by device */ -#define ENOTDIR 20 /* Not a directory */ -#define EISDIR 21 /* Is a directory */ -#define EINVAL 22 /* Invalid argument */ -#define ENFILE 23 /* Too many open files in system */ -#define EMFILE 24 /* Too many open files */ -#define ENOTTY 25 /* Inappropriate ioctl for device */ - -#define ETXTBSY 26 /* Text file busy */ - -#define EFBIG 27 /* File too large */ -#define ENOSPC 28 /* No space left on device */ -#define ESPIPE 29 /* Illegal seek */ -#define EROFS 30 /* Read-only file system */ -#define EMLINK 31 /* Too many links */ -#define EPIPE 32 /* Broken pipe */ +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* Input/output error */ +#define ENXIO 6 /* Device not configured */ +#define E2BIG 7 /* Argument list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file descriptor */ +#define ECHILD 10 /* No child processes */ +#define EDEADLK 11 /* Resource deadlock avoided */ + /* 11 was EAGAIN */ + +#define ENOMEM 12 /* Cannot allocate memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ + +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device busy */ + +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* Operation not supported by device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define EINVAL 22 /* Invalid argument */ +#define ENFILE 23 /* Too many open files in system */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Inappropriate ioctl for device */ + +#define ETXTBSY 26 /* Text file busy */ + +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ /* math software */ -#define EDOM 33 /* Numerical argument out of domain */ -#define ERANGE 34 /* Result too large */ +#define EDOM 33 /* Numerical argument out of domain */ +#define ERANGE 34 /* Result too large */ /* non-blocking and interrupt i/o */ -#define EAGAIN 35 /* Resource temporarily unavailable */ +#define EAGAIN 35 /* Resource temporarily unavailable */ -#define EWOULDBLOCK EAGAIN /* Operation would block */ -#define EINPROGRESS 36 /* Operation now in progress */ -#define EALREADY 37 /* Operation already in progress */ +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define EINPROGRESS 36 /* Operation now in progress */ +#define EALREADY 37 /* Operation already in progress */ /* ipc/network software -- argument errors */ -#define ENOTSOCK 38 /* Socket operation on non-socket */ -#define EDESTADDRREQ 39 /* Destination address required */ -#define EMSGSIZE 40 /* Message too long */ -#define EPROTOTYPE 41 /* Protocol wrong type for socket */ -#define ENOPROTOOPT 42 /* Protocol not available */ -#define EPROTONOSUPPORT 43 /* Protocol not supported */ -#define ESOCKTNOSUPPORT 44 /* Socket type not supported */ -#define EOPNOTSUPP 45 /* Operation not supported on socket */ -#define EPFNOSUPPORT 46 /* Protocol family not supported */ -#define EAFNOSUPPORT 47 /* Address family not supported by protocol family */ -#define EADDRINUSE 48 /* Address already in use */ -#define EADDRNOTAVAIL 49 /* Can't assign requested address */ +#define ENOTSOCK 38 /* Socket operation on non-socket */ +#define EDESTADDRREQ 39 /* Destination address required */ +#define EMSGSIZE 40 /* Message too long */ +#define EPROTOTYPE 41 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 42 /* Protocol not available */ +#define EPROTONOSUPPORT 43 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 44 /* Socket type not supported */ +#define EOPNOTSUPP 45 /* Operation not supported on socket */ +#define EPFNOSUPPORT 46 /* Protocol family not supported */ +#define EAFNOSUPPORT 47 /* Address family not supported by protocol family */ +#define EADDRINUSE 48 /* Address already in use */ +#define EADDRNOTAVAIL 49 /* Can't assign requested address */ /* ipc/network software -- operational errors */ -#define ENETDOWN 50 /* Network is down */ -#define ENETUNREACH 51 /* Network is unreachable */ -#define ENETRESET 52 /* Network dropped connection on reset */ -#define ECONNABORTED 53 /* Software caused connection abort */ -#define ECONNRESET 54 /* Connection reset by peer */ -#define ENOBUFS 55 /* No buffer space available */ -#define EISCONN 56 /* Socket is already connected */ -#define ENOTCONN 57 /* Socket is not connected */ -#define ESHUTDOWN 58 /* Can't send after socket shutdown */ -#define ETOOMANYREFS 59 /* Too many references: can't splice */ -#define ETIMEDOUT 60 /* Connection timed out */ -#define ECONNREFUSED 61 /* Connection refused */ - -#define ELOOP 62 /* Too many levels of symbolic links */ - -#define ENAMETOOLONG 63 /* File name too long */ +#define ENETDOWN 50 /* Network is down */ +#define ENETUNREACH 51 /* Network is unreachable */ +#define ENETRESET 52 /* Network dropped connection on reset */ +#define ECONNABORTED 53 /* Software caused connection abort */ +#define ECONNRESET 54 /* Connection reset by peer */ +#define ENOBUFS 55 /* No buffer space available */ +#define EISCONN 56 /* Socket is already connected */ +#define ENOTCONN 57 /* Socket is not connected */ +#define ESHUTDOWN 58 /* Can't send after socket shutdown */ +#define ETOOMANYREFS 59 /* Too many references: can't splice */ +#define ETIMEDOUT 60 /* Connection timed out */ +#define ECONNREFUSED 61 /* Connection refused */ + +#define ELOOP 62 /* Too many levels of symbolic links */ + +#define ENAMETOOLONG 63 /* File name too long */ /* should be rearranged */ -#define EHOSTDOWN 64 /* Host is down */ -#define EHOSTUNREACH 65 /* No route to host */ -#define ENOTEMPTY 66 /* Directory not empty */ +#define EHOSTDOWN 64 /* Host is down */ +#define EHOSTUNREACH 65 /* No route to host */ +#define ENOTEMPTY 66 /* Directory not empty */ /* quotas & mush */ -#define EPROCLIM 67 /* Too many processes */ -#define EUSERS 68 /* Too many users */ -#define EDQUOT 69 /* Disc quota exceeded */ +#define EPROCLIM 67 /* Too many processes */ +#define EUSERS 68 /* Too many users */ +#define EDQUOT 69 /* Disc quota exceeded */ /* Network File System */ -#define ESTALE 70 /* Stale NFS file handle */ -#define EREMOTE 71 /* Too many levels of remote in path */ -#define EBADRPC 72 /* RPC struct is bad */ -#define ERPCMISMATCH 73 /* RPC version wrong */ -#define EPROGUNAVAIL 74 /* RPC prog. not avail */ -#define EPROGMISMATCH 75 /* Program version wrong */ -#define EPROCUNAVAIL 76 /* Bad procedure for program */ - - -#define ENOLCK 77 /* No locks available */ -#define ENOSYS 78 /* Function not implemented */ - -#define EFTYPE 79 /* Inappropriate file type or format */ -#define EOVERFLOW 80 -#define EILSEQ 81 - -#define EBADMSG 82 -#define ECANCELED 83 -#define EIDRM 84 -#define EMULTIHOP 85 -#define ENOLINK 86 -#define ENOMSG 87 -#define ENOTRECOVERABLE 88 -#define ENOTSUP 89 -#define EOWNERDEAD 90 -#define EPROTO 91 -#define ENODATA 92 -#define ETIME 93 -#define ENOKEY 94 -#define EBADFD 95 -#define ENOMEDIUM 96 -#define ENONET 97 -#define ESTRPIPE 98 -#define EREMOTEIO 99 -#define ERFKILL 100 -#define EBADR 101 -#define EUNATCH 102 -#define EMEDIUMTYPE 103 -#define EKEYREJECTED 104 -#define EUCLEAN 105 -#define EBADSLT 106 -#define ENOANO 107 -#define ENOCSI 108 -#define ENOSTR 109 -#define ENOPKG 110 -#define EKEYREVOKED 111 -#define EXFULL 112 -#define ELNRNG 113 -#define ENOTUNIQ 114 -#define ERESTART 115 -#define ENOTSUP 116 +#define ESTALE 70 /* Stale NFS file handle */ +#define EREMOTE 71 /* Too many levels of remote in path */ +#define EBADRPC 72 /* RPC struct is bad */ +#define ERPCMISMATCH 73 /* RPC version wrong */ +#define EPROGUNAVAIL 74 /* RPC prog. not avail */ +#define EPROGMISMATCH 75 /* Program version wrong */ +#define EPROCUNAVAIL 76 /* Bad procedure for program */ + +#define ENOLCK 77 /* No locks available */ +#define ENOSYS 78 /* Function not implemented */ + +#define EFTYPE 79 /* Inappropriate file type or format */ +#define EOVERFLOW 80 +#define EILSEQ 81 + +#define EBADMSG 82 +#define ECANCELED 83 +#define EIDRM 84 +#define EMULTIHOP 85 +#define ENOLINK 86 +#define ENOMSG 87 +#define ENOTRECOVERABLE 88 +#define ENOTSUP 89 +#define EOWNERDEAD 90 +#define EPROTO 91 +#define ENODATA 92 +#define ETIME 93 +#define ENOKEY 94 +#define EBADFD 95 +#define ENOMEDIUM 96 +#define ENONET 97 +#define ESTRPIPE 98 +#define EREMOTEIO 99 +#define ERFKILL 100 +#define EBADR 101 +#define EUNATCH 102 +#define EMEDIUMTYPE 103 +#define EKEYREJECTED 104 +#define EUCLEAN 105 +#define EBADSLT 106 +#define ENOANO 107 +#define ENOCSI 108 +#define ENOSTR 109 +#define ENOPKG 110 +#define EKEYREVOKED 111 +#define EXFULL 112 +#define ELNRNG 113 +#define ENOTUNIQ 114 +#define ERESTART 115 +#define ENOTSUP 116 #endif diff --git a/abis/ironclad/blksize_t.h b/abis/ironclad/blksize_t.h index a0f23b25f9..a2d2266e56 100644 --- a/abis/ironclad/blksize_t.h +++ b/abis/ironclad/blksize_t.h @@ -5,4 +5,3 @@ typedef long blksize_t; #endif /* _ABIBITS_BLKSIZE_T_H */ - diff --git a/abis/ironclad/clockid_t.h b/abis/ironclad/clockid_t.h index c3932eff31..e8529aee28 100644 --- a/abis/ironclad/clockid_t.h +++ b/abis/ironclad/clockid_t.h @@ -4,4 +4,3 @@ typedef long clockid_t; #endif /* _ABIBITS_CLOCKID_T_H */ - diff --git a/abis/ironclad/fcntl.h b/abis/ironclad/fcntl.h index 9bdda03b36..6a76542adf 100644 --- a/abis/ironclad/fcntl.h +++ b/abis/ironclad/fcntl.h @@ -2,49 +2,49 @@ #define _ABIBITS_FCNTL_H /* Flags supported by the kernel. */ -#define O_ACCMODE 0b000011 -#define O_RDONLY 00000001 -#define O_WRONLY 0b000010 -#define O_RDWR 0b000011 -#define O_APPEND 0b000100 -#define O_CLOEXEC 0b001000 -#define O_NOFOLLOW 0b010000 -#define O_NONBLOCK 0b100000 +#define O_ACCMODE 0b000011 +#define O_RDONLY 00000001 +#define O_WRONLY 0b000010 +#define O_RDWR 0b000011 +#define O_APPEND 0b000100 +#define O_CLOEXEC 0b001000 +#define O_NOFOLLOW 0b010000 +#define O_NONBLOCK 0b100000 /* Flags emulated by userland, we just have to make sure they dont overlap with */ /* kernel flags. */ #define O_CREAT 0b0010000000 -#define O_EXCL 0b0100000000 +#define O_EXCL 0b0100000000 #define O_TRUNC 0b1000000000 /* Stubbed flags, the value really doesnt matter as long as they dont overlap */ /* with usable ones. */ /* Implemented here as some software needs them to compile. */ -#define O_SEARCH 0b000000000010000000000 -#define O_EXEC 0b000000000100000000000 -#define O_NOCTTY 0b000000001000000000000 -#define O_DSYNC 0b000000010000000000000 -#define O_RSYNC 0b000000100000000000000 -#define O_SYNC 0b000001000000000000000 -#define O_PATH 0b000010000000000000000 +#define O_SEARCH 0b000000000010000000000 +#define O_EXEC 0b000000000100000000000 +#define O_NOCTTY 0b000000001000000000000 +#define O_DSYNC 0b000000010000000000000 +#define O_RSYNC 0b000000100000000000000 +#define O_SYNC 0b000001000000000000000 +#define O_PATH 0b000010000000000000000 #define O_DIRECTORY 0b000100000000000000000 #define O_LARGEFILE 0b001000000000000000000 -#define O_NOATIME 0b010000000000000000000 -#define O_TMPFILE 0b100000000000000000000 +#define O_NOATIME 0b010000000000000000000 +#define O_TMPFILE 0b100000000000000000000 /* Fcntl flags. */ -#define FD_CLOEXEC 1 +#define FD_CLOEXEC 1 #define F_DUPFD 1 #define F_DUPFD_CLOEXEC 2 -#define F_GETFD 3 -#define F_SETFD 4 -#define F_GETFL 5 -#define F_SETFL 6 +#define F_GETFD 3 +#define F_SETFD 4 +#define F_GETFL 5 +#define F_SETFL 6 #define F_GETPIPE_SZ 7 #define F_SETPIPE_SZ 8 -#define F_GETLK 9 -#define F_SETLK 10 -#define F_SETLKW 11 +#define F_GETLK 9 +#define F_SETLK 10 +#define F_SETLKW 11 #define F_RDLCK 1 #define F_UNLCK 2 @@ -55,18 +55,18 @@ #define F_SETOWN 11 #define F_SEAL_SHRINK 0x0002 -#define F_SEAL_GROW 0x0004 -#define F_SEAL_WRITE 0x0008 -#define F_SEAL_SEAL 0x0010 -#define F_ADD_SEALS 1033 -#define F_GET_SEALS 1034 +#define F_SEAL_GROW 0x0004 +#define F_SEAL_WRITE 0x0008 +#define F_SEAL_SEAL 0x0010 +#define F_ADD_SEALS 1033 +#define F_GET_SEALS 1034 /* At flags. */ -#define AT_REMOVEDIR 500 -#define AT_EACCESS 512 -#define AT_FDCWD 0x7FFFFFFF -#define AT_EMPTY_PATH 1 -#define AT_SYMLINK_FOLLOW 0 +#define AT_REMOVEDIR 500 +#define AT_EACCESS 512 +#define AT_FDCWD 0x7FFFFFFF +#define AT_EMPTY_PATH 1 +#define AT_SYMLINK_FOLLOW 0 #define AT_SYMLINK_NOFOLLOW 2 #define POSIX_FADV_NORMAL 1 diff --git a/abis/ironclad/in.h b/abis/ironclad/in.h index 2b703585c8..8c9c52c7ab 100644 --- a/abis/ironclad/in.h +++ b/abis/ironclad/in.h @@ -1,9 +1,9 @@ #ifndef _ABIBITS_IN_H #define _ABIBITS_IN_H +#include #include #include -#include #ifdef __cplusplus extern "C" { @@ -19,7 +19,7 @@ struct sockaddr_in { struct in_addr sin_addr; uint8_t pad[8]; }; -#define sin_zero pad /* for BSD Unix compatibility */ +#define sin_zero pad /* for BSD Unix compatibility */ struct in6_addr { union { @@ -83,8 +83,14 @@ struct group_source_req { } #endif -#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } -#define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } +#define IN6ADDR_ANY_INIT \ + { \ + { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } \ + } +#define IN6ADDR_LOOPBACK_INIT \ + { \ + { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } \ + } #define IPPROTO_IP 1 #define IPPROTO_IPV6 2 @@ -146,23 +152,23 @@ struct group_source_req { #define IP_UNICAST_IF 13 #define IP_MTU 14 -#define IP_DEFAULT_MULTICAST_TTL 1 -#define IP_MULTICAST_IF 32 -#define IP_MULTICAST_TTL 33 -#define IP_MULTICAST_LOOP 34 -#define IP_ADD_MEMBERSHIP 35 -#define IP_DROP_MEMBERSHIP 36 -#define IP_UNBLOCK_SOURCE 37 -#define IP_BLOCK_SOURCE 38 -#define IP_ADD_SOURCE_MEMBERSHIP 39 +#define IP_DEFAULT_MULTICAST_TTL 1 +#define IP_MULTICAST_IF 32 +#define IP_MULTICAST_TTL 33 +#define IP_MULTICAST_LOOP 34 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 +#define IP_UNBLOCK_SOURCE 37 +#define IP_BLOCK_SOURCE 38 +#define IP_ADD_SOURCE_MEMBERSHIP 39 #define IP_DROP_SOURCE_MEMBERSHIP 40 -#define MCAST_JOIN_SOURCE_GROUP 46 -#define MCAST_LEAVE_SOURCE_GROUP 47 +#define MCAST_JOIN_SOURCE_GROUP 46 +#define MCAST_LEAVE_SOURCE_GROUP 47 #define IP_PMTUDISC_DONT 0 -#define IP_PMTUDISC_DO 2 +#define IP_PMTUDISC_DO 2 -#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP #endif /* _ABIBITS_IN_H */ diff --git a/abis/ironclad/msg.h b/abis/ironclad/msg.h index 5e890c0687..213f83d5d4 100644 --- a/abis/ironclad/msg.h +++ b/abis/ironclad/msg.h @@ -1,10 +1,10 @@ #ifndef _ABIBITS_MSG_H #define _ABIBITS_MSG_H -#include +#include #include #include -#include +#include #ifdef __cplusplus extern "C" { @@ -36,4 +36,3 @@ struct msqid_ds { #endif #endif /* _ABIBITS_MSG_H */ - diff --git a/abis/ironclad/signal.h b/abis/ironclad/signal.h index 3ecabad046..d466453020 100644 --- a/abis/ironclad/signal.h +++ b/abis/ironclad/signal.h @@ -26,7 +26,7 @@ extern "C" { #endif /* Argument for signal() */ -typedef void (*__sighandler) (int); +typedef void (*__sighandler)(int); #define SIG_ERR ((__sighandler)(void *)(-1)) #define SIG_DFL ((__sighandler)(void *)(-2)) @@ -113,9 +113,9 @@ typedef long sigset_t; #define SS_DISABLE 2 typedef struct __stack { - void *ss_sp; - size_t ss_size; - int ss_flags; + void *ss_sp; + size_t ss_size; + int ss_flags; } stack_t; /* constants for sigev_notify of struct sigevent */ @@ -152,10 +152,10 @@ struct sigevent { }; struct sigaction { - union { - void (*sa_handler)(int); - void (*sa_sigaction)(int, siginfo_t *, void *); - }; + union { + void (*sa_handler)(int); + void (*sa_sigaction)(int, siginfo_t *, void *); + }; sigset_t sa_mask; int sa_flags; }; diff --git a/abis/ironclad/socket.h b/abis/ironclad/socket.h index d7754f456a..359b087f62 100644 --- a/abis/ironclad/socket.h +++ b/abis/ironclad/socket.h @@ -27,7 +27,7 @@ struct sockaddr_storage { struct mmsghdr { struct msghdr msg_hdr; - unsigned int msg_len; + unsigned int msg_len; }; struct cmsghdr { diff --git a/abis/ironclad/stat.h b/abis/ironclad/stat.h index 37f6aaa016..534615b8f6 100644 --- a/abis/ironclad/stat.h +++ b/abis/ironclad/stat.h @@ -1,17 +1,17 @@ #ifndef _ABIBITS_STAT_H #define _ABIBITS_STAT_H -#include -#include -#include -#include +#include +#include #include +#include #include -#include -#include +#include #include +#include #include #include +#include #define S_IFMT 0x0F000 #define S_IFBLK 0x06000 @@ -38,9 +38,9 @@ #define S_ISGID 02000 #define S_ISVTX 01000 -#define S_IREAD S_IRUSR +#define S_IREAD S_IRUSR #define S_IWRITE S_IWUSR -#define S_IEXEC S_IXUSR +#define S_IEXEC S_IXUSR #ifdef __cplusplus extern "C" { diff --git a/abis/ironclad/statfs.h b/abis/ironclad/statfs.h index 60c977f65f..7d840526eb 100644 --- a/abis/ironclad/statfs.h +++ b/abis/ironclad/statfs.h @@ -25,4 +25,3 @@ struct statfs { }; #endif /* _ABIBITS_STATFS_H */ - diff --git a/abis/ironclad/statvfs.h b/abis/ironclad/statvfs.h index 3b73bd817a..02b0f569d0 100644 --- a/abis/ironclad/statvfs.h +++ b/abis/ironclad/statvfs.h @@ -27,4 +27,3 @@ struct statvfs { }; #endif /* _ABIBITS_STATVFS_H */ - diff --git a/abis/ironclad/termios.h b/abis/ironclad/termios.h index 475cd5bd55..903831768f 100644 --- a/abis/ironclad/termios.h +++ b/abis/ironclad/termios.h @@ -6,101 +6,101 @@ typedef unsigned int speed_t; typedef unsigned int tcflag_t; /* indices for the c_cc array in struct termios */ -#define NCCS 11 -#define VEOF 0 -#define VEOL 1 -#define VERASE 2 -#define VINTR 3 -#define VKILL 4 -#define VMIN 5 -#define VQUIT 6 -#define VSTART 7 -#define VSTOP 8 -#define VSUSP 9 -#define VTIME 10 +#define NCCS 11 +#define VEOF 0 +#define VEOL 1 +#define VERASE 2 +#define VINTR 3 +#define VKILL 4 +#define VMIN 5 +#define VQUIT 6 +#define VSTART 7 +#define VSTOP 8 +#define VSUSP 9 +#define VTIME 10 /* bitwise flags for c_iflag in struct termios */ -#define BRKINT 0x0001 -#define ICRNL 0x0002 -#define IGNBRK 0x0004 -#define IGNCR 0x0008 -#define IGNPAR 0x0010 -#define INLCR 0x0020 -#define INPCK 0x0040 -#define ISTRIP 0x0080 -#define IXANY 0x0100 -#define IXOFF 0x0200 -#define IXON 0x0400 -#define PARMRK 0x0800 +#define BRKINT 0x0001 +#define ICRNL 0x0002 +#define IGNBRK 0x0004 +#define IGNCR 0x0008 +#define IGNPAR 0x0010 +#define INLCR 0x0020 +#define INPCK 0x0040 +#define ISTRIP 0x0080 +#define IXANY 0x0100 +#define IXOFF 0x0200 +#define IXON 0x0400 +#define PARMRK 0x0800 #define ECHOCTL 0001000 #define IMAXBEL 0020000 -#define ECHOKE 0004000 +#define ECHOKE 0004000 /* bitwise flags for c_oflag in struct termios */ -#define OPOST 0x0001 -#define ONLCR 0x0002 -#define OCRNL 0x0004 -#define ONOCR 0x0008 -#define ONLRET 0x0010 -#define OFDEL 0x0020 -#define OFILL 0x0040 - -#define NLDLY 0x0080 -#define NL0 0x0000 -#define NL1 0x0080 - -#define CRDLY 0x0300 -#define CR0 0x0000 -#define CR1 0x0100 -#define CR2 0x0200 -#define CR3 0x0300 - -#define TABDLY 0x0C00 -#define TAB0 0x0000 -#define TAB1 0x0400 -#define TAB2 0x0800 -#define TAB3 0x0C00 - -#define BSDLY 0x1000 -#define BS0 0x0000 -#define BS1 0x1000 - -#define VTDLY 0x2000 -#define VT0 0x0000 -#define VT1 0x2000 - -#define FFDLY 0x4000 -#define FF0 0x0000 -#define FF1 0x4000 +#define OPOST 0x0001 +#define ONLCR 0x0002 +#define OCRNL 0x0004 +#define ONOCR 0x0008 +#define ONLRET 0x0010 +#define OFDEL 0x0020 +#define OFILL 0x0040 + +#define NLDLY 0x0080 +#define NL0 0x0000 +#define NL1 0x0080 + +#define CRDLY 0x0300 +#define CR0 0x0000 +#define CR1 0x0100 +#define CR2 0x0200 +#define CR3 0x0300 + +#define TABDLY 0x0C00 +#define TAB0 0x0000 +#define TAB1 0x0400 +#define TAB2 0x0800 +#define TAB3 0x0C00 + +#define BSDLY 0x1000 +#define BS0 0x0000 +#define BS1 0x1000 + +#define VTDLY 0x2000 +#define VT0 0x0000 +#define VT1 0x2000 + +#define FFDLY 0x4000 +#define FF0 0x0000 +#define FF1 0x4000 /* bitwise constants for c_cflag in struct termios */ -#define CSIZE 0x0003 -#define CS5 0x0000 -#define CS6 0x0001 -#define CS7 0x0002 -#define CS8 0x0003 - -#define CSTOPB 0x0004 -#define CREAD 0x0008 -#define PARENB 0x0010 -#define PARODD 0x0020 -#define HUPCL 0x0040 -#define CLOCAL 0x0080 +#define CSIZE 0x0003 +#define CS5 0x0000 +#define CS6 0x0001 +#define CS7 0x0002 +#define CS8 0x0003 + +#define CSTOPB 0x0004 +#define CREAD 0x0008 +#define PARENB 0x0010 +#define PARODD 0x0020 +#define HUPCL 0x0040 +#define CLOCAL 0x0080 #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) -#define CBAUD 0x100F +#define CBAUD 0x100F #endif /* bitwise constants for c_lflag in struct termios */ -#define ECHO 0x0001 -#define ECHOE 0x0002 -#define ECHOK 0x0004 -#define ECHONL 0x0008 -#define ICANON 0x0010 -#define IEXTEN 0x0020 -#define ISIG 0x0040 -#define NOFLSH 0x0080 -#define TOSTOP 0x0100 +#define ECHO 0x0001 +#define ECHOE 0x0002 +#define ECHOK 0x0004 +#define ECHONL 0x0008 +#define ICANON 0x0010 +#define IEXTEN 0x0020 +#define ISIG 0x0040 +#define NOFLSH 0x0080 +#define TOSTOP 0x0100 #define ECHOPRT 0x0200 struct termios { diff --git a/abis/ironclad/time.h b/abis/ironclad/time.h index dfc342ed2f..fa87af7952 100644 --- a/abis/ironclad/time.h +++ b/abis/ironclad/time.h @@ -4,12 +4,12 @@ #include struct itimerval { - struct timeval it_interval; /* Interval for periodic timer */ - struct timeval it_value; /* Time until next expiration */ + struct timeval it_interval; /* Interval for periodic timer */ + struct timeval it_value; /* Time until next expiration */ }; -#define ITIMER_REAL 0 -#define ITIMER_VIRTUAL 1 -#define ITIMER_PROF 2 +#define ITIMER_REAL 0 +#define ITIMER_VIRTUAL 1 +#define ITIMER_PROF 2 #endif /* _ABIBITS_TIME_H */ diff --git a/abis/ironclad/vm-flags.h b/abis/ironclad/vm-flags.h index 86628a4872..85bd1b6778 100644 --- a/abis/ironclad/vm-flags.h +++ b/abis/ironclad/vm-flags.h @@ -1,20 +1,20 @@ #ifndef _ABIBITS_MMAP_FLAGS_H #define _ABIBITS_MMAP_FLAGS_H -#define PROT_NONE 0x00 -#define PROT_READ 0x01 +#define PROT_NONE 0x00 +#define PROT_READ 0x01 #define PROT_WRITE 0x02 -#define PROT_EXEC 0x04 +#define PROT_EXEC 0x04 #define MAP_FAILED ((void *)(-1)) -#define MAP_FILE 0x00 -#define MAP_PRIVATE 0x01 -#define MAP_SHARED 0x02 -#define MAP_FIXED 0x04 -#define MAP_ANON 0x08 +#define MAP_FILE 0x00 +#define MAP_PRIVATE 0x01 +#define MAP_SHARED 0x02 +#define MAP_FIXED 0x04 +#define MAP_ANON 0x08 #define MAP_ANONYMOUS 0x08 #define MAP_NORESERVE 0x10 -#define MAP_WC 0b10000 +#define MAP_WC 0b10000 #define MS_ASYNC 0x01 #define MS_SYNC 0x02 diff --git a/abis/ironclad/xattr.h b/abis/ironclad/xattr.h index c0e7fbebde..09701d6c52 100644 --- a/abis/ironclad/xattr.h +++ b/abis/ironclad/xattr.h @@ -15,7 +15,7 @@ enum { XATTR_REPLACE = 2, #define XATTR_REPLACE XATTR_REPLACE }; -# define __UAPI_DEF_XATTR 0 +#define __UAPI_DEF_XATTR 0 #endif #endif /* MLIBC_ABIS_LINUX_XATTR_H */ diff --git a/abis/linux/blksize_t.h b/abis/linux/blksize_t.h index 02b207a7f0..aba87f1f84 100644 --- a/abis/linux/blksize_t.h +++ b/abis/linux/blksize_t.h @@ -5,4 +5,3 @@ typedef long blksize_t; #endif /* _ABIBITS_BLKSIZE_T_H */ - diff --git a/abis/linux/clockid_t.h b/abis/linux/clockid_t.h index 8d928268c8..e1cdbda7ab 100644 --- a/abis/linux/clockid_t.h +++ b/abis/linux/clockid_t.h @@ -4,4 +4,3 @@ typedef int clockid_t; #endif /* _ABIBITS_CLOCKID_T_H */ - diff --git a/abis/linux/dev_t.h b/abis/linux/dev_t.h index c39ab67f49..74e0a9d2c5 100644 --- a/abis/linux/dev_t.h +++ b/abis/linux/dev_t.h @@ -7,4 +7,3 @@ typedef __mlibc_uint64 dev_t; #endif /* _ABIBITS_DEV_T_H */ - diff --git a/abis/linux/errno.h b/abis/linux/errno.h index bac314f0cf..4b422c1699 100644 --- a/abis/linux/errno.h +++ b/abis/linux/errno.h @@ -1,143 +1,142 @@ #ifndef _ABIBITS_ERRNO_H #define _ABIBITS_ERRNO_H -#define EPERM 1 -#define ENOENT 2 -#define ESRCH 3 -#define EINTR 4 -#define EIO 5 -#define ENXIO 6 -#define E2BIG 7 -#define ENOEXEC 8 -#define EBADF 9 -#define ECHILD 10 -#define EAGAIN 11 -#define ENOMEM 12 -#define EACCES 13 -#define EFAULT 14 -#define ENOTBLK 15 -#define EBUSY 16 -#define EEXIST 17 -#define EXDEV 18 -#define ENODEV 19 -#define ENOTDIR 20 -#define EISDIR 21 -#define EINVAL 22 -#define ENFILE 23 -#define EMFILE 24 -#define ENOTTY 25 -#define ETXTBSY 26 -#define EFBIG 27 -#define ENOSPC 28 -#define ESPIPE 29 -#define EROFS 30 -#define EMLINK 31 -#define EPIPE 32 -#define EDOM 33 -#define ERANGE 34 -#define EDEADLK 35 -#define ENAMETOOLONG 36 -#define ENOLCK 37 -#define ENOSYS 38 -#define ENOTEMPTY 39 -#define ELOOP 40 -#define EWOULDBLOCK EAGAIN -#define ENOMSG 42 -#define EIDRM 43 -#define ECHRNG 44 -#define EL2NSYNC 45 -#define EL3HLT 46 -#define EL3RST 47 -#define ELNRNG 48 -#define EUNATCH 49 -#define ENOCSI 50 -#define EL2HLT 51 -#define EBADE 52 -#define EBADR 53 -#define EXFULL 54 -#define ENOANO 55 -#define EBADRQC 56 -#define EBADSLT 57 -#define EDEADLOCK EDEADLK -#define EBFONT 59 -#define ENOSTR 60 -#define ENODATA 61 -#define ETIME 62 -#define ENOSR 63 -#define ENONET 64 -#define ENOPKG 65 -#define EREMOTE 66 -#define ENOLINK 67 -#define EADV 68 -#define ESRMNT 69 -#define ECOMM 70 -#define EPROTO 71 -#define EMULTIHOP 72 -#define EDOTDOT 73 -#define EBADMSG 74 -#define EOVERFLOW 75 -#define ENOTUNIQ 76 -#define EBADFD 77 -#define EREMCHG 78 -#define ELIBACC 79 -#define ELIBBAD 80 -#define ELIBSCN 81 -#define ELIBMAX 82 -#define ELIBEXEC 83 -#define EILSEQ 84 -#define ERESTART 85 -#define ESTRPIPE 86 -#define EUSERS 87 -#define ENOTSOCK 88 -#define EDESTADDRREQ 89 -#define EMSGSIZE 90 -#define EPROTOTYPE 91 -#define ENOPROTOOPT 92 +#define EPERM 1 +#define ENOENT 2 +#define ESRCH 3 +#define EINTR 4 +#define EIO 5 +#define ENXIO 6 +#define E2BIG 7 +#define ENOEXEC 8 +#define EBADF 9 +#define ECHILD 10 +#define EAGAIN 11 +#define ENOMEM 12 +#define EACCES 13 +#define EFAULT 14 +#define ENOTBLK 15 +#define EBUSY 16 +#define EEXIST 17 +#define EXDEV 18 +#define ENODEV 19 +#define ENOTDIR 20 +#define EISDIR 21 +#define EINVAL 22 +#define ENFILE 23 +#define EMFILE 24 +#define ENOTTY 25 +#define ETXTBSY 26 +#define EFBIG 27 +#define ENOSPC 28 +#define ESPIPE 29 +#define EROFS 30 +#define EMLINK 31 +#define EPIPE 32 +#define EDOM 33 +#define ERANGE 34 +#define EDEADLK 35 +#define ENAMETOOLONG 36 +#define ENOLCK 37 +#define ENOSYS 38 +#define ENOTEMPTY 39 +#define ELOOP 40 +#define EWOULDBLOCK EAGAIN +#define ENOMSG 42 +#define EIDRM 43 +#define ECHRNG 44 +#define EL2NSYNC 45 +#define EL3HLT 46 +#define EL3RST 47 +#define ELNRNG 48 +#define EUNATCH 49 +#define ENOCSI 50 +#define EL2HLT 51 +#define EBADE 52 +#define EBADR 53 +#define EXFULL 54 +#define ENOANO 55 +#define EBADRQC 56 +#define EBADSLT 57 +#define EDEADLOCK EDEADLK +#define EBFONT 59 +#define ENOSTR 60 +#define ENODATA 61 +#define ETIME 62 +#define ENOSR 63 +#define ENONET 64 +#define ENOPKG 65 +#define EREMOTE 66 +#define ENOLINK 67 +#define EADV 68 +#define ESRMNT 69 +#define ECOMM 70 +#define EPROTO 71 +#define EMULTIHOP 72 +#define EDOTDOT 73 +#define EBADMSG 74 +#define EOVERFLOW 75 +#define ENOTUNIQ 76 +#define EBADFD 77 +#define EREMCHG 78 +#define ELIBACC 79 +#define ELIBBAD 80 +#define ELIBSCN 81 +#define ELIBMAX 82 +#define ELIBEXEC 83 +#define EILSEQ 84 +#define ERESTART 85 +#define ESTRPIPE 86 +#define EUSERS 87 +#define ENOTSOCK 88 +#define EDESTADDRREQ 89 +#define EMSGSIZE 90 +#define EPROTOTYPE 91 +#define ENOPROTOOPT 92 #define EPROTONOSUPPORT 93 #define ESOCKTNOSUPPORT 94 -#define EOPNOTSUPP 95 -#define ENOTSUP EOPNOTSUPP -#define EPFNOSUPPORT 96 -#define EAFNOSUPPORT 97 -#define EADDRINUSE 98 -#define EADDRNOTAVAIL 99 -#define ENETDOWN 100 -#define ENETUNREACH 101 -#define ENETRESET 102 -#define ECONNABORTED 103 -#define ECONNRESET 104 -#define ENOBUFS 105 -#define EISCONN 106 -#define ENOTCONN 107 -#define ESHUTDOWN 108 -#define ETOOMANYREFS 109 -#define ETIMEDOUT 110 -#define ECONNREFUSED 111 -#define EHOSTDOWN 112 -#define EHOSTUNREACH 113 -#define EALREADY 114 -#define EINPROGRESS 115 -#define ESTALE 116 -#define EUCLEAN 117 -#define ENOTNAM 118 -#define ENAVAIL 119 -#define EISNAM 120 -#define EREMOTEIO 121 -#define EDQUOT 122 -#define ENOMEDIUM 123 -#define EMEDIUMTYPE 124 -#define ECANCELED 125 -#define ENOKEY 126 -#define EKEYEXPIRED 127 -#define EKEYREVOKED 128 -#define EKEYREJECTED 129 -#define EOWNERDEAD 130 +#define EOPNOTSUPP 95 +#define ENOTSUP EOPNOTSUPP +#define EPFNOSUPPORT 96 +#define EAFNOSUPPORT 97 +#define EADDRINUSE 98 +#define EADDRNOTAVAIL 99 +#define ENETDOWN 100 +#define ENETUNREACH 101 +#define ENETRESET 102 +#define ECONNABORTED 103 +#define ECONNRESET 104 +#define ENOBUFS 105 +#define EISCONN 106 +#define ENOTCONN 107 +#define ESHUTDOWN 108 +#define ETOOMANYREFS 109 +#define ETIMEDOUT 110 +#define ECONNREFUSED 111 +#define EHOSTDOWN 112 +#define EHOSTUNREACH 113 +#define EALREADY 114 +#define EINPROGRESS 115 +#define ESTALE 116 +#define EUCLEAN 117 +#define ENOTNAM 118 +#define ENAVAIL 119 +#define EISNAM 120 +#define EREMOTEIO 121 +#define EDQUOT 122 +#define ENOMEDIUM 123 +#define EMEDIUMTYPE 124 +#define ECANCELED 125 +#define ENOKEY 126 +#define EKEYEXPIRED 127 +#define EKEYREVOKED 128 +#define EKEYREJECTED 129 +#define EOWNERDEAD 130 #define ENOTRECOVERABLE 131 -#define ERFKILL 132 -#define EHWPOISON 133 - +#define ERFKILL 132 +#define EHWPOISON 133 /* This is mlibc-specific. */ -#define EIEIO 4095 +#define EIEIO 4095 #endif /* _ABIBITS_ERRNO_H */ diff --git a/abis/linux/fcntl.h b/abis/linux/fcntl.h index 9e56ed2313..239b0c25bd 100644 --- a/abis/linux/fcntl.h +++ b/abis/linux/fcntl.h @@ -6,36 +6,36 @@ #define O_PATH 010000000 #define O_ACCMODE (03 | O_PATH) -#define O_RDONLY 00 -#define O_WRONLY 01 -#define O_RDWR 02 - -#define O_CREAT 0100 -#define O_EXCL 0200 -#define O_NOCTTY 0400 -#define O_TRUNC 01000 -#define O_APPEND 02000 -#define O_NONBLOCK 04000 -#define O_DSYNC 010000 -#define O_ASYNC 020000 -#define O_DIRECT 040000 -#define O_DIRECTORY 0200000 -#define O_NOFOLLOW 0400000 -#define O_CLOEXEC 02000000 -#define O_SYNC 04010000 -#define O_RSYNC 04010000 -#define O_LARGEFILE 0100000 -#define O_NOATIME 01000000 -#define O_TMPFILE 020000000 +#define O_RDONLY 00 +#define O_WRONLY 01 +#define O_RDWR 02 + +#define O_CREAT 0100 +#define O_EXCL 0200 +#define O_NOCTTY 0400 +#define O_TRUNC 01000 +#define O_APPEND 02000 +#define O_NONBLOCK 04000 +#define O_DSYNC 010000 +#define O_ASYNC 020000 +#define O_DIRECT 040000 +#define O_DIRECTORY 0200000 +#define O_NOFOLLOW 0400000 +#define O_CLOEXEC 02000000 +#define O_SYNC 04010000 +#define O_RSYNC 04010000 +#define O_LARGEFILE 0100000 +#define O_NOATIME 01000000 +#define O_TMPFILE 020000000 #define O_EXEC O_PATH #define O_SEARCH O_PATH -#define F_DUPFD 0 -#define F_GETFD 1 -#define F_SETFD 2 -#define F_GETFL 3 -#define F_SETFL 4 +#define F_DUPFD 0 +#define F_GETFD 1 +#define F_SETFD 2 +#define F_GETFL 3 +#define F_SETFL 4 #define F_SETOWN 8 #define F_GETOWN 9 diff --git a/abis/linux/gid_t.h b/abis/linux/gid_t.h index f513e250d2..3e356f7544 100644 --- a/abis/linux/gid_t.h +++ b/abis/linux/gid_t.h @@ -5,4 +5,3 @@ typedef unsigned int gid_t; #endif /* _ABIBITS_GID_T_H */ - diff --git a/abis/linux/in.h b/abis/linux/in.h index 39f7d88ccc..59aee5565f 100644 --- a/abis/linux/in.h +++ b/abis/linux/in.h @@ -1,9 +1,9 @@ #ifndef _ABIBITS_IN_H #define _ABIBITS_IN_H +#include #include #include -#include #include #ifdef __cplusplus @@ -33,11 +33,11 @@ struct in6_addr { #define s6_addr32 __in6_union.__s6_addr32 struct sockaddr_in6 { - sa_family_t sin6_family; - in_port_t sin6_port; - uint32_t sin6_flowinfo; + sa_family_t sin6_family; + in_port_t sin6_port; + uint32_t sin6_flowinfo; struct in6_addr sin6_addr; - uint32_t sin6_scope_id; + uint32_t sin6_scope_id; }; #define MCAST_INCLUDE 1 @@ -61,7 +61,7 @@ struct ip_mreqn { struct ipv6_mreq { struct in6_addr ipv6mr_multiaddr; - unsigned ipv6mr_interface; + unsigned ipv6mr_interface; }; struct in_pktinfo { @@ -90,58 +90,64 @@ struct group_source_req { } #endif -#define INADDR_ANY ((in_addr_t) 0x00000000) -#define INADDR_BROADCAST ((in_addr_t) 0xffffffff) -#define INADDR_NONE ((in_addr_t) 0xffffffff) -#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001) - -#define INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000) -#define INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001) -#define INADDR_ALLRTRS_GROUP ((in_addr_t) 0xe0000002) -#define INADDR_ALLSNOOPERS_GROUP ((in_addr_t) 0xe000006a) -#define INADDR_MAX_LOCAL_GROUP ((in_addr_t) 0xe00000ff) - -#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } -#define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } - -#define INET_ADDRSTRLEN 16 +#define INADDR_ANY ((in_addr_t)0x00000000) +#define INADDR_BROADCAST ((in_addr_t)0xffffffff) +#define INADDR_NONE ((in_addr_t)0xffffffff) +#define INADDR_LOOPBACK ((in_addr_t)0x7f000001) + +#define INADDR_UNSPEC_GROUP ((in_addr_t)0xe0000000) +#define INADDR_ALLHOSTS_GROUP ((in_addr_t)0xe0000001) +#define INADDR_ALLRTRS_GROUP ((in_addr_t)0xe0000002) +#define INADDR_ALLSNOOPERS_GROUP ((in_addr_t)0xe000006a) +#define INADDR_MAX_LOCAL_GROUP ((in_addr_t)0xe00000ff) + +#define IN6ADDR_ANY_INIT \ + { \ + { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } \ + } +#define IN6ADDR_LOOPBACK_INIT \ + { \ + { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } \ + } + +#define INET_ADDRSTRLEN 16 #define INET6_ADDRSTRLEN 46 #define IPPORT_RESERVED 1024 -#define IPPROTO_IP 0 -#define IPPROTO_HOPOPTS 0 -#define IPPROTO_ICMP 1 -#define IPPROTO_IGMP 2 -#define IPPROTO_IPIP 4 -#define IPPROTO_TCP 6 -#define IPPROTO_EGP 8 -#define IPPROTO_PUP 12 -#define IPPROTO_UDP 17 -#define IPPROTO_IDP 22 -#define IPPROTO_TP 29 -#define IPPROTO_DCCP 33 -#define IPPROTO_IPV6 41 -#define IPPROTO_ROUTING 43 +#define IPPROTO_IP 0 +#define IPPROTO_HOPOPTS 0 +#define IPPROTO_ICMP 1 +#define IPPROTO_IGMP 2 +#define IPPROTO_IPIP 4 +#define IPPROTO_TCP 6 +#define IPPROTO_EGP 8 +#define IPPROTO_PUP 12 +#define IPPROTO_UDP 17 +#define IPPROTO_IDP 22 +#define IPPROTO_TP 29 +#define IPPROTO_DCCP 33 +#define IPPROTO_IPV6 41 +#define IPPROTO_ROUTING 43 #define IPPROTO_FRAGMENT 44 -#define IPPROTO_RSVP 46 -#define IPPROTO_GRE 47 -#define IPPROTO_ESP 50 -#define IPPROTO_AH 51 -#define IPPROTO_ICMPV6 58 -#define IPPROTO_NONE 59 -#define IPPROTO_DSTOPTS 60 -#define IPPROTO_MTP 92 -#define IPPROTO_BEETPH 94 -#define IPPROTO_ENCAP 98 -#define IPPROTO_PIM 103 -#define IPPROTO_COMP 108 -#define IPPROTO_SCTP 132 -#define IPPROTO_MH 135 -#define IPPROTO_UDPLITE 136 -#define IPPROTO_MPLS 137 -#define IPPROTO_RAW 255 -#define IPPROTO_MAX 256 +#define IPPROTO_RSVP 46 +#define IPPROTO_GRE 47 +#define IPPROTO_ESP 50 +#define IPPROTO_AH 51 +#define IPPROTO_ICMPV6 58 +#define IPPROTO_NONE 59 +#define IPPROTO_DSTOPTS 60 +#define IPPROTO_MTP 92 +#define IPPROTO_BEETPH 94 +#define IPPROTO_ENCAP 98 +#define IPPROTO_PIM 103 +#define IPPROTO_COMP 108 +#define IPPROTO_SCTP 132 +#define IPPROTO_MH 135 +#define IPPROTO_UDPLITE 136 +#define IPPROTO_MPLS 137 +#define IPPROTO_RAW 255 +#define IPPROTO_MAX 256 #define IP_TOS 1 #define IP_TTL 2 @@ -180,7 +186,7 @@ struct group_source_req { #define IPV6_RECVHOPLIMIT 51 #define IPV6_HOPLIMIT 52 -#define IPV6_RECVTCLASS 66 +#define IPV6_RECVTCLASS 66 #define IPV6_TCLASS 67 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP diff --git a/abis/linux/ino_t.h b/abis/linux/ino_t.h index edf795dcc7..c3f703563e 100644 --- a/abis/linux/ino_t.h +++ b/abis/linux/ino_t.h @@ -7,4 +7,3 @@ typedef __mlibc_uint64 ino_t; #endif /* _ABIBITS_INO_T_H */ - diff --git a/abis/linux/mode_t.h b/abis/linux/mode_t.h index 8deed27f19..fc4518075d 100644 --- a/abis/linux/mode_t.h +++ b/abis/linux/mode_t.h @@ -5,4 +5,3 @@ typedef unsigned int mode_t; #endif /* _ABIBITS_MODE_T_H */ - diff --git a/abis/linux/mqueue.h b/abis/linux/mqueue.h index 1e2d3eb83d..f18210ca71 100644 --- a/abis/linux/mqueue.h +++ b/abis/linux/mqueue.h @@ -18,4 +18,3 @@ struct mq_attr { #endif #endif /* _ABIBITS_MQUEUE_H */ - diff --git a/abis/linux/msg.h b/abis/linux/msg.h index 577456c918..cc66efde2e 100644 --- a/abis/linux/msg.h +++ b/abis/linux/msg.h @@ -1,10 +1,10 @@ #ifndef _ABIBITS_MSG_H #define _ABIBITS_MSG_H -#include +#include #include #include -#include +#include #ifdef __cplusplus extern "C" { @@ -42,4 +42,3 @@ struct msqid64_ds { #endif #endif /* _ABIBITS_MSG_H */ - diff --git a/abis/linux/nlink_t.h b/abis/linux/nlink_t.h index eb15553cd5..bb80b585fa 100644 --- a/abis/linux/nlink_t.h +++ b/abis/linux/nlink_t.h @@ -5,4 +5,3 @@ typedef unsigned long nlink_t; #endif /* _ABIBITS_NLINK_T_H */ - diff --git a/abis/linux/pid_t.h b/abis/linux/pid_t.h index 9591edb35d..68ead168a7 100644 --- a/abis/linux/pid_t.h +++ b/abis/linux/pid_t.h @@ -5,4 +5,3 @@ typedef int pid_t; #endif /* _ABIBITS_PID_T_H */ - diff --git a/abis/linux/signal.h b/abis/linux/signal.h index 65e575b895..54018938ff 100644 --- a/abis/linux/signal.h +++ b/abis/linux/signal.h @@ -1,11 +1,11 @@ #ifndef _ABIBITS_SIGNAL_H #define _ABIBITS_SIGNAL_H -#include -#include #include #include #include +#include +#include #define POLL_IN 1 #define POLL_OUT 2 @@ -24,7 +24,7 @@ union sigval { typedef struct { int si_signo, si_errno, si_code; union { - char __pad[128 - 2*sizeof(int) - sizeof(long)]; + char __pad[128 - 2 * sizeof(int) - sizeof(long)]; struct { union { struct { @@ -66,26 +66,26 @@ typedef struct { } __sigsys; } __si_fields; } siginfo_t; -#define si_pid __si_fields.__si_common.__first.__piduid.si_pid -#define si_uid __si_fields.__si_common.__first.__piduid.si_uid -#define si_status __si_fields.__si_common.__second.__sigchld.si_status -#define si_utime __si_fields.__si_common.__second.__sigchld.si_utime -#define si_stime __si_fields.__si_common.__second.__sigchld.si_stime -#define si_value __si_fields.__si_common.__second.si_value -#define si_addr __si_fields.__sigfault.si_addr +#define si_pid __si_fields.__si_common.__first.__piduid.si_pid +#define si_uid __si_fields.__si_common.__first.__piduid.si_uid +#define si_status __si_fields.__si_common.__second.__sigchld.si_status +#define si_utime __si_fields.__si_common.__second.__sigchld.si_utime +#define si_stime __si_fields.__si_common.__second.__sigchld.si_stime +#define si_value __si_fields.__si_common.__second.si_value +#define si_addr __si_fields.__sigfault.si_addr #define si_addr_lsb __si_fields.__sigfault.si_addr_lsb -#define si_lower __si_fields.__sigfault.__first.__addr_bnd.si_lower -#define si_upper __si_fields.__sigfault.__first.__addr_bnd.si_upper -#define si_pkey __si_fields.__sigfault.__first.si_pkey -#define si_band __si_fields.__sigpoll.si_band -#define si_fd __si_fields.__sigpoll.si_fd +#define si_lower __si_fields.__sigfault.__first.__addr_bnd.si_lower +#define si_upper __si_fields.__sigfault.__first.__addr_bnd.si_upper +#define si_pkey __si_fields.__sigfault.__first.si_pkey +#define si_band __si_fields.__sigpoll.si_band +#define si_fd __si_fields.__sigpoll.si_fd #define si_timerid __si_fields.__si_common.__first.__timer.si_timerid #define si_overrun __si_fields.__si_common.__first.__timer.si_overrun -#define si_ptr si_value.sival_ptr -#define si_int si_value.sival_int +#define si_ptr si_value.sival_ptr +#define si_int si_value.sival_int #define si_call_addr __si_fields.__sigsys.si_call_addr #define si_syscall __si_fields.__sigsys.si_syscall -#define si_arch __si_fields.__sigsys.si_arch +#define si_arch __si_fields.__sigsys.si_arch /* Required for sys_sigaction sysdep. */ #define SA_NOCLDSTOP 1 @@ -102,7 +102,7 @@ extern "C" { #endif /* Argument for signal() */ -typedef void (*__sighandler) (int); +typedef void (*__sighandler)(int); #define SIG_ERR ((__sighandler)(void *)(-1)) #define SIG_DFL ((__sighandler)(void *)(0)) @@ -129,30 +129,30 @@ typedef struct { #define SIG_UNBLOCK 1 #define SIG_SETMASK 2 -#define SIGHUP 1 -#define SIGQUIT 3 -#define SIGTRAP 5 -#define SIGIOT SIGABRT -#define SIGBUS 7 -#define SIGKILL 9 -#define SIGUSR1 10 -#define SIGUSR2 12 -#define SIGPIPE 13 -#define SIGALRM 14 +#define SIGHUP 1 +#define SIGQUIT 3 +#define SIGTRAP 5 +#define SIGIOT SIGABRT +#define SIGBUS 7 +#define SIGKILL 9 +#define SIGUSR1 10 +#define SIGUSR2 12 +#define SIGPIPE 13 +#define SIGALRM 14 #define SIGSTKFLT 16 -#define SIGCHLD 17 -#define SIGCONT 18 -#define SIGSTOP 19 -#define SIGTSTP 20 -#define SIGTTIN 21 -#define SIGTTOU 22 -#define SIGURG 23 -#define SIGXCPU 24 -#define SIGXFSZ 25 +#define SIGCHLD 17 +#define SIGCONT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +#define SIGTTIN 21 +#define SIGTTOU 22 +#define SIGURG 23 +#define SIGXCPU 24 +#define SIGXFSZ 25 #define SIGVTALRM 26 -#define SIGWINCH 28 -#define SIGPOLL 29 -#define SIGSYS 31 +#define SIGWINCH 28 +#define SIGPOLL 29 +#define SIGSYS 31 #define SIGUNUSED SIGSYS #define SIGCANCEL 32 @@ -352,17 +352,17 @@ typedef struct __ucontext { #define NGREG 32 enum { - REG_PC = 0, + REG_PC = 0, #define REG_PC REG_PC - REG_RA = 1, + REG_RA = 1, #define REG_RA REG_RA - REG_SP = 2, + REG_SP = 2, #define REG_SP REG_SP - REG_TP = 4, + REG_TP = 4, #define REG_TP REG_TP - REG_S0 = 8, + REG_S0 = 8, #define REG_S0 REG_S0 - REG_A0 = 10 + REG_A0 = 10 #define REG_A0 REG_A0 }; @@ -397,7 +397,7 @@ typedef struct sigcontext { typedef struct __ucontext { unsigned long uc_flags; - struct ucontext *uc_link; + struct ucontext *uc_link; stack_t uc_stack; sigset_t uc_sigmask; #pragma GCC diagnostic push @@ -407,7 +407,7 @@ typedef struct __ucontext { mcontext_t uc_mcontext; } ucontext_t; -#elif defined (__aarch64__) +#elif defined(__aarch64__) #define NGREG 34 @@ -449,38 +449,29 @@ struct sve_context { uint16_t vl; uint16_t __reserved[3]; }; -#define SVE_VQ_BYTES 16 -#define SVE_VQ_MIN 1 -#define SVE_VQ_MAX 512 -#define SVE_VL_MIN (SVE_VQ_MIN * SVE_VQ_BYTES) -#define SVE_VL_MAX (SVE_VQ_MAX * SVE_VQ_BYTES) -#define SVE_NUM_ZREGS 32 -#define SVE_NUM_PREGS 16 -#define sve_vl_valid(vl) \ - ((vl) % SVE_VQ_BYTES == 0 && (vl) >= SVE_VL_MIN && (vl) <= SVE_VL_MAX) -#define sve_vq_from_vl(vl) ((vl) / SVE_VQ_BYTES) -#define sve_vl_from_vq(vq) ((vq) * SVE_VQ_BYTES) -#define SVE_SIG_ZREG_SIZE(vq) ((unsigned)(vq) * SVE_VQ_BYTES) -#define SVE_SIG_PREG_SIZE(vq) ((unsigned)(vq) * (SVE_VQ_BYTES / 8)) -#define SVE_SIG_FFR_SIZE(vq) SVE_SIG_PREG_SIZE(vq) -#define SVE_SIG_REGS_OFFSET \ - ((sizeof(struct sve_context) + (SVE_VQ_BYTES - 1)) \ - / SVE_VQ_BYTES * SVE_VQ_BYTES) -#define SVE_SIG_ZREGS_OFFSET SVE_SIG_REGS_OFFSET -#define SVE_SIG_ZREG_OFFSET(vq, n) \ - (SVE_SIG_ZREGS_OFFSET + SVE_SIG_ZREG_SIZE(vq) * (n)) -#define SVE_SIG_ZREGS_SIZE(vq) \ - (SVE_SIG_ZREG_OFFSET(vq, SVE_NUM_ZREGS) - SVE_SIG_ZREGS_OFFSET) -#define SVE_SIG_PREGS_OFFSET(vq) \ - (SVE_SIG_ZREGS_OFFSET + SVE_SIG_ZREGS_SIZE(vq)) -#define SVE_SIG_PREG_OFFSET(vq, n) \ - (SVE_SIG_PREGS_OFFSET(vq) + SVE_SIG_PREG_SIZE(vq) * (n)) -#define SVE_SIG_PREGS_SIZE(vq) \ - (SVE_SIG_PREG_OFFSET(vq, SVE_NUM_PREGS) - SVE_SIG_PREGS_OFFSET(vq)) -#define SVE_SIG_FFR_OFFSET(vq) \ - (SVE_SIG_PREGS_OFFSET(vq) + SVE_SIG_PREGS_SIZE(vq)) -#define SVE_SIG_REGS_SIZE(vq) \ - (SVE_SIG_FFR_OFFSET(vq) + SVE_SIG_FFR_SIZE(vq) - SVE_SIG_REGS_OFFSET) +#define SVE_VQ_BYTES 16 +#define SVE_VQ_MIN 1 +#define SVE_VQ_MAX 512 +#define SVE_VL_MIN (SVE_VQ_MIN * SVE_VQ_BYTES) +#define SVE_VL_MAX (SVE_VQ_MAX * SVE_VQ_BYTES) +#define SVE_NUM_ZREGS 32 +#define SVE_NUM_PREGS 16 +#define sve_vl_valid(vl) ((vl) % SVE_VQ_BYTES == 0 && (vl) >= SVE_VL_MIN && (vl) <= SVE_VL_MAX) +#define sve_vq_from_vl(vl) ((vl) / SVE_VQ_BYTES) +#define sve_vl_from_vq(vq) ((vq) * SVE_VQ_BYTES) +#define SVE_SIG_ZREG_SIZE(vq) ((unsigned)(vq) * SVE_VQ_BYTES) +#define SVE_SIG_PREG_SIZE(vq) ((unsigned)(vq) * (SVE_VQ_BYTES / 8)) +#define SVE_SIG_FFR_SIZE(vq) SVE_SIG_PREG_SIZE(vq) +#define SVE_SIG_REGS_OFFSET \ + ((sizeof(struct sve_context) + (SVE_VQ_BYTES - 1)) / SVE_VQ_BYTES * SVE_VQ_BYTES) +#define SVE_SIG_ZREGS_OFFSET SVE_SIG_REGS_OFFSET +#define SVE_SIG_ZREG_OFFSET(vq, n) (SVE_SIG_ZREGS_OFFSET + SVE_SIG_ZREG_SIZE(vq) * (n)) +#define SVE_SIG_ZREGS_SIZE(vq) (SVE_SIG_ZREG_OFFSET(vq, SVE_NUM_ZREGS) - SVE_SIG_ZREGS_OFFSET) +#define SVE_SIG_PREGS_OFFSET(vq) (SVE_SIG_ZREGS_OFFSET + SVE_SIG_ZREGS_SIZE(vq)) +#define SVE_SIG_PREG_OFFSET(vq, n) (SVE_SIG_PREGS_OFFSET(vq) + SVE_SIG_PREG_SIZE(vq) * (n)) +#define SVE_SIG_PREGS_SIZE(vq) (SVE_SIG_PREG_OFFSET(vq, SVE_NUM_PREGS) - SVE_SIG_PREGS_OFFSET(vq)) +#define SVE_SIG_FFR_OFFSET(vq) (SVE_SIG_PREGS_OFFSET(vq) + SVE_SIG_PREGS_SIZE(vq)) +#define SVE_SIG_REGS_SIZE(vq) (SVE_SIG_FFR_OFFSET(vq) + SVE_SIG_FFR_SIZE(vq) - SVE_SIG_REGS_OFFSET) #define SVE_SIG_CONTEXT_SIZE(vq) (SVE_SIG_REGS_OFFSET + SVE_SIG_REGS_SIZE(vq)) typedef struct __ucontext { @@ -491,7 +482,7 @@ typedef struct __ucontext { mcontext_t uc_mcontext; } ucontext_t; -#elif defined (__m68k__) +#elif defined(__m68k__) /* taken from musl */ @@ -580,7 +571,6 @@ typedef struct __ucontext { sigset_t uc_sigmask; } ucontext_t; - #else #error "Missing architecture specific code." #endif diff --git a/abis/linux/socket.h b/abis/linux/socket.h index 78e1dc3228..d4a2274f5b 100644 --- a/abis/linux/socket.h +++ b/abis/linux/socket.h @@ -1,9 +1,9 @@ #ifndef _ABIBITS_SOCKET_H #define _ABIBITS_SOCKET_H -#include #include #include +#include #ifdef __cplusplus extern "C" { @@ -29,7 +29,7 @@ struct sockaddr_storage { struct mmsghdr { struct msghdr msg_hdr; - unsigned int msg_len; + unsigned int msg_len; }; struct cmsghdr { @@ -50,251 +50,251 @@ struct cmsghdr { #define SHUT_RDWR 2 #ifndef SOCK_STREAM -#define SOCK_STREAM 1 -#define SOCK_DGRAM 2 +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 #endif -#define SOCK_RAW 3 -#define SOCK_RDM 4 +#define SOCK_RAW 3 +#define SOCK_RDM 4 #define SOCK_SEQPACKET 5 -#define SOCK_DCCP 6 -#define SOCK_PACKET 10 +#define SOCK_DCCP 6 +#define SOCK_PACKET 10 #ifndef SOCK_CLOEXEC -#define SOCK_CLOEXEC 02000000 -#define SOCK_NONBLOCK 04000 +#define SOCK_CLOEXEC 02000000 +#define SOCK_NONBLOCK 04000 #endif -#define PF_UNSPEC 0 -#define PF_LOCAL 1 -#define PF_UNIX PF_LOCAL -#define PF_FILE PF_LOCAL -#define PF_INET 2 -#define PF_AX25 3 -#define PF_IPX 4 -#define PF_APPLETALK 5 -#define PF_NETROM 6 -#define PF_BRIDGE 7 -#define PF_ATMPVC 8 -#define PF_X25 9 -#define PF_INET6 10 -#define PF_ROSE 11 -#define PF_DECnet 12 -#define PF_NETBEUI 13 -#define PF_SECURITY 14 -#define PF_KEY 15 -#define PF_NETLINK 16 -#define PF_ROUTE PF_NETLINK -#define PF_PACKET 17 -#define PF_ASH 18 -#define PF_ECONET 19 -#define PF_ATMSVC 20 -#define PF_RDS 21 -#define PF_SNA 22 -#define PF_IRDA 23 -#define PF_PPPOX 24 -#define PF_WANPIPE 25 -#define PF_LLC 26 -#define PF_IB 27 -#define PF_MPLS 28 -#define PF_CAN 29 -#define PF_TIPC 30 -#define PF_BLUETOOTH 31 -#define PF_IUCV 32 -#define PF_RXRPC 33 -#define PF_ISDN 34 -#define PF_PHONET 35 -#define PF_IEEE802154 36 -#define PF_CAIF 37 -#define PF_ALG 38 -#define PF_NFC 39 -#define PF_VSOCK 40 -#define PF_KCM 41 -#define PF_QIPCRTR 42 -#define PF_SMC 43 -#define PF_XDP 44 -#define PF_MAX 45 +#define PF_UNSPEC 0 +#define PF_LOCAL 1 +#define PF_UNIX PF_LOCAL +#define PF_FILE PF_LOCAL +#define PF_INET 2 +#define PF_AX25 3 +#define PF_IPX 4 +#define PF_APPLETALK 5 +#define PF_NETROM 6 +#define PF_BRIDGE 7 +#define PF_ATMPVC 8 +#define PF_X25 9 +#define PF_INET6 10 +#define PF_ROSE 11 +#define PF_DECnet 12 +#define PF_NETBEUI 13 +#define PF_SECURITY 14 +#define PF_KEY 15 +#define PF_NETLINK 16 +#define PF_ROUTE PF_NETLINK +#define PF_PACKET 17 +#define PF_ASH 18 +#define PF_ECONET 19 +#define PF_ATMSVC 20 +#define PF_RDS 21 +#define PF_SNA 22 +#define PF_IRDA 23 +#define PF_PPPOX 24 +#define PF_WANPIPE 25 +#define PF_LLC 26 +#define PF_IB 27 +#define PF_MPLS 28 +#define PF_CAN 29 +#define PF_TIPC 30 +#define PF_BLUETOOTH 31 +#define PF_IUCV 32 +#define PF_RXRPC 33 +#define PF_ISDN 34 +#define PF_PHONET 35 +#define PF_IEEE802154 36 +#define PF_CAIF 37 +#define PF_ALG 38 +#define PF_NFC 39 +#define PF_VSOCK 40 +#define PF_KCM 41 +#define PF_QIPCRTR 42 +#define PF_SMC 43 +#define PF_XDP 44 +#define PF_MAX 45 -#define AF_UNSPEC PF_UNSPEC -#define AF_LOCAL PF_LOCAL -#define AF_UNIX AF_LOCAL -#define AF_FILE AF_LOCAL -#define AF_INET PF_INET -#define AF_AX25 PF_AX25 -#define AF_IPX PF_IPX -#define AF_APPLETALK PF_APPLETALK -#define AF_NETROM PF_NETROM -#define AF_BRIDGE PF_BRIDGE -#define AF_ATMPVC PF_ATMPVC -#define AF_X25 PF_X25 -#define AF_INET6 PF_INET6 -#define AF_ROSE PF_ROSE -#define AF_DECnet PF_DECnet -#define AF_NETBEUI PF_NETBEUI -#define AF_SECURITY PF_SECURITY -#define AF_KEY PF_KEY -#define AF_NETLINK PF_NETLINK -#define AF_ROUTE PF_ROUTE -#define AF_PACKET PF_PACKET -#define AF_ASH PF_ASH -#define AF_ECONET PF_ECONET -#define AF_ATMSVC PF_ATMSVC -#define AF_RDS PF_RDS -#define AF_SNA PF_SNA -#define AF_IRDA PF_IRDA -#define AF_PPPOX PF_PPPOX -#define AF_WANPIPE PF_WANPIPE -#define AF_LLC PF_LLC -#define AF_IB PF_IB -#define AF_MPLS PF_MPLS -#define AF_CAN PF_CAN -#define AF_TIPC PF_TIPC -#define AF_BLUETOOTH PF_BLUETOOTH -#define AF_IUCV PF_IUCV -#define AF_RXRPC PF_RXRPC -#define AF_ISDN PF_ISDN -#define AF_PHONET PF_PHONET -#define AF_IEEE802154 PF_IEEE802154 -#define AF_CAIF PF_CAIF -#define AF_ALG PF_ALG -#define AF_NFC PF_NFC -#define AF_VSOCK PF_VSOCK -#define AF_KCM PF_KCM -#define AF_QIPCRTR PF_QIPCRTR -#define AF_SMC PF_SMC -#define AF_XDP PF_XDP -#define AF_MAX PF_MAX +#define AF_UNSPEC PF_UNSPEC +#define AF_LOCAL PF_LOCAL +#define AF_UNIX AF_LOCAL +#define AF_FILE AF_LOCAL +#define AF_INET PF_INET +#define AF_AX25 PF_AX25 +#define AF_IPX PF_IPX +#define AF_APPLETALK PF_APPLETALK +#define AF_NETROM PF_NETROM +#define AF_BRIDGE PF_BRIDGE +#define AF_ATMPVC PF_ATMPVC +#define AF_X25 PF_X25 +#define AF_INET6 PF_INET6 +#define AF_ROSE PF_ROSE +#define AF_DECnet PF_DECnet +#define AF_NETBEUI PF_NETBEUI +#define AF_SECURITY PF_SECURITY +#define AF_KEY PF_KEY +#define AF_NETLINK PF_NETLINK +#define AF_ROUTE PF_ROUTE +#define AF_PACKET PF_PACKET +#define AF_ASH PF_ASH +#define AF_ECONET PF_ECONET +#define AF_ATMSVC PF_ATMSVC +#define AF_RDS PF_RDS +#define AF_SNA PF_SNA +#define AF_IRDA PF_IRDA +#define AF_PPPOX PF_PPPOX +#define AF_WANPIPE PF_WANPIPE +#define AF_LLC PF_LLC +#define AF_IB PF_IB +#define AF_MPLS PF_MPLS +#define AF_CAN PF_CAN +#define AF_TIPC PF_TIPC +#define AF_BLUETOOTH PF_BLUETOOTH +#define AF_IUCV PF_IUCV +#define AF_RXRPC PF_RXRPC +#define AF_ISDN PF_ISDN +#define AF_PHONET PF_PHONET +#define AF_IEEE802154 PF_IEEE802154 +#define AF_CAIF PF_CAIF +#define AF_ALG PF_ALG +#define AF_NFC PF_NFC +#define AF_VSOCK PF_VSOCK +#define AF_KCM PF_KCM +#define AF_QIPCRTR PF_QIPCRTR +#define AF_SMC PF_SMC +#define AF_XDP PF_XDP +#define AF_MAX PF_MAX -#define SO_DEBUG 1 -#define SO_REUSEADDR 2 -#define SO_TYPE 3 -#define SO_ERROR 4 -#define SO_DONTROUTE 5 -#define SO_BROADCAST 6 -#define SO_SNDBUF 7 -#define SO_RCVBUF 8 -#define SO_KEEPALIVE 9 -#define SO_OOBINLINE 10 -#define SO_NO_CHECK 11 -#define SO_PRIORITY 12 -#define SO_LINGER 13 -#define SO_BSDCOMPAT 14 -#define SO_REUSEPORT 15 -#define SO_PASSCRED 16 -#define SO_PEERCRED 17 -#define SO_RCVLOWAT 18 -#define SO_SNDLOWAT 19 -#define SO_ACCEPTCONN 30 -#define SO_PEERSEC 31 -#define SO_SNDBUFFORCE 32 -#define SO_RCVBUFFORCE 33 -#define SO_PROTOCOL 38 -#define SO_DOMAIN 39 +#define SO_DEBUG 1 +#define SO_REUSEADDR 2 +#define SO_TYPE 3 +#define SO_ERROR 4 +#define SO_DONTROUTE 5 +#define SO_BROADCAST 6 +#define SO_SNDBUF 7 +#define SO_RCVBUF 8 +#define SO_KEEPALIVE 9 +#define SO_OOBINLINE 10 +#define SO_NO_CHECK 11 +#define SO_PRIORITY 12 +#define SO_LINGER 13 +#define SO_BSDCOMPAT 14 +#define SO_REUSEPORT 15 +#define SO_PASSCRED 16 +#define SO_PEERCRED 17 +#define SO_RCVLOWAT 18 +#define SO_SNDLOWAT 19 +#define SO_ACCEPTCONN 30 +#define SO_PEERSEC 31 +#define SO_SNDBUFFORCE 32 +#define SO_RCVBUFFORCE 33 +#define SO_PROTOCOL 38 +#define SO_DOMAIN 39 -#define SO_RCVTIMEO 20 -#define SO_SNDTIMEO 21 +#define SO_RCVTIMEO 20 +#define SO_SNDTIMEO 21 -#define SO_TIMESTAMP 29 -#define SO_TIMESTAMPNS 35 +#define SO_TIMESTAMP 29 +#define SO_TIMESTAMPNS 35 #define SO_TIMESTAMPING 37 -#define SO_SECURITY_AUTHENTICATION 22 -#define SO_SECURITY_ENCRYPTION_TRANSPORT 23 -#define SO_SECURITY_ENCRYPTION_NETWORK 24 +#define SO_SECURITY_AUTHENTICATION 22 +#define SO_SECURITY_ENCRYPTION_TRANSPORT 23 +#define SO_SECURITY_ENCRYPTION_NETWORK 24 #define SO_BINDTODEVICE 25 -#define SO_ATTACH_FILTER 26 -#define SO_DETACH_FILTER 27 -#define SO_GET_FILTER SO_ATTACH_FILTER +#define SO_ATTACH_FILTER 26 +#define SO_DETACH_FILTER 27 +#define SO_GET_FILTER SO_ATTACH_FILTER -#define SO_PEERNAME 28 -#define SCM_TIMESTAMP SO_TIMESTAMP -#define SO_PASSSEC 34 -#define SCM_TIMESTAMPNS SO_TIMESTAMPNS -#define SO_MARK 36 -#define SCM_TIMESTAMPING SO_TIMESTAMPING -#define SO_RXQ_OVFL 40 -#define SO_WIFI_STATUS 41 -#define SCM_WIFI_STATUS SO_WIFI_STATUS -#define SO_PEEK_OFF 42 -#define SO_NOFCS 43 -#define SO_LOCK_FILTER 44 -#define SO_SELECT_ERR_QUEUE 45 -#define SO_BUSY_POLL 46 -#define SO_MAX_PACING_RATE 47 -#define SO_BPF_EXTENSIONS 48 -#define SO_INCOMING_CPU 49 -#define SO_ATTACH_BPF 50 -#define SO_DETACH_BPF SO_DETACH_FILTER +#define SO_PEERNAME 28 +#define SCM_TIMESTAMP SO_TIMESTAMP +#define SO_PASSSEC 34 +#define SCM_TIMESTAMPNS SO_TIMESTAMPNS +#define SO_MARK 36 +#define SCM_TIMESTAMPING SO_TIMESTAMPING +#define SO_RXQ_OVFL 40 +#define SO_WIFI_STATUS 41 +#define SCM_WIFI_STATUS SO_WIFI_STATUS +#define SO_PEEK_OFF 42 +#define SO_NOFCS 43 +#define SO_LOCK_FILTER 44 +#define SO_SELECT_ERR_QUEUE 45 +#define SO_BUSY_POLL 46 +#define SO_MAX_PACING_RATE 47 +#define SO_BPF_EXTENSIONS 48 +#define SO_INCOMING_CPU 49 +#define SO_ATTACH_BPF 50 +#define SO_DETACH_BPF SO_DETACH_FILTER #define SO_ATTACH_REUSEPORT_CBPF 51 #define SO_ATTACH_REUSEPORT_EBPF 52 -#define SO_CNX_ADVICE 53 +#define SO_CNX_ADVICE 53 #define SCM_TIMESTAMPING_OPT_STATS 54 -#define SO_MEMINFO 55 -#define SO_INCOMING_NAPI_ID 56 -#define SO_COOKIE 57 +#define SO_MEMINFO 55 +#define SO_INCOMING_NAPI_ID 56 +#define SO_COOKIE 57 #define SCM_TIMESTAMPING_PKTINFO 58 -#define SO_PEERGROUPS 59 -#define SO_ZEROCOPY 60 -#define SO_TXTIME 61 -#define SCM_TXTIME SO_TXTIME -#define SO_BINDTOIFINDEX 62 +#define SO_PEERGROUPS 59 +#define SO_ZEROCOPY 60 +#define SO_TXTIME 61 +#define SCM_TXTIME SO_TXTIME +#define SO_BINDTOIFINDEX 62 #define SO_DETACH_REUSEPORT_BPF 68 -#define SOL_SOCKET 1 +#define SOL_SOCKET 1 -#define SOL_IP 0 -#define SOL_IPV6 41 -#define SOL_ICMPV6 58 +#define SOL_IP 0 +#define SOL_IPV6 41 +#define SOL_ICMPV6 58 -#define SOL_RAW 255 -#define SOL_DECNET 261 -#define SOL_X25 262 -#define SOL_PACKET 263 -#define SOL_ATM 264 -#define SOL_AAL 265 -#define SOL_IRDA 266 -#define SOL_NETBEUI 267 -#define SOL_LLC 268 -#define SOL_DCCP 269 -#define SOL_NETLINK 270 -#define SOL_TIPC 271 -#define SOL_RXRPC 272 -#define SOL_PPPOL2TP 273 -#define SOL_BLUETOOTH 274 -#define SOL_PNPIPE 275 -#define SOL_RDS 276 -#define SOL_IUCV 277 -#define SOL_CAIF 278 -#define SOL_ALG 279 -#define SOL_NFC 280 -#define SOL_KCM 281 -#define SOL_TLS 282 -#define SOL_XDP 283 +#define SOL_RAW 255 +#define SOL_DECNET 261 +#define SOL_X25 262 +#define SOL_PACKET 263 +#define SOL_ATM 264 +#define SOL_AAL 265 +#define SOL_IRDA 266 +#define SOL_NETBEUI 267 +#define SOL_LLC 268 +#define SOL_DCCP 269 +#define SOL_NETLINK 270 +#define SOL_TIPC 271 +#define SOL_RXRPC 272 +#define SOL_PPPOL2TP 273 +#define SOL_BLUETOOTH 274 +#define SOL_PNPIPE 275 +#define SOL_RDS 276 +#define SOL_IUCV 277 +#define SOL_CAIF 278 +#define SOL_ALG 279 +#define SOL_NFC 280 +#define SOL_KCM 281 +#define SOL_TLS 282 +#define SOL_XDP 283 -#define SOMAXCONN 128 +#define SOMAXCONN 128 -#define MSG_OOB 0x0001 -#define MSG_PEEK 0x0002 +#define MSG_OOB 0x0001 +#define MSG_PEEK 0x0002 #define MSG_DONTROUTE 0x0004 -#define MSG_CTRUNC 0x0008 -#define MSG_PROXY 0x0010 -#define MSG_TRUNC 0x0020 -#define MSG_DONTWAIT 0x0040 -#define MSG_EOR 0x0080 -#define MSG_WAITALL 0x0100 -#define MSG_FIN 0x0200 -#define MSG_SYN 0x0400 -#define MSG_CONFIRM 0x0800 -#define MSG_RST 0x1000 -#define MSG_ERRQUEUE 0x2000 -#define MSG_NOSIGNAL 0x4000 -#define MSG_MORE 0x8000 +#define MSG_CTRUNC 0x0008 +#define MSG_PROXY 0x0010 +#define MSG_TRUNC 0x0020 +#define MSG_DONTWAIT 0x0040 +#define MSG_EOR 0x0080 +#define MSG_WAITALL 0x0100 +#define MSG_FIN 0x0200 +#define MSG_SYN 0x0400 +#define MSG_CONFIRM 0x0800 +#define MSG_RST 0x1000 +#define MSG_ERRQUEUE 0x2000 +#define MSG_NOSIGNAL 0x4000 +#define MSG_MORE 0x8000 #define MSG_WAITFORONE 0x10000 -#define MSG_BATCH 0x40000 -#define MSG_ZEROCOPY 0x4000000 -#define MSG_FASTOPEN 0x20000000 +#define MSG_BATCH 0x40000 +#define MSG_ZEROCOPY 0x4000000 +#define MSG_FASTOPEN 0x20000000 #define MSG_CMSG_CLOEXEC 0x40000000 #endif diff --git a/abis/linux/stat.h b/abis/linux/stat.h index c4b50abc38..aeddf88b13 100644 --- a/abis/linux/stat.h +++ b/abis/linux/stat.h @@ -1,17 +1,17 @@ #ifndef _ABIBITS_STAT_H #define _ABIBITS_STAT_H -#include -#include -#include -#include +#include +#include #include +#include #include -#include -#include +#include #include +#include #include #include +#include #define S_IFMT 0x0F000 #define S_IFBLK 0x06000 @@ -38,9 +38,9 @@ #define S_ISGID 02000 #define S_ISVTX 01000 -#define S_IREAD S_IRUSR +#define S_IREAD S_IRUSR #define S_IWRITE S_IWUSR -#define S_IEXEC S_IXUSR +#define S_IEXEC S_IXUSR #ifdef __cplusplus extern "C" { @@ -66,7 +66,7 @@ struct stat { long __unused[3]; }; -#elif (defined(__riscv) && __riscv_xlen == 64) || defined (__aarch64__) +#elif (defined(__riscv) && __riscv_xlen == 64) || defined(__aarch64__) struct stat { dev_t st_dev; @@ -116,7 +116,7 @@ struct stat { struct timespec st_mtim; struct timespec st_ctim; }; -#elif defined (__m68k__) +#elif defined(__m68k__) struct stat { dev_t st_dev; diff --git a/abis/linux/statfs.h b/abis/linux/statfs.h index 2f0ffa7116..35ccdaf30b 100644 --- a/abis/linux/statfs.h +++ b/abis/linux/statfs.h @@ -41,4 +41,3 @@ struct statfs64 { }; #endif /* _ABIBITS_STATFS_H */ - diff --git a/abis/linux/statvfs.h b/abis/linux/statvfs.h index 03048e759b..baa4ebdc03 100644 --- a/abis/linux/statvfs.h +++ b/abis/linux/statvfs.h @@ -41,4 +41,3 @@ struct statvfs64 { }; #endif /* _ABIBITS_STATVFS_H */ - diff --git a/abis/linux/termios.h b/abis/linux/termios.h index 7cc387f182..bc64c7e582 100644 --- a/abis/linux/termios.h +++ b/abis/linux/termios.h @@ -6,24 +6,24 @@ typedef unsigned int speed_t; typedef unsigned int tcflag_t; /* indices for the c_cc array in struct termios */ -#define NCCS 32 -#define VINTR 0 -#define VQUIT 1 -#define VERASE 2 -#define VKILL 3 -#define VEOF 4 -#define VTIME 5 -#define VMIN 6 -#define VSWTC 7 -#define VSTART 8 -#define VSTOP 9 -#define VSUSP 10 -#define VEOL 11 +#define NCCS 32 +#define VINTR 0 +#define VQUIT 1 +#define VERASE 2 +#define VKILL 3 +#define VEOF 4 +#define VTIME 5 +#define VMIN 6 +#define VSWTC 7 +#define VSTART 8 +#define VSTOP 9 +#define VSUSP 10 +#define VEOL 11 #define VREPRINT 12 #define VDISCARD 13 -#define VWERASE 14 -#define VLNEXT 15 -#define VEOL2 16 +#define VWERASE 14 +#define VLNEXT 15 +#define VEOL2 16 /* bitwise flags for c_iflag in struct termios */ #define IGNBRK 0000001 @@ -111,20 +111,20 @@ typedef unsigned int tcflag_t; #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) -#define EXTA 0000016 -#define EXTB 0000017 -#define CBAUD 0010017 +#define EXTA 0000016 +#define EXTB 0000017 +#define CBAUD 0010017 #define CBAUDEX 0010000 -#define CIBAUD 002003600000 -#define CMSPAR 010000000000 +#define CIBAUD 002003600000 +#define CMSPAR 010000000000 #define CRTSCTS 020000000000 -#define XCASE 0000004 +#define XCASE 0000004 #define ECHOCTL 0001000 #define ECHOPRT 0002000 -#define ECHOKE 0004000 -#define FLUSHO 0010000 -#define PENDIN 0040000 +#define ECHOKE 0004000 +#define FLUSHO 0010000 +#define PENDIN 0040000 #define EXTPROC 0200000 #define XTABS 0014000 diff --git a/abis/linux/time.h b/abis/linux/time.h index dfc342ed2f..fa87af7952 100644 --- a/abis/linux/time.h +++ b/abis/linux/time.h @@ -4,12 +4,12 @@ #include struct itimerval { - struct timeval it_interval; /* Interval for periodic timer */ - struct timeval it_value; /* Time until next expiration */ + struct timeval it_interval; /* Interval for periodic timer */ + struct timeval it_value; /* Time until next expiration */ }; -#define ITIMER_REAL 0 -#define ITIMER_VIRTUAL 1 -#define ITIMER_PROF 2 +#define ITIMER_REAL 0 +#define ITIMER_VIRTUAL 1 +#define ITIMER_PROF 2 #endif /* _ABIBITS_TIME_H */ diff --git a/abis/linux/uid_t.h b/abis/linux/uid_t.h index 976540b12f..eb6f707bc1 100644 --- a/abis/linux/uid_t.h +++ b/abis/linux/uid_t.h @@ -5,4 +5,3 @@ typedef unsigned int uid_t; #endif /* _ABIBITS_UID_T_H */ - diff --git a/abis/linux/vm-flags.h b/abis/linux/vm-flags.h index 2e6275afc1..77fb6f068c 100644 --- a/abis/linux/vm-flags.h +++ b/abis/linux/vm-flags.h @@ -1,28 +1,28 @@ #ifndef _ABIBITS_VM_FLAGS_H #define _ABIBITS_VM_FLAGS_H -#define PROT_NONE 0x00 -#define PROT_READ 0x01 +#define PROT_NONE 0x00 +#define PROT_READ 0x01 #define PROT_WRITE 0x02 -#define PROT_EXEC 0x04 +#define PROT_EXEC 0x04 #define MAP_FAILED ((void *)(-1)) -#define MAP_FILE 0x00 -#define MAP_SHARED 0x01 -#define MAP_PRIVATE 0x02 -#define MAP_FIXED 0x10 -#define MAP_ANON 0x20 +#define MAP_FILE 0x00 +#define MAP_SHARED 0x01 +#define MAP_PRIVATE 0x02 +#define MAP_FIXED 0x10 +#define MAP_ANON 0x20 #define MAP_ANONYMOUS 0x20 #define MAP_GROWSDOWN 0x100 #define MAP_DENYWRITE 0x800 #define MAP_EXECUTABLE 0x1000 -#define MAP_LOCKED 0x2000 +#define MAP_LOCKED 0x2000 #define MAP_NORESERVE 0x4000 -#define MAP_POPULATE 0x8000 -#define MAP_NONBLOCK 0x10000 -#define MAP_STACK 0x20000 -#define MAP_HUGETLB 0x40000 -#define MAP_SYNC 0x80000 +#define MAP_POPULATE 0x8000 +#define MAP_NONBLOCK 0x10000 +#define MAP_STACK 0x20000 +#define MAP_HUGETLB 0x40000 +#define MAP_SYNC 0x80000 #define MAP_FIXED_NOREPLACE 0x100000 #define MS_ASYNC 0x01 diff --git a/abis/linux/vt.h b/abis/linux/vt.h index 8ad19ceb7e..32691695b3 100644 --- a/abis/linux/vt.h +++ b/abis/linux/vt.h @@ -22,11 +22,11 @@ #define VT_SETACTIVATE 0x560F struct vt_mode { - char mode; - char waitv; - short relsig; - short acqsig; - short frsig; + char mode; + char waitv; + short relsig; + short acqsig; + short frsig; }; #define VT_AUTO 0x00 @@ -34,24 +34,24 @@ struct vt_mode { #define VT_ACKACQ 0x02 struct vt_stat { - unsigned short v_active; - unsigned short v_signal; - unsigned short v_state; + unsigned short v_active; + unsigned short v_signal; + unsigned short v_state; }; struct vt_sizes { - unsigned short v_rows; - unsigned short v_cols; - unsigned short v_scrollsize; + unsigned short v_rows; + unsigned short v_cols; + unsigned short v_scrollsize; }; struct vt_consize { - unsigned short v_rows; - unsigned short v_cols; - unsigned short v_vlin; - unsigned short v_clin; - unsigned short v_vcol; - unsigned short v_ccol; + unsigned short v_rows; + unsigned short v_cols; + unsigned short v_vlin; + unsigned short v_clin; + unsigned short v_vcol; + unsigned short v_ccol; }; #define VT_EVENT_SWITCH 0x0001 @@ -61,16 +61,16 @@ struct vt_consize { #define VT_MAX_EVENT 0x000F struct vt_event { - unsigned int event; + unsigned int event; - unsigned int oldev; - unsigned int newev; - unsigned int pad[4]; + unsigned int oldev; + unsigned int newev; + unsigned int pad[4]; }; struct vt_setactivate { - unsigned int console; - struct vt_mode mode; + unsigned int console; + struct vt_mode mode; }; #endif /* _ABIBITS_VT_H */ diff --git a/abis/linux/wait.h b/abis/linux/wait.h index fb9a9aebaf..74002117e6 100644 --- a/abis/linux/wait.h +++ b/abis/linux/wait.h @@ -17,7 +17,7 @@ #define WTERMSIG(x) ((x) & 0x7f) #define WSTOPSIG(x) WEXITSTATUS(x) #define WIFEXITED(x) (WTERMSIG(x) == 0) -#define WIFSIGNALED(x) (((signed char) (((x) & 0x7f) + 1) >> 1) > 0) +#define WIFSIGNALED(x) (((signed char)(((x) & 0x7f) + 1) >> 1) > 0) #define WIFSTOPPED(x) (((x) & 0xff) == 0x7f) #define WIFCONTINUED(x) ((x) == 0xffff) #define WCOREDUMP(x) ((x) & WCOREFLAG) diff --git a/abis/linux/xattr.h b/abis/linux/xattr.h index 89450e3238..01f34b796a 100644 --- a/abis/linux/xattr.h +++ b/abis/linux/xattr.h @@ -15,7 +15,7 @@ enum { XATTR_REPLACE = 2 #define XATTR_REPLACE XATTR_REPLACE }; -# define __UAPI_DEF_XATTR 0 +#define __UAPI_DEF_XATTR 0 #endif #endif /* MLIBC_ABIS_LINUX_XATTR_H */ diff --git a/abis/lyre/statvfs.h b/abis/lyre/statvfs.h index 0628966218..6eabdf1070 100644 --- a/abis/lyre/statvfs.h +++ b/abis/lyre/statvfs.h @@ -32,4 +32,3 @@ struct statvfs { }; #endif /* _ABIBITS_STATVFS_H */ - diff --git a/abis/mlibc/blksize_t.h b/abis/mlibc/blksize_t.h index e4c9f3f7ab..97e8913c2f 100644 --- a/abis/mlibc/blksize_t.h +++ b/abis/mlibc/blksize_t.h @@ -6,4 +6,3 @@ typedef long blksize_t; #endif /* _ABIBITS_BLKSIZE_T_H */ - diff --git a/abis/mlibc/clockid_t.h b/abis/mlibc/clockid_t.h index c3932eff31..e8529aee28 100644 --- a/abis/mlibc/clockid_t.h +++ b/abis/mlibc/clockid_t.h @@ -4,4 +4,3 @@ typedef long clockid_t; #endif /* _ABIBITS_CLOCKID_T_H */ - diff --git a/abis/mlibc/dev_t.h b/abis/mlibc/dev_t.h index 16ccd69670..58a6f22e50 100644 --- a/abis/mlibc/dev_t.h +++ b/abis/mlibc/dev_t.h @@ -5,4 +5,3 @@ typedef unsigned long dev_t; #endif /* _ABIBITS_DEV_T_H */ - diff --git a/abis/mlibc/fcntl.h b/abis/mlibc/fcntl.h index 1fb8ac6ca1..f794667b26 100644 --- a/abis/mlibc/fcntl.h +++ b/abis/mlibc/fcntl.h @@ -10,24 +10,24 @@ #define O_WRONLY 5 /* these flags get their own bit */ -#define O_APPEND 0x000008 -#define O_CREAT 0x000010 +#define O_APPEND 0x000008 +#define O_CREAT 0x000010 #define O_DIRECTORY 0x000020 -#define O_EXCL 0x000040 -#define O_NOCTTY 0x000080 -#define O_NOFOLLOW 0x000100 -#define O_TRUNC 0x000200 -#define O_NONBLOCK 0x000400 -#define O_DSYNC 0x000800 -#define O_RSYNC 0x001000 -#define O_SYNC 0x002000 -#define O_CLOEXEC 0x004000 -#define O_PATH 0x008000 +#define O_EXCL 0x000040 +#define O_NOCTTY 0x000080 +#define O_NOFOLLOW 0x000100 +#define O_TRUNC 0x000200 +#define O_NONBLOCK 0x000400 +#define O_DSYNC 0x000800 +#define O_RSYNC 0x001000 +#define O_SYNC 0x002000 +#define O_CLOEXEC 0x004000 +#define O_PATH 0x008000 #define O_LARGEFILE 0x010000 -#define O_NOATIME 0x020000 -#define O_ASYNC 0x040000 -#define O_TMPFILE 0x080000 -#define O_DIRECT 0x100000 +#define O_NOATIME 0x020000 +#define O_ASYNC 0x040000 +#define O_TMPFILE 0x080000 +#define O_DIRECT 0x100000 /* constants for fcntl()'s command argument */ #define F_DUPFD 1 @@ -54,11 +54,11 @@ /* Used by mmap */ #define F_SEAL_SHRINK 0x0002 -#define F_SEAL_GROW 0x0004 -#define F_SEAL_WRITE 0x0008 -#define F_SEAL_SEAL 0x0010 -#define F_ADD_SEALS 1033 -#define F_GET_SEALS 1034 +#define F_SEAL_GROW 0x0004 +#define F_SEAL_WRITE 0x0008 +#define F_SEAL_SEAL 0x0010 +#define F_ADD_SEALS 1033 +#define F_GET_SEALS 1034 #define AT_EMPTY_PATH 1 #define AT_SYMLINK_FOLLOW 2 diff --git a/abis/mlibc/gid_t.h b/abis/mlibc/gid_t.h index f513e250d2..3e356f7544 100644 --- a/abis/mlibc/gid_t.h +++ b/abis/mlibc/gid_t.h @@ -5,4 +5,3 @@ typedef unsigned int gid_t; #endif /* _ABIBITS_GID_T_H */ - diff --git a/abis/mlibc/in.h b/abis/mlibc/in.h index 3b4df5b2a7..92361b09d2 100644 --- a/abis/mlibc/in.h +++ b/abis/mlibc/in.h @@ -1,9 +1,9 @@ #ifndef _ABIBITS_IN_H #define _ABIBITS_IN_H +#include #include #include -#include #include #ifdef __cplusplus @@ -20,7 +20,7 @@ struct sockaddr_in { struct in_addr sin_addr; uint8_t pad[8]; }; -#define sin_zero pad /* for BSD Unix compatibility */ +#define sin_zero pad /* for BSD Unix compatibility */ struct in6_addr { union { @@ -84,8 +84,14 @@ struct group_source_req { } #endif -#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } -#define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } +#define IN6ADDR_ANY_INIT \ + { \ + { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } \ + } +#define IN6ADDR_LOOPBACK_INIT \ + { \ + { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } \ + } #define IPPROTO_IP 1 #define IPPROTO_IPV6 2 @@ -147,23 +153,23 @@ struct group_source_req { #define IP_UNICAST_IF 13 #define IP_MTU 14 -#define IP_DEFAULT_MULTICAST_TTL 1 -#define IP_MULTICAST_IF 32 -#define IP_MULTICAST_TTL 33 -#define IP_MULTICAST_LOOP 34 -#define IP_ADD_MEMBERSHIP 35 -#define IP_DROP_MEMBERSHIP 36 -#define IP_UNBLOCK_SOURCE 37 -#define IP_BLOCK_SOURCE 38 -#define IP_ADD_SOURCE_MEMBERSHIP 39 +#define IP_DEFAULT_MULTICAST_TTL 1 +#define IP_MULTICAST_IF 32 +#define IP_MULTICAST_TTL 33 +#define IP_MULTICAST_LOOP 34 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 +#define IP_UNBLOCK_SOURCE 37 +#define IP_BLOCK_SOURCE 38 +#define IP_ADD_SOURCE_MEMBERSHIP 39 #define IP_DROP_SOURCE_MEMBERSHIP 40 -#define MCAST_JOIN_SOURCE_GROUP 46 -#define MCAST_LEAVE_SOURCE_GROUP 47 +#define MCAST_JOIN_SOURCE_GROUP 46 +#define MCAST_LEAVE_SOURCE_GROUP 47 #define IP_PMTUDISC_DONT 0 -#define IP_PMTUDISC_DO 2 +#define IP_PMTUDISC_DO 2 -#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP #endif /* _ABIBITS_IN_H */ diff --git a/abis/mlibc/ino_t.h b/abis/mlibc/ino_t.h index 049e16ec76..69a0f07d04 100644 --- a/abis/mlibc/ino_t.h +++ b/abis/mlibc/ino_t.h @@ -6,4 +6,3 @@ typedef long ino_t; #endif /* _ABIBITS_INO_T_H */ - diff --git a/abis/mlibc/mode_t.h b/abis/mlibc/mode_t.h index b1a11f371a..3e502f9161 100644 --- a/abis/mlibc/mode_t.h +++ b/abis/mlibc/mode_t.h @@ -5,4 +5,3 @@ typedef int mode_t; #endif /* _ABIBITS_MODE_T_H */ - diff --git a/abis/mlibc/nlink_t.h b/abis/mlibc/nlink_t.h index 49c7e0f55b..7f88b39d39 100644 --- a/abis/mlibc/nlink_t.h +++ b/abis/mlibc/nlink_t.h @@ -5,4 +5,3 @@ typedef int nlink_t; #endif /* _ABIBITS_NLINK_T_H */ - diff --git a/abis/mlibc/pid_t.h b/abis/mlibc/pid_t.h index 9591edb35d..68ead168a7 100644 --- a/abis/mlibc/pid_t.h +++ b/abis/mlibc/pid_t.h @@ -5,4 +5,3 @@ typedef int pid_t; #endif /* _ABIBITS_PID_T_H */ - diff --git a/abis/mlibc/signal.h b/abis/mlibc/signal.h index 3997facf48..8a46102080 100644 --- a/abis/mlibc/signal.h +++ b/abis/mlibc/signal.h @@ -8,8 +8,8 @@ #include #include -#include #include +#include union sigval { int sival_int; @@ -32,7 +32,7 @@ extern "C" { #endif /* Argument for signal() */ -typedef void (*__sighandler) (int); +typedef void (*__sighandler)(int); #define SIG_ERR ((__sighandler)(void *)(-1)) #define SIG_DFL ((__sighandler)(void *)(-2)) @@ -118,9 +118,9 @@ typedef __mlibc_uint64 sigset_t; #define SS_DISABLE 2 typedef struct __stack { - void *ss_sp; - size_t ss_size; - int ss_flags; + void *ss_sp; + size_t ss_size; + int ss_flags; } stack_t; /* constants for sigev_notify of struct sigevent */ diff --git a/abis/mlibc/socket.h b/abis/mlibc/socket.h index d7754f456a..359b087f62 100644 --- a/abis/mlibc/socket.h +++ b/abis/mlibc/socket.h @@ -27,7 +27,7 @@ struct sockaddr_storage { struct mmsghdr { struct msghdr msg_hdr; - unsigned int msg_len; + unsigned int msg_len; }; struct cmsghdr { diff --git a/abis/mlibc/stat.h b/abis/mlibc/stat.h index 37f6aaa016..534615b8f6 100644 --- a/abis/mlibc/stat.h +++ b/abis/mlibc/stat.h @@ -1,17 +1,17 @@ #ifndef _ABIBITS_STAT_H #define _ABIBITS_STAT_H -#include -#include -#include -#include +#include +#include #include +#include #include -#include -#include +#include #include +#include #include #include +#include #define S_IFMT 0x0F000 #define S_IFBLK 0x06000 @@ -38,9 +38,9 @@ #define S_ISGID 02000 #define S_ISVTX 01000 -#define S_IREAD S_IRUSR +#define S_IREAD S_IRUSR #define S_IWRITE S_IWUSR -#define S_IEXEC S_IXUSR +#define S_IEXEC S_IXUSR #ifdef __cplusplus extern "C" { diff --git a/abis/mlibc/termios.h b/abis/mlibc/termios.h index eafec507a0..9636d48613 100644 --- a/abis/mlibc/termios.h +++ b/abis/mlibc/termios.h @@ -11,98 +11,98 @@ typedef unsigned int speed_t; typedef unsigned int tcflag_t; /* indices for the c_cc array in struct termios */ -#define NCCS 11 -#define VEOF 0 -#define VEOL 1 -#define VERASE 2 -#define VINTR 3 -#define VKILL 4 -#define VMIN 5 -#define VQUIT 6 -#define VSTART 7 -#define VSTOP 8 -#define VSUSP 9 -#define VTIME 10 +#define NCCS 11 +#define VEOF 0 +#define VEOL 1 +#define VERASE 2 +#define VINTR 3 +#define VKILL 4 +#define VMIN 5 +#define VQUIT 6 +#define VSTART 7 +#define VSTOP 8 +#define VSUSP 9 +#define VTIME 10 /* bitwise flags for c_iflag in struct termios */ -#define BRKINT 0x0001 -#define ICRNL 0x0002 -#define IGNBRK 0x0004 -#define IGNCR 0x0008 -#define IGNPAR 0x0010 -#define INLCR 0x0020 -#define INPCK 0x0040 -#define ISTRIP 0x0080 -#define IXANY 0x0100 -#define IXOFF 0x0200 -#define IXON 0x0400 -#define PARMRK 0x0800 +#define BRKINT 0x0001 +#define ICRNL 0x0002 +#define IGNBRK 0x0004 +#define IGNCR 0x0008 +#define IGNPAR 0x0010 +#define INLCR 0x0020 +#define INPCK 0x0040 +#define ISTRIP 0x0080 +#define IXANY 0x0100 +#define IXOFF 0x0200 +#define IXON 0x0400 +#define PARMRK 0x0800 /* bitwise flags for c_oflag in struct termios */ -#define OPOST 0x0001 -#define ONLCR 0x0002 -#define OCRNL 0x0004 -#define ONOCR 0x0008 -#define ONLRET 0x0010 -#define OFDEL 0x0020 -#define OFILL 0x0040 - -#define NLDLY 0x0080 -#define NL0 0x0000 -#define NL1 0x0080 - -#define CRDLY 0x0300 -#define CR0 0x0000 -#define CR1 0x0100 -#define CR2 0x0200 -#define CR3 0x0300 - -#define TABDLY 0x0C00 -#define TAB0 0x0000 -#define TAB1 0x0400 -#define TAB2 0x0800 -#define TAB3 0x0C00 - -#define BSDLY 0x1000 -#define BS0 0x0000 -#define BS1 0x1000 - -#define VTDLY 0x2000 -#define VT0 0x0000 -#define VT1 0x2000 - -#define FFDLY 0x4000 -#define FF0 0x0000 -#define FF1 0x4000 +#define OPOST 0x0001 +#define ONLCR 0x0002 +#define OCRNL 0x0004 +#define ONOCR 0x0008 +#define ONLRET 0x0010 +#define OFDEL 0x0020 +#define OFILL 0x0040 + +#define NLDLY 0x0080 +#define NL0 0x0000 +#define NL1 0x0080 + +#define CRDLY 0x0300 +#define CR0 0x0000 +#define CR1 0x0100 +#define CR2 0x0200 +#define CR3 0x0300 + +#define TABDLY 0x0C00 +#define TAB0 0x0000 +#define TAB1 0x0400 +#define TAB2 0x0800 +#define TAB3 0x0C00 + +#define BSDLY 0x1000 +#define BS0 0x0000 +#define BS1 0x1000 + +#define VTDLY 0x2000 +#define VT0 0x0000 +#define VT1 0x2000 + +#define FFDLY 0x4000 +#define FF0 0x0000 +#define FF1 0x4000 /* bitwise constants for c_cflag in struct termios */ -#define CSIZE 0x0003 -#define CS5 0x0000 -#define CS6 0x0001 -#define CS7 0x0002 -#define CS8 0x0003 - -#define CSTOPB 0x0004 -#define CREAD 0x0008 -#define PARENB 0x0010 -#define PARODD 0x0020 -#define HUPCL 0x0040 -#define CLOCAL 0x0080 +#define CSIZE 0x0003 +#define CS5 0x0000 +#define CS6 0x0001 +#define CS7 0x0002 +#define CS8 0x0003 + +#define CSTOPB 0x0004 +#define CREAD 0x0008 +#define PARENB 0x0010 +#define PARODD 0x0020 +#define HUPCL 0x0040 +#define CLOCAL 0x0080 #if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) -#define CBAUD 0x100F +#define CBAUD 0x100F #endif /* bitwise constants for c_lflag in struct termios */ -#define ECHO 0x0001 -#define ECHOE 0x0002 -#define ECHOK 0x0004 -#define ECHONL 0x0008 -#define ICANON 0x0010 -#define IEXTEN 0x0020 -#define ISIG 0x0040 -#define NOFLSH 0x0080 -#define TOSTOP 0x0100 +#define ECHO 0x0001 +#define ECHOE 0x0002 +#define ECHOK 0x0004 +#define ECHONL 0x0008 +#define ICANON 0x0010 +#define IEXTEN 0x0020 +#define ISIG 0x0040 +#define NOFLSH 0x0080 +#define TOSTOP 0x0100 #define ECHOPRT 0x0200 struct termios { diff --git a/abis/mlibc/time.h b/abis/mlibc/time.h index dfc342ed2f..fa87af7952 100644 --- a/abis/mlibc/time.h +++ b/abis/mlibc/time.h @@ -4,12 +4,12 @@ #include struct itimerval { - struct timeval it_interval; /* Interval for periodic timer */ - struct timeval it_value; /* Time until next expiration */ + struct timeval it_interval; /* Interval for periodic timer */ + struct timeval it_value; /* Time until next expiration */ }; -#define ITIMER_REAL 0 -#define ITIMER_VIRTUAL 1 -#define ITIMER_PROF 2 +#define ITIMER_REAL 0 +#define ITIMER_VIRTUAL 1 +#define ITIMER_PROF 2 #endif /* _ABIBITS_TIME_H */ diff --git a/abis/mlibc/uid_t.h b/abis/mlibc/uid_t.h index 976540b12f..eb6f707bc1 100644 --- a/abis/mlibc/uid_t.h +++ b/abis/mlibc/uid_t.h @@ -5,4 +5,3 @@ typedef unsigned int uid_t; #endif /* _ABIBITS_UID_T_H */ - diff --git a/abis/mlibc/vm-flags.h b/abis/mlibc/vm-flags.h index 769275a994..6361e32e33 100644 --- a/abis/mlibc/vm-flags.h +++ b/abis/mlibc/vm-flags.h @@ -1,17 +1,17 @@ #ifndef _ABIBITS_MMAP_FLAGS_H #define _ABIBITS_MMAP_FLAGS_H -#define PROT_NONE 0x00 -#define PROT_READ 0x01 +#define PROT_NONE 0x00 +#define PROT_READ 0x01 #define PROT_WRITE 0x02 -#define PROT_EXEC 0x04 +#define PROT_EXEC 0x04 #define MAP_FAILED ((void *)(-1)) -#define MAP_FILE 0x00 -#define MAP_PRIVATE 0x01 -#define MAP_SHARED 0x02 -#define MAP_FIXED 0x04 -#define MAP_ANON 0x08 +#define MAP_FILE 0x00 +#define MAP_PRIVATE 0x01 +#define MAP_SHARED 0x02 +#define MAP_FIXED 0x04 +#define MAP_ANON 0x08 #define MAP_ANONYMOUS 0x08 #define MAP_NORESERVE 0x10 #define MAP_FIXED_NOREPLACE 0x20 diff --git a/abis/vinix/signal.h b/abis/vinix/signal.h index 80adcdf0b1..e3d689a9e4 100644 --- a/abis/vinix/signal.h +++ b/abis/vinix/signal.h @@ -26,7 +26,7 @@ extern "C" { #endif /* Argument for signal() */ -typedef void (*__sighandler) (int); +typedef void (*__sighandler)(int); #define SIG_ERR ((__sighandler)(void *)(-1)) #define SIG_DFL ((__sighandler)(void *)(-2)) diff --git a/dummy-libs/libdl/src/dummy.cpp b/dummy-libs/libdl/src/dummy.cpp index c9d4287dbf..a43867c648 100644 --- a/dummy-libs/libdl/src/dummy.cpp +++ b/dummy-libs/libdl/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libdl because g++ always links with -ldl // The actual functions reside inside libc -extern "C" void __mlibc_libdl_dummy(void) { } - +extern "C" void __mlibc_libdl_dummy(void) {} diff --git a/dummy-libs/libm/src/dummy.cpp b/dummy-libs/libm/src/dummy.cpp index eed43ca1e9..0fed479b29 100644 --- a/dummy-libs/libm/src/dummy.cpp +++ b/dummy-libs/libm/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libm because g++ always links with -lm // The actual math functions reside inside libc -extern "C" void __mlibc_libm_dummy(void) { } - +extern "C" void __mlibc_libm_dummy(void) {} diff --git a/dummy-libs/libpthread/src/dummy.cpp b/dummy-libs/libpthread/src/dummy.cpp index 3f8c51a9c3..548f51a1e4 100644 --- a/dummy-libs/libpthread/src/dummy.cpp +++ b/dummy-libs/libpthread/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libpthread because g++ always links with -lpthread // The actual functions reside inside libc -extern "C" void __mlibc_libpthread_dummy(void) { } - +extern "C" void __mlibc_libpthread_dummy(void) {} diff --git a/dummy-libs/libresolv/src/dummy.cpp b/dummy-libs/libresolv/src/dummy.cpp index 5feb1c37e6..491aa22acb 100644 --- a/dummy-libs/libresolv/src/dummy.cpp +++ b/dummy-libs/libresolv/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libresolv because some programs always links with -lresolv // The actual functions reside inside libc -extern "C" void __mlibc_libresolv_dummy(void) { } - +extern "C" void __mlibc_libresolv_dummy(void) {} diff --git a/dummy-libs/librt/src/dummy.cpp b/dummy-libs/librt/src/dummy.cpp index 35c3852875..ad764d3f92 100644 --- a/dummy-libs/librt/src/dummy.cpp +++ b/dummy-libs/librt/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty librt because g++ always links with -lrt // The actual functions reside inside libc -extern "C" void __mlibc_librt_dummy(void) { } - +extern "C" void __mlibc_librt_dummy(void) {} diff --git a/dummy-libs/libssp/src/dummy.cpp b/dummy-libs/libssp/src/dummy.cpp index 43286c1dad..950f1455e8 100644 --- a/dummy-libs/libssp/src/dummy.cpp +++ b/dummy-libs/libssp/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libsso because some packages expect -lssp // The actual ssp functions are provided by libc. -extern "C" void __mlibc_libssp_dummy(void) { } - +extern "C" void __mlibc_libssp_dummy(void) {} diff --git a/dummy-libs/libssp_nonshared/src/dummy.cpp b/dummy-libs/libssp_nonshared/src/dummy.cpp index dcd8e9048f..18a082e722 100644 --- a/dummy-libs/libssp_nonshared/src/dummy.cpp +++ b/dummy-libs/libssp_nonshared/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libsso because some packages expect -lssp_nonshared // The actual ssp functions are provided by libc. -extern "C" void __mlibc_libssp_nonshared_dummy(void) { } - +extern "C" void __mlibc_libssp_nonshared_dummy(void) {} diff --git a/dummy-libs/libutil/src/dummy.cpp b/dummy-libs/libutil/src/dummy.cpp index c295ee5cb3..552b514dbf 100644 --- a/dummy-libs/libutil/src/dummy.cpp +++ b/dummy-libs/libutil/src/dummy.cpp @@ -2,5 +2,4 @@ // We build an empty libutil because g++ always links with -lutil // The actual functions reside inside libc -extern "C" void __mlibc_libutil_dummy(void) { } - +extern "C" void __mlibc_libutil_dummy(void) {} diff --git a/options/ansi/generic/assert.cpp b/options/ansi/generic/assert.cpp index 6ebb6eda1d..6f6ec89444 100644 --- a/options/ansi/generic/assert.cpp +++ b/options/ansi/generic/assert.cpp @@ -5,9 +5,15 @@ #include -[[gnu::noreturn]] void __assert_fail(const char *assertion, const char *file, unsigned int line, - const char *function) { - fprintf(stderr, "In function %s, file %s:%d: Assertion '%s' failed!\n", - function, file, line, assertion); +[[gnu::noreturn]] void +__assert_fail(const char *assertion, const char *file, unsigned int line, const char *function) { + fprintf( + stderr, + "In function %s, file %s:%d: Assertion '%s' failed!\n", + function, + file, + line, + assertion + ); abort(); } diff --git a/options/ansi/generic/complex.c b/options/ansi/generic/complex.c index 069626bd08..113a3231f5 100644 --- a/options/ansi/generic/complex.c +++ b/options/ansi/generic/complex.c @@ -1,9 +1,5 @@ #include -long double cimagl(long double complex z) { - return __imag__(z); -} +long double cimagl(long double complex z) { return __imag__(z); } -long double creall(long double complex z) { - return __real__(z); -} +long double creall(long double complex z) { return __real__(z); } diff --git a/options/ansi/generic/ctype.cpp b/options/ansi/generic/ctype.cpp index 3ce76e9db6..b7cebdfacf 100644 --- a/options/ansi/generic/ctype.cpp +++ b/options/ansi/generic/ctype.cpp @@ -12,7 +12,7 @@ int isalpha(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_alpha(cp); } @@ -20,7 +20,7 @@ int isalpha(int nc) { int isdigit(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_digit(cp); } @@ -28,7 +28,7 @@ int isdigit(int nc) { int isxdigit(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_xdigit(cp); } @@ -36,7 +36,7 @@ int isxdigit(int nc) { int isalnum(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_alnum(cp); } @@ -44,7 +44,7 @@ int isalnum(int nc) { int ispunct(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_punct(cp); } @@ -52,7 +52,7 @@ int ispunct(int nc) { int isgraph(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_graph(cp); } @@ -60,7 +60,7 @@ int isgraph(int nc) { int isblank(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_blank(cp); } @@ -68,7 +68,7 @@ int isblank(int nc) { int isspace(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_space(cp); } @@ -76,7 +76,7 @@ int isspace(int nc) { int isprint(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_print(cp); } @@ -84,7 +84,7 @@ int isprint(int nc) { int islower(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_lower(cp); } @@ -92,7 +92,7 @@ int islower(int nc) { int isupper(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_upper(cp); } @@ -100,7 +100,7 @@ int isupper(int nc) { int iscntrl(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::generic_is_control(cp); } @@ -108,7 +108,7 @@ int iscntrl(int nc) { int isascii(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return cp <= 0x7F; } @@ -120,7 +120,7 @@ int isascii(int nc) { int iswalpha(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_alpha(cp); } @@ -128,7 +128,7 @@ int iswalpha(wint_t nc) { int iswdigit(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_digit(cp); } @@ -136,7 +136,7 @@ int iswdigit(wint_t nc) { int iswxdigit(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_xdigit(cp); } @@ -144,7 +144,7 @@ int iswxdigit(wint_t nc) { int iswalnum(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_alnum(cp); } @@ -152,7 +152,7 @@ int iswalnum(wint_t nc) { int iswpunct(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_punct(cp); } @@ -160,7 +160,7 @@ int iswpunct(wint_t nc) { int iswgraph(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_graph(cp); } @@ -168,7 +168,7 @@ int iswgraph(wint_t nc) { int iswblank(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_blank(cp); } @@ -176,7 +176,7 @@ int iswblank(wint_t nc) { int iswspace(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_space(cp); } @@ -184,7 +184,7 @@ int iswspace(wint_t nc) { int iswprint(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_print(cp); } @@ -192,7 +192,7 @@ int iswprint(wint_t nc) { int iswlower(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_lower(cp); } @@ -200,7 +200,7 @@ int iswlower(wint_t nc) { int iswupper(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::current_charset()->is_upper(cp); } @@ -208,7 +208,7 @@ int iswupper(wint_t nc) { int iswcntrl(wint_t nc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return 0; return mlibc::generic_is_control(cp); } @@ -218,68 +218,80 @@ int iswcntrl(wint_t nc) { // -------------------------------------------------------------------------------------- namespace { - enum { - ct_null, - ct_alnum, - ct_alpha, - ct_blank, - ct_cntrl, - ct_digit, - ct_graph, - ct_lower, - ct_print, - ct_punct, - ct_space, - ct_upper, - ct_xdigit, - ct_count - }; +enum { + ct_null, + ct_alnum, + ct_alpha, + ct_blank, + ct_cntrl, + ct_digit, + ct_graph, + ct_lower, + ct_print, + ct_punct, + ct_space, + ct_upper, + ct_xdigit, + ct_count +}; } wctype_t wctype(const char *cs) { frg::string_view s{cs}; - if(s == "alnum") return ct_alnum; - if(s == "alpha") return ct_alpha; - if(s == "blank") return ct_blank; - if(s == "cntrl") return ct_cntrl; - if(s == "digit") return ct_digit; - if(s == "graph") return ct_graph; - if(s == "lower") return ct_lower; - if(s == "print") return ct_print; - if(s == "punct") return ct_punct; - if(s == "space") return ct_space; - if(s == "upper") return ct_upper; - if(s == "xdigit") return ct_xdigit; + if (s == "alnum") + return ct_alnum; + if (s == "alpha") + return ct_alpha; + if (s == "blank") + return ct_blank; + if (s == "cntrl") + return ct_cntrl; + if (s == "digit") + return ct_digit; + if (s == "graph") + return ct_graph; + if (s == "lower") + return ct_lower; + if (s == "print") + return ct_print; + if (s == "punct") + return ct_punct; + if (s == "space") + return ct_space; + if (s == "upper") + return ct_upper; + if (s == "xdigit") + return ct_xdigit; mlibc::infoLogger() << "mlibc: wctype(\"" << cs << "\") is not supported" << frg::endlog; return ct_null; } int iswctype(wint_t wc, wctype_t type) { switch (type) { - case ct_alnum: - return iswalnum(wc); - case ct_alpha: - return iswalpha(wc); - case ct_blank: - return iswblank(wc); - case ct_cntrl: - return iswcntrl(wc); - case ct_digit: - return iswdigit(wc); - case ct_graph: - return iswgraph(wc); - case ct_lower: - return iswlower(wc); - case ct_print: - return iswprint(wc); - case ct_punct: - return iswpunct(wc); - case ct_space: - return iswspace(wc); - case ct_upper: - return iswupper(wc); - case ct_xdigit: - return iswxdigit(wc); + case ct_alnum: + return iswalnum(wc); + case ct_alpha: + return iswalpha(wc); + case ct_blank: + return iswblank(wc); + case ct_cntrl: + return iswcntrl(wc); + case ct_digit: + return iswdigit(wc); + case ct_graph: + return iswgraph(wc); + case ct_lower: + return iswlower(wc); + case ct_print: + return iswprint(wc); + case ct_punct: + return iswpunct(wc); + case ct_space: + return iswspace(wc); + case ct_upper: + return iswupper(wc); + case ct_xdigit: + return iswxdigit(wc); } return 0; } @@ -291,7 +303,7 @@ int iswctype(wint_t wc, wctype_t type) { int tolower(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return nc; return mlibc::current_charset()->to_lower(cp); } @@ -299,7 +311,7 @@ int tolower(int nc) { int toupper(int nc) { auto cc = mlibc::current_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(nc, cp); e != mlibc::charcode_error::null) return nc; return mlibc::current_charset()->to_upper(cp); } @@ -311,7 +323,7 @@ int toupper(int nc) { wint_t towlower(wint_t wc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(wc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(wc, cp); e != mlibc::charcode_error::null) return wc; return mlibc::current_charset()->to_lower(cp); } @@ -319,8 +331,7 @@ wint_t towlower(wint_t wc) { wint_t towupper(wint_t wc) { auto cc = mlibc::platform_wide_charcode(); mlibc::codepoint cp; - if(auto e = cc->promote(wc, cp); e != mlibc::charcode_error::null) + if (auto e = cc->promote(wc, cp); e != mlibc::charcode_error::null) return wc; return mlibc::current_charset()->to_upper(cp); } - diff --git a/options/ansi/generic/environment.cpp b/options/ansi/generic/environment.cpp index 5625592027..f988dc079f 100644 --- a/options/ansi/generic/environment.cpp +++ b/options/ansi/generic/environment.cpp @@ -1,6 +1,6 @@ #include -#include #include +#include #include #include @@ -10,7 +10,7 @@ #include namespace { - char *empty_environment[] = { nullptr }; +char *empty_environment[] = {nullptr}; } char **environ = empty_environment; @@ -18,16 +18,16 @@ char **environ = empty_environment; namespace { size_t find_environ_index(frg::string_view name) { - for(size_t i = 0; environ[i]; i++) { + for (size_t i = 0; environ[i]; i++) { frg::string_view view{environ[i]}; size_t s = view.find_first('='); - if(s == size_t(-1)) { + if (s == size_t(-1)) { mlibc::infoLogger() << "mlibc: environment string \"" - << frg::escape_fmt{view.data(), view.size()} - << "\" does not contain an equals sign (=)" << frg::endlog; + << frg::escape_fmt{view.data(), view.size()} + << "\" does not contain an equals sign (=)" << frg::endlog; continue; } - if(view.sub_string(0, s) == name) + if (view.sub_string(0, s) == name) return i; } @@ -43,13 +43,13 @@ frg::vector &get_vector() { void update_vector() { auto &vector = get_vector(); - if(environ == vector.data()) + if (environ == vector.data()) return; // If the environ variable was changed, we copy the environment. // Note that we must only copy the pointers but not the strings themselves! vector.clear(); - for(size_t i = 0; environ[i]; i++) + for (size_t i = 0; environ[i]; i++) vector.push(environ[i]); vector.push(nullptr); @@ -61,10 +61,10 @@ void assign_variable(frg::string_view name, const char *string, bool overwrite) __ensure(environ == vector.data()); auto k = find_environ_index(name); - if(k != size_t(-1)) { - if(overwrite) + if (k != size_t(-1)) { + if (overwrite) vector[k] = const_cast(string); - }else{ + } else { // Last pointer of environ must always be a null delimiter. __ensure(!vector.back()); vector.back() = const_cast(string); @@ -80,7 +80,7 @@ void unassign_variable(frg::string_view name) { __ensure(environ == vector.data()); auto k = find_environ_index(name); - if(k == size_t(-1)) + if (k == size_t(-1)) return; // Last pointer of environ must always be a null delimiter. @@ -97,7 +97,7 @@ void unassign_variable(frg::string_view name) { char *getenv(const char *name) { auto k = find_environ_index(name); - if(k == size_t(-1)) + if (k == size_t(-1)) return nullptr; frg::string_view view{environ[k]}; @@ -111,7 +111,7 @@ namespace mlibc { int putenv(char *string) { frg::string_view view{string}; size_t s = view.find_first('='); - if(s == size_t(-1)) + if (s == size_t(-1)) __ensure(!"Environment strings need to contain an equals sign"); update_vector(); @@ -123,17 +123,15 @@ int putenv(char *string) { #if __MLIBC_POSIX_OPTION -int putenv(char *string) { - return mlibc::putenv(string); -} +int putenv(char *string) { return mlibc::putenv(string); } int setenv(const char *name, const char *value, int overwrite) { frg::string_view view{name}; size_t s = view.find_first('='); - if(s != size_t(-1)) { + if (s != size_t(-1)) { mlibc::infoLogger() << "mlibc: environment variable \"" - << frg::escape_fmt{view.data(), view.size()} << "\" contains an equals sign" - << frg::endlog; + << frg::escape_fmt{view.data(), view.size()} + << "\" contains an equals sign" << frg::endlog; errno = EINVAL; return -1; } diff --git a/options/ansi/generic/errno.cpp b/options/ansi/generic/errno.cpp index 8229a9a5b6..7ecf1d661e 100644 --- a/options/ansi/generic/errno.cpp +++ b/options/ansi/generic/errno.cpp @@ -7,6 +7,4 @@ char *program_invocation_short_name = nullptr; extern char *__progname __attribute__((__weak__, __alias__("program_invocation_short_name"))); extern char *__progname_full __attribute__((__weak__, __alias__("program_invocation_name"))); -int *__errno_location() { - return &__mlibc_errno; -} +int *__errno_location() { return &__mlibc_errno; } diff --git a/options/ansi/generic/fenv.cpp b/options/ansi/generic/fenv.cpp index 7153844bdf..c81830be4d 100644 --- a/options/ansi/generic/fenv.cpp +++ b/options/ansi/generic/fenv.cpp @@ -24,13 +24,13 @@ int fesetexceptflag(const fexcept_t *, int) { int fesetround(int r) { if (r != FE_TONEAREST #ifdef FE_DOWNWARD - && r != FE_DOWNWARD + && r != FE_DOWNWARD #endif #ifdef FE_UPWARD - && r != FE_UPWARD + && r != FE_UPWARD #endif #ifdef FE_TOWARDZERO - && r != FE_TOWARDZERO + && r != FE_TOWARDZERO #endif ) return -1; diff --git a/options/ansi/generic/file-io.cpp b/options/ansi/generic/file-io.cpp index e59b109ee5..50941b1f57 100644 --- a/options/ansi/generic/file-io.cpp +++ b/options/ansi/generic/file-io.cpp @@ -1,9 +1,9 @@ #include -#include #include -#include #include +#include +#include #if __MLIBC_GLIBC_OPTION #include #endif @@ -16,8 +16,8 @@ #include #include #include -#include #include +#include #include namespace mlibc { @@ -27,27 +27,25 @@ namespace mlibc { // -------------------------------------------------------------------------------------- namespace { - using file_list = frg::intrusive_list< - abstract_file, - frg::locate_member< - abstract_file, - frg::default_list_hook, - &abstract_file::_list_hook - > - >; - - // Useful when debugging the FILE implementation. - constexpr bool globallyDisableBuffering = false; - - // The maximum number of characters we permit the user to ungetc. - constexpr size_t ungetBufferSize = 8; - - // List of files that will be flushed before exit(). - file_list &global_file_list() { - static frg::eternal list; - return list.get(); - }; -} +using file_list = frg::intrusive_list< + abstract_file, + frg::locate_member< + abstract_file, + frg::default_list_hook, + &abstract_file::_list_hook>>; + +// Useful when debugging the FILE implementation. +constexpr bool globallyDisableBuffering = false; + +// The maximum number of characters we permit the user to ungetc. +constexpr size_t ungetBufferSize = 8; + +// List of files that will be flushed before exit(). +file_list &global_file_list() { + static frg::eternal list; + return list.get(); +}; +} // namespace // For pipe-like streams (seek returns ESPIPE), we need to make sure // that the buffer only ever contains all-dirty or all-clean data. @@ -56,7 +54,9 @@ namespace { // open (e.g. for std{in,out,err}), we defer the type determination and cache the result. abstract_file::abstract_file(void (*do_dispose)(abstract_file *)) -: _type{stream_type::unknown}, _bufmode{buffer_mode::unknown}, _do_dispose{do_dispose} { + : _type{stream_type::unknown}, + _bufmode{buffer_mode::unknown}, + _do_dispose{do_dispose} { // TODO: For __fwriting to work correctly, set the __io_mode to 1 if the write is write-only. __buffer_ptr = nullptr; __unget_ptr = nullptr; @@ -73,11 +73,11 @@ abstract_file::abstract_file(void (*do_dispose)(abstract_file *)) } abstract_file::~abstract_file() { - if(__dirty_begin != __dirty_end) + if (__dirty_begin != __dirty_end) mlibc::infoLogger() << "mlibc warning: File is not flushed before destruction" - << frg::endlog; + << frg::endlog; - if(__buffer_ptr) + if (__buffer_ptr) getAllocator().free(__buffer_ptr - ungetBufferSize); auto it = global_file_list().iterator_to(this); @@ -85,7 +85,7 @@ abstract_file::~abstract_file() { } void abstract_file::dispose() { - if(!_do_dispose) + if (!_do_dispose) return; _do_dispose(this); } @@ -97,7 +97,7 @@ void abstract_file::dispose() { int abstract_file::read(char *buffer, size_t max_size, size_t *actual_size) { __ensure(max_size); - if(_init_bufmode()) + if (_init_bufmode()) return -1; size_t unget_length = 0; @@ -115,13 +115,13 @@ int abstract_file::read(char *buffer, size_t max_size, size_t *actual_size) { } } - if(globallyDisableBuffering || _bufmode == buffer_mode::no_buffer) { + if (globallyDisableBuffering || _bufmode == buffer_mode::no_buffer) { size_t io_size; - if(int e = io_read(buffer, max_size, &io_size); e) { + if (int e = io_read(buffer, max_size, &io_size); e) { __status_bits |= __MLIBC_ERROR_BIT; return e; } - if(!io_size) + if (!io_size) __status_bits |= __MLIBC_EOF_BIT; *actual_size = io_size + unget_length; return 0; @@ -129,27 +129,26 @@ int abstract_file::read(char *buffer, size_t max_size, size_t *actual_size) { // Ensure correct buffer type for pipe-like streams. // TODO: In order to support pipe-like streams we need to write-back the buffer. - if(__io_mode && __valid_limit) - mlibc::panicLogger() << "mlibc: Cannot read-write to same pipe-like stream" - << frg::endlog; + if (__io_mode && __valid_limit) + mlibc::panicLogger() << "mlibc: Cannot read-write to same pipe-like stream" << frg::endlog; __io_mode = 0; // Clear the buffer, then buffer new data. - if(__offset == __valid_limit) { + if (__offset == __valid_limit) { // TODO: We only have to write-back/reset if __valid_limit reaches the buffer end. - if(int e = _write_back(); e) + if (int e = _write_back(); e) return e; - if(int e = _reset(); e) + if (int e = _reset(); e) return e; // Perform a read-ahead. _ensure_allocation(); size_t io_size; - if(int e = io_read(__buffer_ptr, __buffer_size, &io_size); e) { + if (int e = io_read(__buffer_ptr, __buffer_size, &io_size); e) { __status_bits |= __MLIBC_ERROR_BIT; return e; } - if(!io_size) { + if (!io_size) { __status_bits |= __MLIBC_EOF_BIT; *actual_size = 0; return 0; @@ -173,13 +172,13 @@ int abstract_file::read(char *buffer, size_t max_size, size_t *actual_size) { int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_size) { __ensure(max_size); - if(_init_bufmode()) + if (_init_bufmode()) return -1; - if(globallyDisableBuffering || _bufmode == buffer_mode::no_buffer) { + if (globallyDisableBuffering || _bufmode == buffer_mode::no_buffer) { // As we do not buffer, nothing can be dirty. __ensure(__dirty_begin == __dirty_end); size_t io_size; - if(int e = io_write(buffer, max_size, &io_size); e) { + if (int e = io_write(buffer, max_size, &io_size); e) { __status_bits |= __MLIBC_ERROR_BIT; return e; } @@ -188,10 +187,10 @@ int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_siz } // Flush the buffer if necessary. - if(__offset == __buffer_size) { - if(int e = _write_back(); e) + if (__offset == __buffer_size) { + if (int e = _write_back(); e) return e; - if(int e = _reset(); e) + if (int e = _reset(); e) return e; } @@ -199,9 +198,8 @@ int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_siz // TODO: We could full support pipe-like files // by ungetc()ing all data before a write happens, // however, for now we just report an error. - if(!__io_mode && __valid_limit) // TODO: Only check this for pipe-like streams. - mlibc::panicLogger() << "mlibc: Cannot read-write to same pipe-like stream" - << frg::endlog; + if (!__io_mode && __valid_limit) // TODO: Only check this for pipe-like streams. + mlibc::panicLogger() << "mlibc: Cannot read-write to same pipe-like stream" << frg::endlog; __io_mode = 1; __ensure(__offset < __buffer_size); @@ -209,9 +207,9 @@ int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_siz // Line-buffered streams perform I/O on full lines. bool flush_line = false; - if(_bufmode == buffer_mode::line_buffer) { + if (_bufmode == buffer_mode::line_buffer) { auto nl = reinterpret_cast(memchr(buffer, '\n', chunk)); - if(nl) { + if (nl) { chunk = nl + 1 - buffer; flush_line = true; } @@ -222,10 +220,10 @@ int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_siz _ensure_allocation(); memcpy(__buffer_ptr + __offset, buffer, chunk); - if(__dirty_begin != __dirty_end) { + if (__dirty_begin != __dirty_end) { __dirty_begin = frg::min(__dirty_begin, __offset); __dirty_end = frg::max(__dirty_end, __offset + chunk); - }else{ + } else { __dirty_begin = __offset; __dirty_end = __offset + chunk; } @@ -233,8 +231,8 @@ int abstract_file::write(const char *buffer, size_t max_size, size_t *actual_siz __offset += chunk; // Flush line-buffered streams. - if(flush_line) { - if(_write_back()) + if (flush_line) { + if (_write_back()) return -1; } @@ -261,8 +259,9 @@ int abstract_file::unget(char c) { int abstract_file::update_bufmode(buffer_mode mode) { // setvbuf() has undefined behavior if I/O has been performed. - __ensure(__dirty_begin == __dirty_end - && "update_bufmode() must only be called before performing I/O"); + __ensure( + __dirty_begin == __dirty_end && "update_bufmode() must only be called before performing I/O" + ); _bufmode = mode; return 0; } @@ -289,7 +288,7 @@ int abstract_file::flush() { int abstract_file::tell(off_t *current_offset) { off_t seek_offset; - if(int e = io_seek(0, SEEK_CUR, &seek_offset); e) + if (int e = io_seek(0, SEEK_CUR, &seek_offset); e) return e; *current_offset = seek_offset + (off_t(__offset) - off_t(__io_offset)); @@ -297,19 +296,19 @@ int abstract_file::tell(off_t *current_offset) { } int abstract_file::seek(off_t offset, int whence) { - if(int e = _write_back(); e) + if (int e = _write_back(); e) return e; off_t new_offset; - if(whence == SEEK_CUR) { + if (whence == SEEK_CUR) { auto seek_offset = offset + (off_t(__offset) - off_t(__io_offset)); - if(int e = io_seek(seek_offset, whence, &new_offset); e) { + if (int e = io_seek(seek_offset, whence, &new_offset); e) { __status_bits |= __MLIBC_ERROR_BIT; return e; } - }else{ + } else { __ensure(whence == SEEK_SET || whence == SEEK_END); - if(int e = io_seek(offset, whence, &new_offset); e) { + if (int e = io_seek(offset, whence, &new_offset); e) { __status_bits |= __MLIBC_ERROR_BIT; return e; } @@ -323,51 +322,52 @@ int abstract_file::seek(off_t offset, int whence) { } int abstract_file::_init_type() { - if(_type != stream_type::unknown) + if (_type != stream_type::unknown) return 0; - if(int e = determine_type(&_type); e) + if (int e = determine_type(&_type); e) return e; __ensure(_type != stream_type::unknown); return 0; } int abstract_file::_init_bufmode() { - if(_bufmode != buffer_mode::unknown) + if (_bufmode != buffer_mode::unknown) return 0; - if(determine_bufmode(&_bufmode)) + if (determine_bufmode(&_bufmode)) return -1; __ensure(_bufmode != buffer_mode::unknown); return 0; } int abstract_file::_write_back() { - if(int e = _init_type(); e) + if (int e = _init_type(); e) return e; - if(__dirty_begin == __dirty_end) + if (__dirty_begin == __dirty_end) return 0; // For non-pipe streams, first do a seek to reset the // I/O position to zero, then do a write(). - if(_type == stream_type::file_like) { - if(__io_offset != __dirty_begin) { + if (_type == stream_type::file_like) { + if (__io_offset != __dirty_begin) { __ensure(__dirty_begin - __io_offset > 0); off_t new_offset; - if(int e = io_seek(off_t(__dirty_begin) - off_t(__io_offset), SEEK_CUR, &new_offset); e) + if (int e = io_seek(off_t(__dirty_begin) - off_t(__io_offset), SEEK_CUR, &new_offset); + e) return e; __io_offset = __dirty_begin; } - }else{ + } else { __ensure(_type == stream_type::pipe_like); __ensure(__io_offset == __dirty_begin); } // Now, we are in the correct position to write-back everything. - while(__io_offset < __dirty_end) { + while (__io_offset < __dirty_end) { size_t io_size; - if(int e = io_write(__buffer_ptr + __io_offset, __dirty_end - __io_offset, &io_size); e) { + if (int e = io_write(__buffer_ptr + __io_offset, __dirty_end - __io_offset, &io_size); e) { __status_bits |= __MLIBC_ERROR_BIT; return e; } @@ -399,12 +399,12 @@ int abstract_file::_save_pos() { } int abstract_file::_reset() { - if(int e = _init_type(); e) + if (int e = _init_type(); e) return e; // For pipe-like files, we must not forget already read data. // TODO: Report this error to the user. - if(_type == stream_type::pipe_like) + if (_type == stream_type::pipe_like) __ensure(__offset == __valid_limit); __ensure(__dirty_begin == __dirty_end); @@ -417,7 +417,7 @@ int abstract_file::_reset() { // This may still be called when buffering is disabled, for ungetc. void abstract_file::_ensure_allocation() { - if(__buffer_ptr) + if (__buffer_ptr) return; auto ptr = getAllocator().allocate(__buffer_size + ungetBufferSize); @@ -430,17 +430,16 @@ void abstract_file::_ensure_allocation() { // -------------------------------------------------------------------------------------- fd_file::fd_file(int fd, void (*do_dispose)(abstract_file *), bool force_unbuffered) -: abstract_file{do_dispose}, _fd{fd}, _force_unbuffered{force_unbuffered} { } + : abstract_file{do_dispose}, + _fd{fd}, + _force_unbuffered{force_unbuffered} {} -int fd_file::fd() { - return _fd; -} +int fd_file::fd() { return _fd; } int fd_file::close() { - if(__dirty_begin != __dirty_end) - mlibc::infoLogger() << "mlibc warning: File is not flushed before closing" - << frg::endlog; - if(int e = mlibc::sys_close(_fd); e) + if (__dirty_begin != __dirty_end) + mlibc::infoLogger() << "mlibc warning: File is not flushed before closing" << frg::endlog; + if (int e = mlibc::sys_close(_fd); e) return e; return 0; } @@ -449,7 +448,10 @@ int fd_file::reopen(const char *path, const char *mode) { int mode_flags = parse_modestring(mode); int fd; - if(int e = sys_open(path, mode_flags, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH, &fd); e) { + if (int e = sys_open( + path, mode_flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, &fd + ); + e) { return e; } @@ -463,7 +465,7 @@ int fd_file::reopen(const char *path, const char *mode) { _reset(); _fd = fd; - if(mode_flags & O_APPEND) { + if (mode_flags & O_APPEND) { seek(0, SEEK_END); } @@ -473,45 +475,46 @@ int fd_file::reopen(const char *path, const char *mode) { int fd_file::determine_type(stream_type *type) { off_t offset; int e = mlibc::sys_seek(_fd, 0, SEEK_CUR, &offset); - if(!e) { + if (!e) { *type = stream_type::file_like; return 0; - }else if(e == ESPIPE) { + } else if (e == ESPIPE) { *type = stream_type::pipe_like; return 0; - }else{ + } else { return e; } } int fd_file::determine_bufmode(buffer_mode *mode) { // When isatty() is not implemented, we fall back to the safest default (no buffering). - if(!mlibc::sys_isatty) { + if (!mlibc::sys_isatty) { MLIBC_MISSING_SYSDEP(); *mode = buffer_mode::no_buffer; return 0; } - if(_force_unbuffered) { + if (_force_unbuffered) { *mode = buffer_mode::no_buffer; return 0; } - if(int e = mlibc::sys_isatty(_fd); !e) { + if (int e = mlibc::sys_isatty(_fd); !e) { *mode = buffer_mode::line_buffer; return 0; - }else if(e == ENOTTY) { + } else if (e == ENOTTY) { *mode = buffer_mode::full_buffer; return 0; - }else{ + } else { mlibc::infoLogger() << "mlibc: sys_isatty() failed while determining whether" - " stream is interactive" << frg::endlog; + " stream is interactive" + << frg::endlog; return -1; } } int fd_file::io_read(char *buffer, size_t max_size, size_t *actual_size) { ssize_t s; - if(int e = mlibc::sys_read(_fd, buffer, max_size, &s); e) + if (int e = mlibc::sys_read(_fd, buffer, max_size, &s); e) return e; *actual_size = s; return 0; @@ -519,14 +522,14 @@ int fd_file::io_read(char *buffer, size_t max_size, size_t *actual_size) { int fd_file::io_write(const char *buffer, size_t max_size, size_t *actual_size) { ssize_t s; - if(int e = mlibc::sys_write(_fd, buffer, max_size, &s); e) + if (int e = mlibc::sys_write(_fd, buffer, max_size, &s); e) return e; *actual_size = s; return 0; } int fd_file::io_seek(off_t offset, int whence, off_t *new_offset) { - if(int e = mlibc::sys_seek(_fd, offset, whence, new_offset); e) + if (int e = mlibc::sys_seek(_fd, offset, whence, new_offset); e) return e; return 0; } @@ -535,41 +538,41 @@ int fd_file::parse_modestring(const char *mode) { // Consume the first char; this must be 'r', 'w' or 'a'. int flags = 0; bool has_plus = strchr(mode, '+'); - if(*mode == 'r') { - if(has_plus) { + if (*mode == 'r') { + if (has_plus) { flags = O_RDWR; - }else{ + } else { flags = O_RDONLY; } - }else if(*mode == 'w') { - if(has_plus) { + } else if (*mode == 'w') { + if (has_plus) { flags = O_RDWR; - }else{ + } else { flags = O_WRONLY; } flags |= O_CREAT | O_TRUNC; - }else if(*mode == 'a') { - if(has_plus) { + } else if (*mode == 'a') { + if (has_plus) { flags = O_APPEND | O_RDWR; - }else{ + } else { flags = O_APPEND | O_WRONLY; } flags |= O_CREAT; - }else{ + } else { mlibc::infoLogger() << "Illegal fopen() mode '" << *mode << "'" << frg::endlog; } mode += 1; // Consume additional flags. - while(*mode) { - if(*mode == '+') { + while (*mode) { + if (*mode == '+') { mode++; // This is already handled above. - }else if(*mode == 'b') { + } else if (*mode == 'b') { mode++; // mlibc assumes that there is no distinction between text and binary. - }else if(*mode == 'e') { + } else if (*mode == 'e') { flags |= O_CLOEXEC; mode++; - }else{ + } else { mlibc::infoLogger() << "Illegal fopen() flag '" << mode << "'" << frg::endlog; mode++; } @@ -581,23 +584,23 @@ int fd_file::parse_modestring(const char *mode) { } // namespace mlibc namespace { - mlibc::fd_file stdin_file{0}; - mlibc::fd_file stdout_file{1}; - mlibc::fd_file stderr_file{2, nullptr, true}; - - struct stdio_guard { - stdio_guard() { } - - ~stdio_guard() { - // Only flush the files but do not close them. - for(auto it : mlibc::global_file_list()) { - if(int e = it->flush(); e) - mlibc::infoLogger() << "mlibc warning: Failed to flush file before exit()" - << frg::endlog; - } +mlibc::fd_file stdin_file{0}; +mlibc::fd_file stdout_file{1}; +mlibc::fd_file stderr_file{2, nullptr, true}; + +struct stdio_guard { + stdio_guard() {} + + ~stdio_guard() { + // Only flush the files but do not close them. + for (auto it : mlibc::global_file_list()) { + if (int e = it->flush(); e) + mlibc::infoLogger() + << "mlibc warning: Failed to flush file before exit()" << frg::endlog; } - } global_stdio_guard; -} + } +} global_stdio_guard; +} // namespace FILE *stderr = &stderr_file; FILE *stdin = &stdin_file; @@ -618,21 +621,21 @@ FILE *fopen(const char *path, const char *mode) { int flags = mlibc::fd_file::parse_modestring(mode); int fd; - if(int e = mlibc::sys_open(path, flags, 0666, &fd); e) { + if (int e = mlibc::sys_open(path, flags, 0666, &fd); e) { errno = e; return nullptr; } - return frg::construct(getAllocator(), fd, - mlibc::file_dispose_cb); + return frg::construct< + mlibc::fd_file>(getAllocator(), fd, mlibc::file_dispose_cb); } int fclose(FILE *file_base) { auto file = static_cast(file_base); int e = 0; - if(file->flush()) + if (file->flush()) e = EOF; - if(file->close()) + if (file->close()) e = EOF; file->dispose(); return e; @@ -641,7 +644,7 @@ int fclose(FILE *file_base) { int fseek(FILE *file_base, long offset, int whence) { auto file = static_cast(file_base); frg::unique_lock lock(file->_lock); - if(int e = file->seek(offset, whence); e) { + if (int e = file->seek(offset, whence); e) { errno = e; return -1; } @@ -652,7 +655,7 @@ long ftell(FILE *file_base) { auto file = static_cast(file_base); frg::unique_lock lock(file->_lock); off_t current_offset; - if(int e = file->tell(¤t_offset); e) { + if (int e = file->tell(¤t_offset); e) { errno = e; return -1; } @@ -660,28 +663,26 @@ long ftell(FILE *file_base) { } int fflush_unlocked(FILE *file_base) { - if(file_base == NULL) { + if (file_base == NULL) { // Only flush the files but do not close them. - for(auto it : mlibc::global_file_list()) { - if(int e = it->flush(); e) - mlibc::infoLogger() << "mlibc warning: Failed to flush file" - << frg::endlog; + for (auto it : mlibc::global_file_list()) { + if (int e = it->flush(); e) + mlibc::infoLogger() << "mlibc warning: Failed to flush file" << frg::endlog; } return 0; } auto file = static_cast(file_base); - if(file->flush()) + if (file->flush()) return EOF; return 0; } int fflush(FILE *file_base) { - if(file_base == NULL) { + if (file_base == NULL) { // Only flush the files but do not close them. - for(auto it : mlibc::global_file_list()) { + for (auto it : mlibc::global_file_list()) { frg::unique_lock lock(it->_lock); - if(int e = it->flush(); e) - mlibc::infoLogger() << "mlibc warning: Failed to flush file" - << frg::endlog; + if (int e = it->flush(); e) + mlibc::infoLogger() << "mlibc warning: Failed to flush file" << frg::endlog; } return 0; } @@ -696,22 +697,22 @@ int fflush(FILE *file_base) { int setvbuf(FILE *file_base, char *, int mode, size_t) { // TODO: We could also honor the buffer, but for now use just set the mode. auto file = static_cast(file_base); - if(mode == _IONBF) { - if(int e = file->update_bufmode(mlibc::buffer_mode::no_buffer); e) { + if (mode == _IONBF) { + if (int e = file->update_bufmode(mlibc::buffer_mode::no_buffer); e) { errno = e; return -1; } - }else if(mode == _IOLBF) { - if(int e = file->update_bufmode(mlibc::buffer_mode::line_buffer); e) { + } else if (mode == _IOLBF) { + if (int e = file->update_bufmode(mlibc::buffer_mode::line_buffer); e) { errno = e; return -1; } - }else if(mode == _IOFBF) { - if(int e = file->update_bufmode(mlibc::buffer_mode::full_buffer); e) { + } else if (mode == _IOFBF) { + if (int e = file->update_bufmode(mlibc::buffer_mode::full_buffer); e) { errno = e; return -1; } - }else{ + } else { errno = EINVAL; return -1; } @@ -742,4 +743,3 @@ void __fpurge(FILE *file_base) { file->purge(); } #endif - diff --git a/options/ansi/generic/inttypes.cpp b/options/ansi/generic/inttypes.cpp index ae0f9e70da..ebaad36540 100644 --- a/options/ansi/generic/inttypes.cpp +++ b/options/ansi/generic/inttypes.cpp @@ -8,9 +8,7 @@ static const char *__mlibc_digits = "0123456789abcdefghijklmnopqrstuvwxyz"; -intmax_t imaxabs(intmax_t num) { - return num < 0 ? -num : num; -} +intmax_t imaxabs(intmax_t num) { return num < 0 ? -num : num; } imaxdiv_t imaxdiv(intmax_t number, intmax_t denom) { imaxdiv_t r; r.quot = number / denom; @@ -24,10 +22,10 @@ template T strtoxmax(const char *it, char **out, int base) { const unsigned char *s = (const unsigned char *)it; int c; - if(std::is_signed::value) { - if(*s == '+') { + if (std::is_signed::value) { + if (*s == '+') { s++; - }else if(*s == '-') { + } else if (*s == '-') { negate = true; s++; } @@ -44,41 +42,41 @@ template T strtoxmax(const char *it, char **out, int base) { if (base == 0) base = c == '0' ? 8 : 10; - if(base == 8) { - if(*it != 0) + if (base == 8) { + if (*it != 0) goto parse_digits; it++; - }else if(base == 16) { - if(*it != 0) + } else if (base == 16) { + if (*it != 0) goto parse_digits; it++; - if(*it != 'x' && *it != 'X') + if (*it != 'x' && *it != 'X') goto parse_digits; it++; } parse_digits: - while(*it) { - if(isspace(*it)) { + while (*it) { + if (isspace(*it)) { it++; continue; } __ensure(base <= 10); // TODO: For base > 10 we need to implement tolower(). - //auto c = strchr(__mlibc_digits, tolower(*it)); + // auto c = strchr(__mlibc_digits, tolower(*it)); auto c = strchr(__mlibc_digits, *it); - if(!c || (c - __mlibc_digits) >= base) + if (!c || (c - __mlibc_digits) >= base) break; v = v * base + (c - __mlibc_digits); it++; } - if(std::is_signed::value) { - if(negate) + if (std::is_signed::value) { + if (negate) v = -v; } - if(out) + if (out) *out = const_cast(it); return v; } diff --git a/options/ansi/generic/locale.cpp b/options/ansi/generic/locale.cpp index 38f5859ed4..c2046b426c 100644 --- a/options/ansi/generic/locale.cpp +++ b/options/ansi/generic/locale.cpp @@ -5,72 +5,66 @@ #include -#include #include +#include namespace { - // Values of the C locale are defined by the C standard. - constexpr lconv c_lconv = { - const_cast("."), // decimal_point - const_cast(""), // thousands_sep - const_cast(""), // grouping - const_cast(""), // mon_decimal_point - const_cast(""), // mon_thousands_sep - const_cast(""), // mon_grouping - const_cast(""), // positive_sign - const_cast(""), // negative_sign - const_cast(""), // currency_symbol - CHAR_MAX, // frac_digits - CHAR_MAX, // p_cs_precedes - CHAR_MAX, // n_cs_precedes - CHAR_MAX, // p_sep_by_space - CHAR_MAX, // n_sep_by_space - CHAR_MAX, // p_sign_posn - CHAR_MAX, // n_sign_posn - const_cast(""), // int_curr_symbol - CHAR_MAX, // int_frac_digits - CHAR_MAX, // int_p_cs_precedes - CHAR_MAX, // int_n_cs_precedes - CHAR_MAX, // int_p_sep_by_space - CHAR_MAX, // int_n_sep_by_space - CHAR_MAX, // int_p_sign_posn - CHAR_MAX // int_n_sign_posn - }; -} +// Values of the C locale are defined by the C standard. +constexpr lconv c_lconv = { + const_cast("."), // decimal_point + const_cast(""), // thousands_sep + const_cast(""), // grouping + const_cast(""), // mon_decimal_point + const_cast(""), // mon_thousands_sep + const_cast(""), // mon_grouping + const_cast(""), // positive_sign + const_cast(""), // negative_sign + const_cast(""), // currency_symbol + CHAR_MAX, // frac_digits + CHAR_MAX, // p_cs_precedes + CHAR_MAX, // n_cs_precedes + CHAR_MAX, // p_sep_by_space + CHAR_MAX, // n_sep_by_space + CHAR_MAX, // p_sign_posn + CHAR_MAX, // n_sign_posn + const_cast(""), // int_curr_symbol + CHAR_MAX, // int_frac_digits + CHAR_MAX, // int_p_cs_precedes + CHAR_MAX, // int_n_cs_precedes + CHAR_MAX, // int_p_sep_by_space + CHAR_MAX, // int_n_sep_by_space + CHAR_MAX, // int_p_sign_posn + CHAR_MAX // int_n_sign_posn +}; +} // namespace namespace mlibc { - struct locale_description { - // Identifier of this locale. used in setlocale(). - const char *name; - lconv lc; - }; - - constinit const locale_description c_locale{ - .name = "C", - .lc = c_lconv - }; - - constinit const locale_description posix_locale{ - .name = "POSIX", - .lc = c_lconv - }; - - const locale_description *query_locale_description(const char *name) { - if(!strcmp(name, "C")) - return &c_locale; - if(!strcmp(name, "POSIX")) - return &posix_locale; - return nullptr; - } - - const locale_description *collate_facet; - const locale_description *ctype_facet; - const locale_description *monetary_facet; - const locale_description *numeric_facet; - const locale_description *time_facet; - const locale_description *messages_facet; +struct locale_description { + // Identifier of this locale. used in setlocale(). + const char *name; + lconv lc; +}; + +constinit const locale_description c_locale{.name = "C", .lc = c_lconv}; + +constinit const locale_description posix_locale{.name = "POSIX", .lc = c_lconv}; + +const locale_description *query_locale_description(const char *name) { + if (!strcmp(name, "C")) + return &c_locale; + if (!strcmp(name, "POSIX")) + return &posix_locale; + return nullptr; } +const locale_description *collate_facet; +const locale_description *ctype_facet; +const locale_description *monetary_facet; +const locale_description *numeric_facet; +const locale_description *time_facet; +const locale_description *messages_facet; +} // namespace mlibc + void __mlibc_initLocale() { mlibc::collate_facet = &mlibc::c_locale; mlibc::ctype_facet = &mlibc::c_locale; @@ -81,7 +75,7 @@ void __mlibc_initLocale() { } char *setlocale(int category, const char *name) { - if(category == LC_ALL) { + if (category == LC_ALL) { // ´TODO: Implement correct return value when categories differ. auto current_desc = mlibc::collate_facet; __ensure(current_desc == mlibc::ctype_facet); @@ -90,15 +84,15 @@ char *setlocale(int category, const char *name) { __ensure(current_desc == mlibc::time_facet); __ensure(current_desc == mlibc::messages_facet); - if(name) { + if (name) { // Our default C locale is the C locale. - if(!strlen(name)) + if (!strlen(name)) name = "C"; auto new_desc = mlibc::query_locale_description(name); - if(!new_desc) { - mlibc::infoLogger() << "mlibc: Locale " << name - << " is not supported" << frg::endlog; + if (!new_desc) { + mlibc::infoLogger() + << "mlibc: Locale " << name << " is not supported" << frg::endlog; return nullptr; } @@ -110,9 +104,9 @@ char *setlocale(int category, const char *name) { mlibc::messages_facet = new_desc; } return const_cast(current_desc->name); - }else{ + } else { const mlibc::locale_description **facet_ptr; - switch(category) { + switch (category) { case LC_COLLATE: facet_ptr = &mlibc::collate_facet; break; @@ -133,20 +127,20 @@ char *setlocale(int category, const char *name) { break; default: mlibc::infoLogger() << "mlibc: Unexpected value " << category - << " for category in setlocale()" << frg::endlog; + << " for category in setlocale()" << frg::endlog; return nullptr; } auto current_desc = *facet_ptr; - if(name) { + if (name) { // Our default C locale is the C locale. - if(!strlen(name)) + if (!strlen(name)) name = "C"; auto new_desc = mlibc::query_locale_description(name); - if(!new_desc) { - mlibc::infoLogger() << "mlibc: Locale " << name - << " is not supported" << frg::endlog; + if (!new_desc) { + mlibc::infoLogger() + << "mlibc: Locale " << name << " is not supported" << frg::endlog; return nullptr; } @@ -157,7 +151,7 @@ char *setlocale(int category, const char *name) { } namespace { - lconv effective_lc; +lconv effective_lc; } struct lconv *localeconv(void) { diff --git a/options/ansi/generic/signal.cpp b/options/ansi/generic/signal.cpp index 0e1b44f271..ad6b49fae9 100644 --- a/options/ansi/generic/signal.cpp +++ b/options/ansi/generic/signal.cpp @@ -3,8 +3,8 @@ #include #include -#include #include +#include __sighandler signal(int sn, __sighandler handler) { struct sigaction sa; @@ -13,7 +13,7 @@ __sighandler signal(int sn, __sighandler handler) { sigemptyset(&sa.sa_mask); struct sigaction old; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sigaction, SIG_ERR); - if(int e = mlibc::sys_sigaction(sn, &sa, &old)){ + if (int e = mlibc::sys_sigaction(sn, &sa, &old)) { errno = e; return SIG_ERR; } @@ -35,10 +35,9 @@ int raise(int sig) { // This is a POSIX extension, but we have it in here for sigsetjmp int sigprocmask(int how, const sigset_t *__restrict set, sigset_t *__restrict retrieve) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sigprocmask, -1); - if(int e = mlibc::sys_sigprocmask(how, set, retrieve); e) { + if (int e = mlibc::sys_sigprocmask(how, set, retrieve); e) { errno = e; return -1; } return 0; } - diff --git a/options/ansi/generic/stdio.cpp b/options/ansi/generic/stdio.cpp index 2b8a55cb38..f6ed07aeea 100644 --- a/options/ansi/generic/stdio.cpp +++ b/options/ansi/generic/stdio.cpp @@ -1,44 +1,41 @@ #include #include +#include #include -#include -#include #include +#include #include +#include #include -#include -#include #include #include -#include +#include +#include +#include #include +#include #include #include -#include -#include -#include -#include +#include -template -struct PrintfAgent { - PrintfAgent(F *formatter, frg::va_struct *vsp) - : _formatter{formatter}, _vsp{vsp} { } +template struct PrintfAgent { + PrintfAgent(F *formatter, frg::va_struct *vsp) : _formatter{formatter}, _vsp{vsp} {} - frg::expected operator() (char c) { + frg::expected operator()(char c) { _formatter->append(c); return {}; } - frg::expected operator() (const char *c, size_t n) { + frg::expected operator()(const char *c, size_t n) { _formatter->append(c, n); return {}; } - frg::expected operator() (char t, frg::format_options opts, - frg::printf_size_mod szmod) { - switch(t) { + frg::expected + operator()(char t, frg::format_options opts, frg::printf_size_mod szmod) { + switch (t) { case 'c': if (szmod == frg::printf_size_mod::long_size) { char c_buf[sizeof(wchar_t)]; @@ -51,13 +48,26 @@ struct PrintfAgent { } frg::do_printf_chars(*_formatter, t, opts, szmod, _vsp); break; - case 'p': case 's': + case 'p': + case 's': frg::do_printf_chars(*_formatter, t, opts, szmod, _vsp); break; - case 'd': case 'i': case 'o': case 'x': case 'X': case 'b': case 'B': case 'u': + case 'd': + case 'i': + case 'o': + case 'x': + case 'X': + case 'b': + case 'B': + case 'u': frg::do_printf_ints(*_formatter, t, opts, szmod, _vsp); break; - case 'f': case 'F': case 'g': case 'G': case 'e': case 'E': + case 'f': + case 'F': + case 'g': + case 'G': + case 'e': + case 'E': frg::do_printf_floats(*_formatter, t, opts, szmod, _vsp); break; case 'm': @@ -76,22 +86,21 @@ struct PrintfAgent { break; } default: - mlibc::infoLogger() << "\e[31mmlibc: Unknown printf terminator '" - << t << "'\e[39m" << frg::endlog; + mlibc::infoLogger() << "\e[31mmlibc: Unknown printf terminator '" << t << "'\e[39m" + << frg::endlog; __ensure(!"Illegal printf terminator"); } return {}; } -private: + private: F *_formatter; frg::va_struct *_vsp; }; struct StreamPrinter { - StreamPrinter(FILE *stream) - : stream(stream), count(0) { } + StreamPrinter(FILE *stream) : stream(stream), count(0) {} void append(char c) { fwrite_unlocked(&c, 1, 1, stream); @@ -113,8 +122,7 @@ struct StreamPrinter { }; struct BufferPrinter { - BufferPrinter(char *buffer) - : buffer(buffer), count(0) { } + BufferPrinter(char *buffer) : buffer(buffer), count(0) {} void append(char c) { buffer[count] = c; @@ -123,7 +131,7 @@ struct BufferPrinter { void append(const char *str) { // TODO: use strcat - for(size_t i = 0; str[i]; i++) { + for (size_t i = 0; str[i]; i++) { buffer[count] = str[i]; count++; } @@ -131,7 +139,7 @@ struct BufferPrinter { void append(const char *str, size_t n) { // TODO: use strcat - for(size_t i = 0; i < n; i++) { + for (size_t i = 0; i < n; i++) { buffer[count] = str[i]; count++; } @@ -142,24 +150,23 @@ struct BufferPrinter { }; struct LimitedPrinter { - LimitedPrinter(char *buffer, size_t limit) - : buffer(buffer), limit(limit), count(0) { } + LimitedPrinter(char *buffer, size_t limit) : buffer(buffer), limit(limit), count(0) {} void append(char c) { - if(count < limit) + if (count < limit) buffer[count] = c; count++; } void append(const char *str) { // TODO: use strcat - for(size_t i = 0; str[i]; i++) + for (size_t i = 0; str[i]; i++) append(str[i]); } void append(const char *str, size_t n) { // TODO: use strcat - for(size_t i = 0; i < n; i++) + for (size_t i = 0; i < n; i++) append(str[i]); } @@ -169,11 +176,10 @@ struct LimitedPrinter { }; struct ResizePrinter { - ResizePrinter() - : buffer(nullptr), limit(0), count(0) { } + ResizePrinter() : buffer(nullptr), limit(0), count(0) {} void expand() { - if(count == limit) { + if (count == limit) { auto new_limit = frg::max(2 * limit, size_t(16)); auto new_buffer = reinterpret_cast(malloc(new_limit)); __ensure(new_buffer); @@ -192,12 +198,12 @@ struct ResizePrinter { } void append(const char *str) { - for(size_t i = 0; str[i]; i++) + for (size_t i = 0; str[i]; i++) append(str[i]); } void append(const char *str, size_t n) { - for(size_t i = 0; i < n; i++) + for (size_t i = 0; i < n; i++) append(str[i]); } @@ -208,10 +214,10 @@ struct ResizePrinter { int remove(const char *filename) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_rmdir, -1); - if(int e = mlibc::sys_rmdir(filename); e) { + if (int e = mlibc::sys_rmdir(filename); e) { if (e == ENOTDIR) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_unlinkat, -1); - if(e = mlibc::sys_unlinkat(AT_FDCWD, filename, 0); e) { + if (e = mlibc::sys_unlinkat(AT_FDCWD, filename, 0); e) { errno = e; return -1; } @@ -226,7 +232,7 @@ int remove(const char *filename) { int rename(const char *path, const char *new_path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_rename, -1); - if(int e = mlibc::sys_rename(path, new_path); e) { + if (int e = mlibc::sys_rename(path, new_path); e) { errno = e; return -1; } @@ -235,7 +241,7 @@ int rename(const char *path, const char *new_path) { int renameat(int olddirfd, const char *old_path, int newdirfd, const char *new_path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_renameat, -1); - if(int e = mlibc::sys_renameat(olddirfd, old_path, newdirfd, new_path); e) { + if (int e = mlibc::sys_renameat(olddirfd, old_path, newdirfd, new_path); e) { errno = e; return -1; } @@ -258,12 +264,12 @@ FILE *freopen(const char *__restrict path, const char *__restrict mode, FILE *__ auto file = static_cast(f); frg::unique_lock lock(file->_lock); - if(file->reopen(path, mode) == -1) { + if (file->reopen(path, mode) == -1) { errno = EINVAL; return nullptr; } - return f; + return f; } void setbuf(FILE *__restrict stream, char *__restrict buffer) { @@ -271,13 +277,9 @@ void setbuf(FILE *__restrict stream, char *__restrict buffer) { } // setvbuf() is provided by the POSIX sublibrary -void setlinebuf(FILE *stream) { - setvbuf(stream, NULL, _IOLBF, 0); -} +void setlinebuf(FILE *stream) { setvbuf(stream, NULL, _IOLBF, 0); } -void setbuffer(FILE *f, char *buf, size_t size) { - setvbuf(f, buf, buf ? _IOFBF : _IONBF, size); -} +void setbuffer(FILE *f, char *buf, size_t size) { setvbuf(f, buf, buf ? _IOFBF : _IONBF, size); } int fprintf(FILE *__restrict stream, const char *__restrict format, ...) { va_list args; @@ -304,59 +306,63 @@ int printf(const char *__restrict format, ...) { } namespace { - enum { - SCANF_TYPE_CHAR, - SCANF_TYPE_SHORT, - SCANF_TYPE_INTMAX, - SCANF_TYPE_L, - SCANF_TYPE_LL, - SCANF_TYPE_PTRDIFF, - SCANF_TYPE_SIZE_T, - SCANF_TYPE_INT - }; +enum { + SCANF_TYPE_CHAR, + SCANF_TYPE_SHORT, + SCANF_TYPE_INTMAX, + SCANF_TYPE_L, + SCANF_TYPE_LL, + SCANF_TYPE_PTRDIFF, + SCANF_TYPE_SIZE_T, + SCANF_TYPE_INT +}; } static void store_int(void *dest, unsigned int size, unsigned long long i) { switch (size) { - case SCANF_TYPE_CHAR: - *(char *)dest = i; - break; - case SCANF_TYPE_SHORT: - *(short *)dest = i; - break; - case SCANF_TYPE_INTMAX: - *(intmax_t *)dest = i; - break; - case SCANF_TYPE_L: - *(long *)dest = i; - break; - case SCANF_TYPE_LL: - *(long long *)dest = i; - break; - case SCANF_TYPE_PTRDIFF: - *(ptrdiff_t *)dest = i; - break; - case SCANF_TYPE_SIZE_T: - *(size_t *)dest = i; - break; - /* fallthrough */ - case SCANF_TYPE_INT: - default: - *(int *)dest = i; - break; + case SCANF_TYPE_CHAR: + *(char *)dest = i; + break; + case SCANF_TYPE_SHORT: + *(short *)dest = i; + break; + case SCANF_TYPE_INTMAX: + *(intmax_t *)dest = i; + break; + case SCANF_TYPE_L: + *(long *)dest = i; + break; + case SCANF_TYPE_LL: + *(long long *)dest = i; + break; + case SCANF_TYPE_PTRDIFF: + *(ptrdiff_t *)dest = i; + break; + case SCANF_TYPE_SIZE_T: + *(size_t *)dest = i; + break; + /* fallthrough */ + case SCANF_TYPE_INT: + default: + *(int *)dest = i; + break; } } -template -static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { - #define NOMATCH_CHECK(cond) if(cond) return match_count // if cond is true, matching error - #define EOF_CHECK(cond) if(cond) return match_count ? match_count : EOF // if cond is true, no more data to read +template static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { +#define NOMATCH_CHECK(cond) \ + if (cond) \ + return match_count // if cond is true, matching error +#define EOF_CHECK(cond) \ + if (cond) \ + return match_count ? match_count : EOF // if cond is true, no more data to read int match_count = 0; for (; *fmt; fmt++) { if (isspace(*fmt)) { - while (isspace(fmt[1])) fmt++; + while (isspace(fmt[1])) + fmt++; while (isspace(handler.look_ahead())) - handler.consume(); + handler.consume(); continue; } @@ -376,7 +382,7 @@ static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { fmt += 3; } else { if (fmt[1] != '*') { - dest = va_arg(args, void*); + dest = va_arg(args, void *); } fmt++; } @@ -386,12 +392,12 @@ static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { int count = 0; const auto append_to_buffer = [&](char c) { - if(allocate_buf) { + if (allocate_buf) { temp_dest += c; count++; } else { char *typed_dest = (char *)dest; - if(typed_dest) + if (typed_dest) typed_dest[count++] = c; } }; @@ -421,51 +427,51 @@ static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { unsigned int type = SCANF_TYPE_INT; unsigned int base = 10; switch (*fmt) { - case 'h': { - if (fmt[1] == 'h') { - type = SCANF_TYPE_CHAR; - fmt += 2; - break; - } - type = SCANF_TYPE_SHORT; - fmt++; - break; - } - case 'j': { - type = SCANF_TYPE_INTMAX; - fmt++; - break; - } - case 'l': { - if (fmt[1] == 'l') { - type = SCANF_TYPE_LL; - fmt += 2; - break; - } - type = SCANF_TYPE_L; - fmt++; - break; - } - case 'L': { - type = SCANF_TYPE_LL; - fmt++; + case 'h': { + if (fmt[1] == 'h') { + type = SCANF_TYPE_CHAR; + fmt += 2; break; } - case 'q': { + type = SCANF_TYPE_SHORT; + fmt++; + break; + } + case 'j': { + type = SCANF_TYPE_INTMAX; + fmt++; + break; + } + case 'l': { + if (fmt[1] == 'l') { type = SCANF_TYPE_LL; - fmt++; - break; - } - case 't': { - type = SCANF_TYPE_PTRDIFF; - fmt++; - break; - } - case 'z': { - type = SCANF_TYPE_SIZE_T; - fmt++; + fmt += 2; break; } + type = SCANF_TYPE_L; + fmt++; + break; + } + case 'L': { + type = SCANF_TYPE_LL; + fmt++; + break; + } + case 'q': { + type = SCANF_TYPE_LL; + fmt++; + break; + } + case 't': { + type = SCANF_TYPE_PTRDIFF; + fmt++; + break; + } + case 'z': { + type = SCANF_TYPE_SIZE_T; + fmt++; + break; + } } // Leading whitespace is skipped for most conversions except these. @@ -475,106 +481,43 @@ static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { } switch (*fmt) { - case 'd': - case 'u': - base = 10; - [[fallthrough]]; - case 'i': { - bool is_negative = false; - unsigned long long res = 0; - char c = handler.look_ahead(); - EOF_CHECK(c == '\0'); - - if((*fmt == 'i' || *fmt == 'd') && c == '-') { - handler.consume(); - is_negative = true; - } - - if(*fmt == 'i' && handler.look_ahead() == '0') { - handler.consume(); - if(handler.look_ahead() == 'x') { - handler.consume(); - base = 16; - } else { - base = 8; - } - } + case 'd': + case 'u': + base = 10; + [[fallthrough]]; + case 'i': { + bool is_negative = false; + unsigned long long res = 0; + char c = handler.look_ahead(); + EOF_CHECK(c == '\0'); - c = handler.look_ahead(); - int count = 0; - switch (base) { - case 10: - NOMATCH_CHECK(!isdigit(c)); - while (c >= '0' && c <= '9') { - handler.consume(); - res = res * 10 + (c - '0'); - c = handler.look_ahead(); - } - break; - case 16: - while (true) { - if (c >= '0' && c <= '9') { - handler.consume(); - res = res * 16 + (c - '0'); - } else if (c >= 'a' && c <= 'f') { - handler.consume(); - res = res * 16 + (c - 'a' + 10); - } else if (c >= 'A' && c <= 'F') { - handler.consume(); - res = res * 16 + (c - 'A' + 10); - } else { - break; - } - count++; - c = handler.look_ahead(); - } - NOMATCH_CHECK(count == 0); - break; - case 8: - while (c >= '0' && c <= '7') { - handler.consume(); - res = res * 8 + (c - '0'); - c = handler.look_ahead(); - } - break; - // no need for a match check, the starting 0 was already consumed - } - if (dest) { - if(is_negative) - store_int(dest, type, -res); - else - store_int(dest, type, res); - } - break; + if ((*fmt == 'i' || *fmt == 'd') && c == '-') { + handler.consume(); + is_negative = true; } - case 'o': { - unsigned long long res = 0; - char c = handler.look_ahead(); - EOF_CHECK(c == '\0'); - NOMATCH_CHECK(!(c >= '0' && c <= '7')); - while (c >= '0' && c <= '7') { + + if (*fmt == 'i' && handler.look_ahead() == '0') { + handler.consume(); + if (handler.look_ahead() == 'x') { handler.consume(); - res = res * 8 + (c - '0'); - c = handler.look_ahead(); + base = 16; + } else { + base = 8; } - if (dest) - store_int(dest, type, res); - break; } - case 'x': - case 'X': { - unsigned long long res = 0; - char c = handler.look_ahead(); - int count = 0; - EOF_CHECK(c == '\0'); - if (c == '0') { + + c = handler.look_ahead(); + int count = 0; + switch (base) { + case 10: + NOMATCH_CHECK(!isdigit(c)); + while (c >= '0' && c <= '9') { handler.consume(); + res = res * 10 + (c - '0'); c = handler.look_ahead(); - if (c == 'x') { - handler.consume(); - c = handler.look_ahead(); - } } + break; + case 16: while (true) { if (c >= '0' && c <= '9') { handler.consume(); @@ -592,153 +535,217 @@ static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { c = handler.look_ahead(); } NOMATCH_CHECK(count == 0); - if (dest) - store_int(dest, type, res); break; - } - case 'b': { - unsigned long long res = 0; - char c = handler.look_ahead(); - int count = 0; - EOF_CHECK(c == '\0'); - if (c == '0') { + case 8: + while (c >= '0' && c <= '7') { handler.consume(); - c = handler.look_ahead(); - if (c == 'b' || c == 'B') { - handler.consume(); - c = handler.look_ahead(); - } - } - while (true) { - if (c == '0' || c == '1') { - handler.consume(); - res = res * 2 + (c - '0'); - } else { - break; - } - count++; + res = res * 8 + (c - '0'); c = handler.look_ahead(); } - NOMATCH_CHECK(count == 0); - if (dest) - store_int(dest, type, res); break; + // no need for a match check, the starting 0 was already consumed + } + if (dest) { + if (is_negative) + store_int(dest, type, -res); + else + store_int(dest, type, res); } - case 's': { - char c = handler.look_ahead(); - EOF_CHECK(c == '\0'); - while (c && !isspace(c)) { + break; + } + case 'o': { + unsigned long long res = 0; + char c = handler.look_ahead(); + EOF_CHECK(c == '\0'); + NOMATCH_CHECK(!(c >= '0' && c <= '7')); + while (c >= '0' && c <= '7') { + handler.consume(); + res = res * 8 + (c - '0'); + c = handler.look_ahead(); + } + if (dest) + store_int(dest, type, res); + break; + } + case 'x': + case 'X': { + unsigned long long res = 0; + char c = handler.look_ahead(); + int count = 0; + EOF_CHECK(c == '\0'); + if (c == '0') { + handler.consume(); + c = handler.look_ahead(); + if (c == 'x') { handler.consume(); - append_to_buffer(c); c = handler.look_ahead(); - if (width && count >= width) - break; } - NOMATCH_CHECK(count == 0); - append_to_buffer('\0'); - break; } - case 'c': { - char c = handler.look_ahead(); - EOF_CHECK(c == '\0'); - if (!width) - width = 1; - while (c && count < width) { + while (true) { + if (c >= '0' && c <= '9') { + handler.consume(); + res = res * 16 + (c - '0'); + } else if (c >= 'a' && c <= 'f') { + handler.consume(); + res = res * 16 + (c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + handler.consume(); + res = res * 16 + (c - 'A' + 10); + } else { + break; + } + count++; + c = handler.look_ahead(); + } + NOMATCH_CHECK(count == 0); + if (dest) + store_int(dest, type, res); + break; + } + case 'b': { + unsigned long long res = 0; + char c = handler.look_ahead(); + int count = 0; + EOF_CHECK(c == '\0'); + if (c == '0') { + handler.consume(); + c = handler.look_ahead(); + if (c == 'b' || c == 'B') { handler.consume(); - append_to_buffer(c); c = handler.look_ahead(); - count++; } - break; } - case '[': { - fmt++; - int invert = 0; - if (*fmt == '^') { - invert = 1; - fmt++; + while (true) { + if (c == '0' || c == '1') { + handler.consume(); + res = res * 2 + (c - '0'); + } else { + break; } + count++; + c = handler.look_ahead(); + } + NOMATCH_CHECK(count == 0); + if (dest) + store_int(dest, type, res); + break; + } + case 's': { + char c = handler.look_ahead(); + EOF_CHECK(c == '\0'); + while (c && !isspace(c)) { + handler.consume(); + append_to_buffer(c); + c = handler.look_ahead(); + if (width && count >= width) + break; + } + NOMATCH_CHECK(count == 0); + append_to_buffer('\0'); + break; + } + case 'c': { + char c = handler.look_ahead(); + EOF_CHECK(c == '\0'); + if (!width) + width = 1; + while (c && count < width) { + handler.consume(); + append_to_buffer(c); + c = handler.look_ahead(); + count++; + } + break; + } + case '[': { + fmt++; + int invert = 0; + if (*fmt == '^') { + invert = 1; + fmt++; + } - char scanset[257]; - memset(&scanset[0], invert, sizeof(char) * 257); - scanset[0] = '\0'; + char scanset[257]; + memset(&scanset[0], invert, sizeof(char) * 257); + scanset[0] = '\0'; - if (*fmt == '-') { - fmt++; - scanset[1+'-'] = 1 - invert; - } else if (*fmt == ']') { + if (*fmt == '-') { + fmt++; + scanset[1 + '-'] = 1 - invert; + } else if (*fmt == ']') { + fmt++; + scanset[1 + ']'] = 1 - invert; + } + + for (; *fmt != ']'; fmt++) { + if (!*fmt) + return EOF; + if (*fmt == '-' && *fmt != ']') { fmt++; - scanset[1+']'] = 1 - invert; + for (char c = *(fmt - 2); c < *fmt; c++) + scanset[1 + c] = 1 - invert; } + scanset[1 + *fmt] = 1 - invert; + } - for (; *fmt != ']'; fmt++) { - if (!*fmt) return EOF; - if (*fmt == '-' && *fmt != ']') { - fmt++; - for (char c = *(fmt - 2); c < *fmt; c++) - scanset[1 + c] = 1 - invert; - } - scanset[1 + *fmt] = 1 - invert; - } + char c = handler.look_ahead(); + EOF_CHECK(c == '\0'); + while (c && (!width || count < width)) { + handler.consume(); + if (!scanset[1 + c]) + break; + append_to_buffer(c); + c = handler.look_ahead(); + } + NOMATCH_CHECK(count == 0); + append_to_buffer('\0'); + break; + } + case 'p': { + unsigned long long res = 0; + char c = handler.look_ahead(); + int count = 0; + EOF_CHECK(c == '\0'); - char c = handler.look_ahead(); - EOF_CHECK(c == '\0'); - while (c && (!width || count < width)) { + if (c == '0') { + handler.consume(); + c = handler.look_ahead(); + if (c == 'x') { handler.consume(); - if (!scanset[1 + c]) - break; - append_to_buffer(c); c = handler.look_ahead(); } - NOMATCH_CHECK(count == 0); - append_to_buffer('\0'); - break; } - case 'p': { - unsigned long long res = 0; - char c = handler.look_ahead(); - int count = 0; - EOF_CHECK(c == '\0'); - if (c == '0') { + while (true) { + if (c >= '0' && c <= '9') { handler.consume(); - c = handler.look_ahead(); - if (c == 'x') { - handler.consume(); - c = handler.look_ahead(); - } - } - - while (true) { - if (c >= '0' && c <= '9') { - handler.consume(); - res = res * 16 + (c - '0'); - } else if (c >= 'a' && c <= 'f') { - handler.consume(); - res = res * 16 + (c - 'a'); - } else if (c >= 'A' && c <= 'F') { - handler.consume(); - res = res * 16 + (c - 'A'); - } else { - break; - } - count++; - c = handler.look_ahead(); + res = res * 16 + (c - '0'); + } else if (c >= 'a' && c <= 'f') { + handler.consume(); + res = res * 16 + (c - 'a'); + } else if (c >= 'A' && c <= 'F') { + handler.consume(); + res = res * 16 + (c - 'A'); + } else { + break; } - NOMATCH_CHECK(count == 0); - void **typed_dest = (void **)dest; - *typed_dest = (void *)(uintptr_t)res; - break; - } - case 'n': { - int *typed_dest = (int *)dest; - if (typed_dest) - *typed_dest = handler.num_consumed; - continue; + count++; + c = handler.look_ahead(); } + NOMATCH_CHECK(count == 0); + void **typed_dest = (void **)dest; + *typed_dest = (void *)(uintptr_t)res; + break; + } + case 'n': { + int *typed_dest = (int *)dest; + if (typed_dest) + *typed_dest = handler.num_consumed; + continue; + } } - if(allocate_buf && dest) { + if (allocate_buf && dest) { char *temp = (char *)getAllocator().allocate(temp_dest.size() + 1); memcpy(temp, temp_dest.data(), temp_dest.size()); temp[temp_dest.size()] = '\0'; @@ -747,7 +754,8 @@ static int do_scanf(H &handler, const char *fmt, __builtin_va_list args) { *dest_ptr = temp; } - if (dest) match_count++; + if (dest) + match_count++; } return match_count; } @@ -794,7 +802,7 @@ int vfprintf(FILE *__restrict stream, const char *__restrict format, __builtin_v auto file = static_cast(stream); frg::unique_lock lock(file->_lock); StreamPrinter p{stream}; -// mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; + // mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; auto res = frg::printf_format(PrintfAgent{&p, &vs}, format, &vs); if (!res) return -static_cast(res.error()); @@ -832,7 +840,7 @@ int vfscanf(FILE *__restrict stream, const char *__restrict format, __builtin_va return do_scanf(handler, format, args); } -int vprintf(const char *__restrict format, __builtin_va_list args){ +int vprintf(const char *__restrict format, __builtin_va_list args) { return vfprintf(stdout, format, args); } @@ -841,14 +849,15 @@ int vscanf(const char *__restrict, __builtin_va_list) { __builtin_unreachable(); } -int vsnprintf(char *__restrict buffer, size_t max_size, - const char *__restrict format, __builtin_va_list args) { +int vsnprintf( + char *__restrict buffer, size_t max_size, const char *__restrict format, __builtin_va_list args +) { frg::va_struct vs; frg::arg arg_list[NL_ARGMAX + 1]; vs.arg_list = arg_list; va_copy(vs.args, args); LimitedPrinter p{buffer, max_size ? max_size - 1 : 0}; -// mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; + // mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; auto res = frg::printf_format(PrintfAgent{&p, &vs}, format, &vs); if (!res) return -static_cast(res.error()); @@ -863,7 +872,7 @@ int vsprintf(char *__restrict buffer, const char *__restrict format, __builtin_v vs.arg_list = arg_list; va_copy(vs.args, args); BufferPrinter p(buffer); -// mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; + // mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; auto res = frg::printf_format(PrintfAgent{&p, &vs}, format, &vs); if (!res) return -static_cast(res.error()); @@ -873,9 +882,7 @@ int vsprintf(char *__restrict buffer, const char *__restrict format, __builtin_v int vsscanf(const char *__restrict buffer, const char *__restrict format, __builtin_va_list args) { struct { - char look_ahead() { - return *buffer; - } + char look_ahead() { return *buffer; } char consume() { num_consumed++; @@ -892,24 +899,30 @@ int vsscanf(const char *__restrict buffer, const char *__restrict format, __buil } int fwprintf(FILE *__restrict, const wchar_t *__restrict, ...) MLIBC_STUB_BODY -int fwscanf(FILE *__restrict, const wchar_t *__restrict, ...) MLIBC_STUB_BODY -int vfwprintf(FILE *__restrict, const wchar_t *__restrict, __builtin_va_list) MLIBC_STUB_BODY -int vfwscanf(FILE *__restrict, const wchar_t *__restrict, __builtin_va_list) MLIBC_STUB_BODY + int fwscanf(FILE *__restrict, const wchar_t *__restrict, ...) MLIBC_STUB_BODY + int vfwprintf(FILE *__restrict, const wchar_t *__restrict, __builtin_va_list) +MLIBC_STUB_BODY +int vfwscanf(FILE *__restrict, const wchar_t *__restrict, __builtin_va_list) +MLIBC_STUB_BODY int swprintf(wchar_t *__restrict, size_t, const wchar_t *__restrict, ...) MLIBC_STUB_BODY -int swscanf(wchar_t *__restrict, const wchar_t *__restrict, ...) MLIBC_STUB_BODY -int vswprintf(wchar_t *__restrict, size_t, const wchar_t *__restrict, __builtin_va_list) MLIBC_STUB_BODY -int vswscanf(wchar_t *__restrict, const wchar_t *__restrict, __builtin_va_list) MLIBC_STUB_BODY + int swscanf(wchar_t *__restrict, const wchar_t *__restrict, ...) MLIBC_STUB_BODY + int vswprintf(wchar_t *__restrict, size_t, const wchar_t *__restrict, __builtin_va_list) +MLIBC_STUB_BODY +int vswscanf(wchar_t *__restrict, const wchar_t *__restrict, __builtin_va_list) +MLIBC_STUB_BODY int wprintf(const wchar_t *__restrict, ...) MLIBC_STUB_BODY -int wscanf(const wchar_t *__restrict, ...) MLIBC_STUB_BODY -int vwprintf(const wchar_t *__restrict, __builtin_va_list) MLIBC_STUB_BODY -int vwscanf(const wchar_t *__restrict, __builtin_va_list) MLIBC_STUB_BODY + int wscanf(const wchar_t *__restrict, ...) MLIBC_STUB_BODY + int vwprintf(const wchar_t *__restrict, __builtin_va_list) +MLIBC_STUB_BODY +int vwscanf(const wchar_t *__restrict, __builtin_va_list) +MLIBC_STUB_BODY int fgetc(FILE *stream) { char c; auto bytes_read = fread(&c, 1, 1, stream); - if(bytes_read != 1) + if (bytes_read != 1) return EOF; return c; } @@ -922,7 +935,7 @@ char *fgets(char *__restrict buffer, int max_size, FILE *__restrict stream) { int fputc_unlocked(int c, FILE *stream) { char d = c; - if(fwrite_unlocked(&d, 1, 1, stream) != 1) + if (fwrite_unlocked(&d, 1, 1, stream) != 1) return EOF; return 1; } @@ -934,7 +947,7 @@ int fputc(int c, FILE *stream) { } int fputs_unlocked(const char *__restrict string, FILE *__restrict stream) { - if(fwrite_unlocked(string, strlen(string), 1, stream) != 1) + if (fwrite_unlocked(string, strlen(string), 1, stream) != 1) return EOF; return 1; } @@ -945,29 +958,19 @@ int fputs(const char *__restrict string, FILE *__restrict stream) { return fputs_unlocked(string, stream); } -int getc_unlocked(FILE *stream) { - return fgetc_unlocked(stream); -} +int getc_unlocked(FILE *stream) { return fgetc_unlocked(stream); } -int getc(FILE *stream) { - return fgetc(stream); -} +int getc(FILE *stream) { return fgetc(stream); } -int getchar_unlocked(void) { - return fgetc_unlocked(stdin); -} +int getchar_unlocked(void) { return fgetc_unlocked(stdin); } -int getchar(void) { - return fgetc(stdin); -} +int getchar(void) { return fgetc(stdin); } -char *gets(char *s){ - return fgets(s, INT_MAX, stdin); -} +char *gets(char *s) { return fgets(s, INT_MAX, stdin); } int putc_unlocked(int c, FILE *stream) { char d = c; - if(fwrite_unlocked(&d, 1, 1, stream) != 1) + if (fwrite_unlocked(&d, 1, 1, stream) != 1) return EOF; return c; } @@ -978,9 +981,7 @@ int putc(int c, FILE *stream) { return putc_unlocked(c, stream); } -int putchar_unlocked(int c) { - return putc_unlocked(c, stdout); -} +int putchar_unlocked(int c) { return putc_unlocked(c, stdout); } int putchar(int c) { auto file = static_cast(stdout); @@ -994,12 +995,11 @@ int puts(const char *string) { size_t progress = 0; size_t len = strlen(string); - while(progress < len) { + while (progress < len) { size_t chunk; - if(file->write(string + progress, - len - progress, &chunk)) { + if (file->write(string + progress, len - progress, &chunk)) { return EOF; - }else if(!chunk) { + } else if (!chunk) { return EOF; } @@ -1014,24 +1014,22 @@ int puts(const char *string) { return 1; } -wint_t fgetwc(FILE *) MLIBC_STUB_BODY -wchar_t *fgetws(wchar_t *__restrict, int, FILE *__restrict) MLIBC_STUB_BODY -wint_t fputwc(wchar_t, FILE *) MLIBC_STUB_BODY -int fputws(const wchar_t *__restrict, FILE *__restrict) MLIBC_STUB_BODY -int fwide(FILE *, int) MLIBC_STUB_BODY -wint_t getwc(FILE *) MLIBC_STUB_BODY -wint_t getwchar(void) MLIBC_STUB_BODY -wint_t putwc(wchar_t, FILE *) MLIBC_STUB_BODY -wint_t putwchar(wchar_t) MLIBC_STUB_BODY +wint_t fgetwc(FILE *) MLIBC_STUB_BODY wchar_t *fgetws(wchar_t *__restrict, int, FILE *__restrict) + MLIBC_STUB_BODY wint_t fputwc(wchar_t, FILE *) MLIBC_STUB_BODY + int fputws(const wchar_t *__restrict, FILE *__restrict) MLIBC_STUB_BODY + int fwide(FILE *, int) MLIBC_STUB_BODY wint_t getwc(FILE *) MLIBC_STUB_BODY wint_t + getwchar(void) MLIBC_STUB_BODY wint_t putwc(wchar_t, FILE *) MLIBC_STUB_BODY wint_t + putwchar(wchar_t) +MLIBC_STUB_BODY wint_t ungetwc(wint_t, FILE *) MLIBC_STUB_BODY -size_t fread(void *buffer, size_t size, size_t count, FILE *file_base) { + size_t fread(void *buffer, size_t size, size_t count, FILE *file_base) { auto file = static_cast(file_base); frg::unique_lock lock(file->_lock); return fread_unlocked(buffer, size, count, file_base); } -size_t fwrite(const void *buffer, size_t size , size_t count, FILE *file_base) { +size_t fwrite(const void *buffer, size_t size, size_t count, FILE *file_base) { auto file = static_cast(file_base); frg::unique_lock lock(file->_lock); return fwrite_unlocked(buffer, size, count, file_base); @@ -1041,7 +1039,7 @@ int fgetpos(FILE *__restrict f, fpos_t *__restrict out) { auto file = static_cast(f); off_t current_offset; - if(int e = file->tell(¤t_offset); e) { + if (int e = file->tell(¤t_offset); e) { errno = e; return -1; } @@ -1055,7 +1053,7 @@ int fgetpos(FILE *__restrict f, fpos_t *__restrict out) { int fsetpos(FILE *f, const fpos_t *pos) { auto file = static_cast(f); frg::unique_lock lock(file->_lock); - if(int e = file->seek(*pos, SEEK_SET); e) { + if (int e = file->seek(*pos, SEEK_SET); e) { errno = e; return -1; } @@ -1063,17 +1061,11 @@ int fsetpos(FILE *f, const fpos_t *pos) { } // ftell() is provided by the POSIX sublibrary -void clearerr(FILE *file_base) { - file_base->__status_bits = 0; -} +void clearerr(FILE *file_base) { file_base->__status_bits = 0; } -int feof(FILE *file_base) { - return file_base->__status_bits & __MLIBC_EOF_BIT; -} +int feof(FILE *file_base) { return file_base->__status_bits & __MLIBC_EOF_BIT; } -int ferror(FILE *file_base) { - return file_base->__status_bits & __MLIBC_ERROR_BIT; -} +int ferror(FILE *file_base) { return file_base->__status_bits & __MLIBC_ERROR_BIT; } void perror(const char *string) { int error = errno; @@ -1085,13 +1077,11 @@ void perror(const char *string) { // POSIX extensions. -ssize_t getline(char **line, size_t *n, FILE *stream) { - return getdelim(line, n, '\n', stream); -} +ssize_t getline(char **line, size_t *n, FILE *stream) { return getdelim(line, n, '\n', stream); } ssize_t getdelim(char **line, size_t *n, int delim, FILE *stream) { // Otherwise, we cannot store the buffer / size. - if(!line || !n) { + if (!line || !n) { errno = EINVAL; return -1; } @@ -1160,7 +1150,7 @@ int vasprintf(char **out, const char *format, __builtin_va_list args) { vs.arg_list = arg_list; va_copy(vs.args, args); ResizePrinter p; -// mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; + // mlibc::infoLogger() << "printf(" << format << ")" << frg::endlog; auto res = frg::printf_format(PrintfAgent{&p, &vs}, format, &vs); if (!res) return -static_cast(res.error()); @@ -1172,9 +1162,7 @@ int vasprintf(char **out, const char *format, __builtin_va_list args) { // Linux unlocked I/O extensions. -void flockfile(FILE *file_base) { - static_cast(file_base)->_lock.lock(); -} +void flockfile(FILE *file_base) { static_cast(file_base)->_lock.lock(); } void funlockfile(FILE *file_base) { static_cast(file_base)->_lock.unlock(); @@ -1185,41 +1173,34 @@ int ftrylockfile(FILE *file_base) { return 0; } -void clearerr_unlocked(FILE *file_base) { - file_base->__status_bits = 0; -} +void clearerr_unlocked(FILE *file_base) { file_base->__status_bits = 0; } -int feof_unlocked(FILE *file_base) { - return file_base->__status_bits & __MLIBC_EOF_BIT; -} +int feof_unlocked(FILE *file_base) { return file_base->__status_bits & __MLIBC_EOF_BIT; } -int ferror_unlocked(FILE *file_base) { - return file_base->__status_bits & __MLIBC_ERROR_BIT; -} +int ferror_unlocked(FILE *file_base) { return file_base->__status_bits & __MLIBC_ERROR_BIT; } int fgetc_unlocked(FILE *stream) { unsigned char d; - if(fread_unlocked(&d, 1, 1, stream) != 1) + if (fread_unlocked(&d, 1, 1, stream) != 1) return EOF; return (int)d; } size_t fread_unlocked(void *buffer, size_t size, size_t count, FILE *file_base) { auto file = static_cast(file_base); - if(!size || !count) + if (!size || !count) return 0; // Distinguish two cases here: If the object size is one, we perform byte-wise reads. // Otherwise, we try to read each object individually. - if(size == 1) { + if (size == 1) { size_t progress = 0; - while(progress < count) { + while (progress < count) { size_t chunk; - if(int e = file->read((char *)buffer + progress, - count - progress, &chunk)) { + if (int e = file->read((char *)buffer + progress, count - progress, &chunk)) { errno = e; return 0; - }else if(!chunk) { + } else if (!chunk) { // TODO: Handle eof. break; } @@ -1228,16 +1209,16 @@ size_t fread_unlocked(void *buffer, size_t size, size_t count, FILE *file_base) } return progress; - }else{ - for(size_t i = 0; i < count; i++) { + } else { + for (size_t i = 0; i < count; i++) { size_t progress = 0; - while(progress < size) { + while (progress < size) { size_t chunk; - if(int e = file->read((char *)buffer + i * size + progress, - size - progress, &chunk)) { + if (int e = + file->read((char *)buffer + i * size + progress, size - progress, &chunk)) { errno = e; return 0; - }else if(!chunk) { + } else if (!chunk) { // TODO: Handle eof. break; } @@ -1245,7 +1226,7 @@ size_t fread_unlocked(void *buffer, size_t size, size_t count, FILE *file_base) progress += chunk; } - if(progress < size) + if (progress < size) return i; } @@ -1255,22 +1236,20 @@ size_t fread_unlocked(void *buffer, size_t size, size_t count, FILE *file_base) size_t fwrite_unlocked(const void *buffer, size_t size, size_t count, FILE *file_base) { auto file = static_cast(file_base); - if(!size || !count) + if (!size || !count) return 0; // Distinguish two cases here: If the object size is one, we perform byte-wise writes. // Otherwise, we try to write each object individually. - if(size == 1) { + if (size == 1) { size_t progress = 0; - while(progress < count) { + while (progress < count) { size_t chunk; - if(file->write((const char *)buffer + progress, - count - progress, &chunk)) { + if (file->write((const char *)buffer + progress, count - progress, &chunk)) { // TODO: Handle I/O errors. - mlibc::infoLogger() << "mlibc: fwrite() I/O errors are not handled" - << frg::endlog; + mlibc::infoLogger() << "mlibc: fwrite() I/O errors are not handled" << frg::endlog; break; - }else if(!chunk) { + } else if (!chunk) { // TODO: Handle eof. break; } @@ -1279,18 +1258,19 @@ size_t fwrite_unlocked(const void *buffer, size_t size, size_t count, FILE *file } return progress; - }else{ - for(size_t i = 0; i < count; i++) { + } else { + for (size_t i = 0; i < count; i++) { size_t progress = 0; - while(progress < size) { + while (progress < size) { size_t chunk; - if(file->write((const char *)buffer + i * size + progress, - size - progress, &chunk)) { + if (file->write( + (const char *)buffer + i * size + progress, size - progress, &chunk + )) { // TODO: Handle I/O errors. - mlibc::infoLogger() << "mlibc: fwrite() I/O errors are not handled" - << frg::endlog; + mlibc::infoLogger() + << "mlibc: fwrite() I/O errors are not handled" << frg::endlog; break; - }else if(!chunk) { + } else if (!chunk) { // TODO: Handle eof. break; } @@ -1298,7 +1278,7 @@ size_t fwrite_unlocked(const void *buffer, size_t size, size_t count, FILE *file progress += chunk; } - if(progress < size) + if (progress < size) return i; } @@ -1308,8 +1288,8 @@ size_t fwrite_unlocked(const void *buffer, size_t size, size_t count, FILE *file char *fgets_unlocked(char *__restrict buffer, int max_size, FILE *__restrict stream) { __ensure(max_size > 0); - for(int i = 0; ; i++) { - if(i == max_size - 1) { + for (int i = 0;; i++) { + if (i == max_size - 1) { buffer[i] = 0; return buffer; } @@ -1317,8 +1297,8 @@ char *fgets_unlocked(char *__restrict buffer, int max_size, FILE *__restrict str auto c = fgetc_unlocked(stream); // If fgetc() fails, there is either an EOF or an I/O error. - if(c == EOF) { - if(i) { + if (c == EOF) { + if (i) { buffer[i] = 0; return buffer; } else { @@ -1329,7 +1309,7 @@ char *fgets_unlocked(char *__restrict buffer, int max_size, FILE *__restrict str buffer[i] = c; } - if(c == '\n') { + if (c == '\n') { buffer[i + 1] = 0; return buffer; } diff --git a/options/ansi/generic/stdlib.cpp b/options/ansi/generic/stdlib.cpp index 724de10b5e..3ea0f60d1e 100644 --- a/options/ansi/generic/stdlib.cpp +++ b/options/ansi/generic/stdlib.cpp @@ -1,26 +1,26 @@ +#include #include +#include +#include +#include #include +#include #include #include -#include -#include -#include #include -#include -#include -#include -#include #include #include +#include +#include #include -#include #include +#include +#include #include #include -#include #if __MLIBC_POSIX_OPTION #include @@ -30,36 +30,28 @@ extern "C" int __cxa_atexit(void (*function)(void *), void *argument, void *dso_ void __mlibc_do_finalize(); namespace { - // According to the first paragraph of [C11 7.22.7], - // mblen(), mbtowc() and wctomb() have an internal state. - // The string functions mbstowcs() and wcstombs() do *not* have this state. - thread_local __mlibc_mbstate mblen_state = __MLIBC_MBSTATE_INITIALIZER; - thread_local __mlibc_mbstate mbtowc_state = __MLIBC_MBSTATE_INITIALIZER; -} - -double atof(const char *string) { - return strtod(string, NULL); -} -int atoi(const char *string) { - return strtol(string, nullptr, 10); -} -long atol(const char *string) { - return strtol(string, nullptr, 10); -} -long long atoll(const char *string) { - return strtoll(string, nullptr, 10); -} +// According to the first paragraph of [C11 7.22.7], +// mblen(), mbtowc() and wctomb() have an internal state. +// The string functions mbstowcs() and wcstombs() do *not* have this state. +thread_local __mlibc_mbstate mblen_state = __MLIBC_MBSTATE_INITIALIZER; +thread_local __mlibc_mbstate mbtowc_state = __MLIBC_MBSTATE_INITIALIZER; +} // namespace + +double atof(const char *string) { return strtod(string, NULL); } +int atoi(const char *string) { return strtol(string, nullptr, 10); } +long atol(const char *string) { return strtol(string, nullptr, 10); } +long long atoll(const char *string) { return strtoll(string, nullptr, 10); } // POSIX extensions but are here for simplicities sake. Forward declaration is here // to avoid exporting sigprocmask when posix is disabled. int sigprocmask(int, const sigset_t *__restrict, sigset_t *__restrict); extern "C" { - __attribute__((__returns_twice__)) int __sigsetjmp(sigjmp_buf buffer, int savesigs) { - buffer[0].__savesigs = savesigs; - if (savesigs) - sigprocmask(0, NULL, &buffer[0].__sigset); - return 0; - } +__attribute__((__returns_twice__)) int __sigsetjmp(sigjmp_buf buffer, int savesigs) { + buffer[0].__savesigs = savesigs; + if (savesigs) + sigprocmask(0, NULL, &buffer[0].__sigset); + return 0; +} } __attribute__((__noreturn__)) void siglongjmp(sigjmp_buf buffer, int value) { @@ -108,13 +100,9 @@ static unsigned temper(unsigned x) { return x; } -int rand_r(unsigned *seed) { - return temper(*seed = *seed * 1103515245 + 12345) / 2; -} +int rand_r(unsigned *seed) { return temper(*seed = *seed * 1103515245 + 12345) / 2; } -void srand(unsigned int s) { - __mlibc_rand_engine.seed(s); -} +void srand(unsigned int s) { __mlibc_rand_engine.seed(s); } void *aligned_alloc(size_t alignment, size_t size) { void *ptr; @@ -135,19 +123,18 @@ void *aligned_alloc(size_t alignment, size_t size) { return nullptr; } return ptr; - } void *calloc(size_t count, size_t size) { // we want to ensure that count*size > SIZE_MAX doesn't happen // to prevent overflowing, we divide both sides of the inequality by size and check with that - if(size && count > (SIZE_MAX / size)) { + if (size && count > (SIZE_MAX / size)) { errno = EINVAL; return NULL; } // TODO: this could be done more efficient if the OS gives us already zero'd pages void *ptr = malloc(count * size); - if(!ptr) + if (!ptr) return nullptr; memset(ptr, 0, count * size); return ptr; @@ -190,7 +177,7 @@ int atexit(void (*func)(void)) { // TODO: the function pointer types are not compatible; // the conversion here is undefined behavior. its fine to do // this on the x86_64 abi though. - __cxa_atexit((void (*) (void *))func, nullptr, nullptr); + __cxa_atexit((void (*)(void *))func, nullptr, nullptr); return 0; } int at_quick_exit(void (*func)(void)) { @@ -204,9 +191,7 @@ void exit(int status) { mlibc::sys_exit(status); } -void _Exit(int status) { - mlibc::sys_exit(status); -} +void _Exit(int status) { mlibc::sys_exit(status); } // getenv() is provided by POSIX void quick_exit(int) { @@ -220,8 +205,11 @@ int system(const char *command) { int status = -1; pid_t child; - MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fork && mlibc::sys_waitpid && - mlibc::sys_execve && mlibc::sys_sigprocmask && mlibc::sys_sigaction, -1); + MLIBC_CHECK_OR_ENOSYS( + mlibc::sys_fork && mlibc::sys_waitpid && mlibc::sys_execve && mlibc::sys_sigprocmask && + mlibc::sys_sigaction, + -1 + ); #if __MLIBC_POSIX_OPTION pthread_testcancel(); @@ -251,9 +239,7 @@ int system(const char *command) { mlibc::sys_sigaction(SIGQUIT, &old_quit, nullptr); mlibc::sys_sigprocmask(SIG_SETMASK, &old_mask, nullptr); - const char *args[] = { - "sh", "-c", command, nullptr - }; + const char *args[] = {"sh", "-c", command, nullptr}; mlibc::sys_execve("/bin/sh", const_cast(args), environ); _Exit(127); @@ -282,21 +268,26 @@ char *mktemp(char *) { __builtin_unreachable(); } -void *bsearch(const void *key, const void *base, size_t count, size_t size, - int (*compare)(const void *, const void *)) { +void *bsearch( + const void *key, + const void *base, + size_t count, + size_t size, + int (*compare)(const void *, const void *) +) { // Invariant: Element is in the interval [i, j). size_t i = 0; size_t j = count; - while(i < j) { + while (i < j) { size_t k = (j - i) / 2; auto element = reinterpret_cast(base) + (i + k) * size; auto res = compare(key, element); - if(res < 0) { + if (res < 0) { j = i + k; - }else if(res > 0) { + } else if (res > 0) { i = i + k + 1; - }else{ + } else { return const_cast(element); } } @@ -311,26 +302,29 @@ static int qsort_callback(const void *a, const void *b, void *arg) { return compare(a, b); } -void qsort(void *base, size_t count, size_t size, - int (*compare)(const void *, const void *)) { - return qsort_r(base, count, size, qsort_callback, (void *) compare); +void qsort(void *base, size_t count, size_t size, int (*compare)(const void *, const void *)) { + return qsort_r(base, count, size, qsort_callback, (void *)compare); } -void qsort_r(void *base, size_t count, size_t size, - int (*compare)(const void *, const void *, void *), - void *arg) { +void qsort_r( + void *base, + size_t count, + size_t size, + int (*compare)(const void *, const void *, void *), + void *arg +) { // TODO: implement a faster sort - for(size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { void *u = (void *)((uintptr_t)base + i * size); - for(size_t j = i + 1; j < count; j++) { + for (size_t j = i + 1; j < count; j++) { void *v = (void *)((uintptr_t)base + j * size); - if(compare(u, v, arg) <= 0) + if (compare(u, v, arg) <= 0) continue; // swap u and v char *u_bytes = (char *)u; char *v_bytes = (char *)v; - for(size_t k = 0; k < size; k++) { + for (size_t k = 0; k < size; k++) { char temp = u_bytes[k]; u_bytes[k] = v_bytes[k]; v_bytes[k] = temp; @@ -339,17 +333,11 @@ void qsort_r(void *base, size_t count, size_t size, } } -int abs(int num) { - return num < 0 ? -num : num; -} +int abs(int num) { return num < 0 ? -num : num; } -long labs(long num) { - return num < 0 ? -num : num; -} +long labs(long num) { return num < 0 ? -num : num; } -long long llabs(long long num) { - return num < 0 ? -num : num; -} +long long llabs(long long num) { return num < 0 ? -num : num; } div_t div(int number, int denom) { div_t r; @@ -378,12 +366,12 @@ int mblen(const char *mbs, size_t mb_limit) { mlibc::code_seq nseq{mbs, mbs + mb_limit}; mlibc::code_seq wseq{&wc, &wc + 1}; - if(!mbs) { + if (!mbs) { mblen_state = __MLIBC_MBSTATE_INITIALIZER; return cc->has_shift_states; } - if(auto e = cc->decode_wtranscode(nseq, wseq, mblen_state); e != mlibc::charcode_error::null) + if (auto e = cc->decode_wtranscode(nseq, wseq, mblen_state); e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return nseq.it - mbs; } @@ -403,24 +391,28 @@ int mbtowc(wchar_t *__restrict wc, const char *__restrict mb, size_t max_size) { mlibc::code_seq wseq{wc, wc + 1}; mlibc::code_seq nseq{mb, mb + frg::min(max_size, MB_CUR_MAX)}; auto e = cc->decode_wtranscode(nseq, wseq, mbtowc_state); - switch(e) { - // We keep the state, so we can simply return here. - case mlibc::charcode_error::input_underflow: - case mlibc::charcode_error::null: { - return nseq.it - mb; - } - case mlibc::charcode_error::illegal_input: { - errno = -EILSEQ; - return -1; - } - case mlibc::charcode_error::dirty: { - mlibc::panicLogger() << "decode_wtranscode() charcode_error::dirty errors are not handled" << frg::endlog; - break; - } - case mlibc::charcode_error::output_overflow: { - mlibc::panicLogger() << "decode_wtranscode() charcode_error::output_overflow errors are not handled" << frg::endlog; - break; - } + switch (e) { + // We keep the state, so we can simply return here. + case mlibc::charcode_error::input_underflow: + case mlibc::charcode_error::null: { + return nseq.it - mb; + } + case mlibc::charcode_error::illegal_input: { + errno = -EILSEQ; + return -1; + } + case mlibc::charcode_error::dirty: { + mlibc::panicLogger() + << "decode_wtranscode() charcode_error::dirty errors are not handled" + << frg::endlog; + break; + } + case mlibc::charcode_error::output_overflow: { + mlibc::panicLogger() + << "decode_wtranscode() charcode_error::output_overflow errors are not handled" + << frg::endlog; + break; + } } __builtin_unreachable(); } else { @@ -444,19 +436,20 @@ size_t mbstowcs(wchar_t *__restrict wcs, const char *__restrict mbs, size_t wc_l mlibc::code_seq nseq{mbs, nullptr}; mlibc::code_seq wseq{wcs, wcs + wc_limit}; - if(!wcs) { + if (!wcs) { size_t size; - if(auto e = cc->decode_wtranscode_length(nseq, &size, st); e != mlibc::charcode_error::null) + if (auto e = cc->decode_wtranscode_length(nseq, &size, st); + e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return size; } - if(auto e = cc->decode_wtranscode(nseq, wseq, st); e != mlibc::charcode_error::null) { + if (auto e = cc->decode_wtranscode(nseq, wseq, st); e != mlibc::charcode_error::null) { __ensure(!"decode_wtranscode() errors are not handled"); __builtin_unreachable(); - }else{ + } else { size_t n = wseq.it - wcs; - if(n < wc_limit) // Null-terminate resulting wide string. + if (n < wc_limit) // Null-terminate resulting wide string. wcs[n] = 0; return n; } @@ -470,9 +463,8 @@ size_t wcstombs(char *__restrict mb_string, const wchar_t *__restrict wc_string, void free(void *ptr) { // TODO: Print PID only if POSIX option is enabled. if (mlibc::globalConfig().debugMalloc) { - mlibc::infoLogger() << "mlibc (PID ?): free() on " - << ptr << frg::endlog; - if((uintptr_t)ptr & 1) + mlibc::infoLogger() << "mlibc (PID ?): free() on " << ptr << frg::endlog; + if ((uintptr_t)ptr & 1) mlibc::infoLogger() << __builtin_return_address(0) << frg::endlog; } getAllocator().free(ptr); @@ -482,8 +474,7 @@ void *malloc(size_t size) { auto nptr = getAllocator().allocate(size); // TODO: Print PID only if POSIX option is enabled. if (mlibc::globalConfig().debugMalloc) - mlibc::infoLogger() << "mlibc (PID ?): malloc() returns " - << nptr << frg::endlog; + mlibc::infoLogger() << "mlibc (PID ?): malloc() returns " << nptr << frg::endlog; return nptr; } @@ -491,18 +482,18 @@ void *realloc(void *ptr, size_t size) { auto nptr = getAllocator().reallocate(ptr, size); // TODO: Print PID only if POSIX option is enabled. if (mlibc::globalConfig().debugMalloc) - mlibc::infoLogger() << "mlibc (PID ?): realloc() on " - << ptr << " returns " << nptr << frg::endlog; + mlibc::infoLogger() << "mlibc (PID ?): realloc() on " << ptr << " returns " << nptr + << frg::endlog; return nptr; } int posix_memalign(void **out, size_t align, size_t size) { - if(align < sizeof(void *)) + if (align < sizeof(void *)) return EINVAL; - if(align & (align - 1)) // Make sure that align is a power of two. + if (align & (align - 1)) // Make sure that align is a power of two. return EINVAL; auto p = getAllocator().allocate(frg::max(align, size)); - if(!p) + if (!p) return ENOMEM; // Hope that the alignment was respected. This works on the current allocator. // TODO: Make the allocator alignment-aware. diff --git a/options/ansi/generic/string.cpp b/options/ansi/generic/string.cpp index 8defd0e5ad..da2fdeefab 100644 --- a/options/ansi/generic/string.cpp +++ b/options/ansi/generic/string.cpp @@ -1,7 +1,7 @@ -#include +#include #include +#include #include -#include #include #include @@ -14,7 +14,7 @@ char *strcpy(char *__restrict dest, const char *src) { char *dest_bytes = (char *)dest; char *src_bytes = (char *)src; - while(*src_bytes) + while (*src_bytes) *(dest_bytes++) = *(src_bytes++); *dest_bytes = 0; return dest; @@ -23,11 +23,11 @@ char *strncpy(char *__restrict dest, const char *src, size_t max_size) { auto dest_bytes = static_cast(dest); auto src_bytes = static_cast(src); size_t i = 0; - while(*src_bytes && i < max_size) { + while (*src_bytes && i < max_size) { *(dest_bytes++) = *(src_bytes++); i++; } - while(i < max_size) { + while (i < max_size) { *(dest_bytes++) = 0; i++; } @@ -43,7 +43,7 @@ char *strncat(char *__restrict dest, const char *__restrict src, size_t max_size auto src_bytes = static_cast(src); dest_bytes += strlen(dest); size_t i = 0; - while(*src_bytes && i < max_size) { + while (*src_bytes && i < max_size) { *(dest_bytes++) = *(src_bytes++); i++; } @@ -52,27 +52,27 @@ char *strncat(char *__restrict dest, const char *__restrict src, size_t max_size } int memcmp(const void *a, const void *b, size_t size) { - for(size_t i = 0; i < size; i++) { + for (size_t i = 0; i < size; i++) { auto a_byte = static_cast(a)[i]; auto b_byte = static_cast(b)[i]; - if(a_byte < b_byte) + if (a_byte < b_byte) return -1; - if(a_byte > b_byte) + if (a_byte > b_byte) return 1; } return 0; } int strcmp(const char *a, const char *b) { size_t i = 0; - while(true) { + while (true) { unsigned char a_byte = a[i]; unsigned char b_byte = b[i]; - if(!a_byte && !b_byte) + if (!a_byte && !b_byte) return 0; // If only one char is null, one of the following cases applies. - if(a_byte < b_byte) + if (a_byte < b_byte) return -1; - if(a_byte > b_byte) + if (a_byte > b_byte) return 1; i++; } @@ -85,17 +85,17 @@ int strcoll(const char *a, const char *b) { int strncmp(const char *a, const char *b, size_t max_size) { size_t i = 0; - while(true) { - if(!(i < max_size)) + while (true) { + if (!(i < max_size)) return 0; unsigned char a_byte = a[i]; unsigned char b_byte = b[i]; - if(!a_byte && !b_byte) + if (!a_byte && !b_byte) return 0; // If only one char is null, one of the following cases applies. - if(a_byte < b_byte) + if (a_byte < b_byte) return -1; - if(a_byte > b_byte) + if (a_byte > b_byte) return 1; i++; } @@ -106,7 +106,7 @@ size_t strxfrm(char *__restrict dest, const char *__restrict src, size_t n) { size_t l = strlen(src); // man page: If the value returned is n or more, the contents of dest are indeterminate. - if(n > l) + if (n > l) strncpy(dest, src, n); return l; @@ -114,34 +114,34 @@ size_t strxfrm(char *__restrict dest, const char *__restrict src, size_t n) { void *memchr(const void *s, int c, size_t size) { auto s_bytes = static_cast(s); - for(size_t i = 0; i < size; i++) - if(s_bytes[i] == static_cast(c)) + for (size_t i = 0; i < size; i++) + if (s_bytes[i] == static_cast(c)) return const_cast(s_bytes + i); return nullptr; } char *strchr(const char *s, int c) { size_t i = 0; - while(s[i]) { - if(s[i] == c) + while (s[i]) { + if (s[i] == c) return const_cast(&s[i]); i++; } - if(c == 0) + if (c == 0) return const_cast(&s[i]); return nullptr; } size_t strcspn(const char *s, const char *chrs) { size_t n = 0; - while(true) { - if(!s[n] || strchr(chrs, s[n])) + while (true) { + if (!s[n] || strchr(chrs, s[n])) return n; n++; } } char *strpbrk(const char *s, const char *chrs) { size_t n = 0; - while(s[n]) { - if(strchr(chrs, s[n])) + while (s[n]) { + if (strchr(chrs, s[n])) return const_cast(s + n); n++; } @@ -150,32 +150,32 @@ char *strpbrk(const char *s, const char *chrs) { char *strrchr(const char *s, int c) { // The null-terminator is considered to be part of the string. size_t length = strlen(s); - for(size_t i = 0; i <= length; i++) { - if(s[length - i] == c) + for (size_t i = 0; i <= length; i++) { + if (s[length - i] == c) return const_cast(s + (length - i)); } return nullptr; } size_t strspn(const char *s, const char *chrs) { size_t n = 0; - while(true) { - if(!s[n] || !strchr(chrs, s[n])) + while (true) { + if (!s[n] || !strchr(chrs, s[n])) return n; n++; } } char *strstr(const char *s, const char *pattern) { - for(size_t i = 0; s[i]; i++) { + for (size_t i = 0; s[i]; i++) { bool found = true; - for(size_t j = 0; pattern[j]; j++) { - if(!pattern[j] || s[i + j] == pattern[j]) + for (size_t j = 0; pattern[j]; j++) { + if (!pattern[j] || s[i + j] == pattern[j]) continue; found = false; break; } - if(found) + if (found) return const_cast(&s[i]); } @@ -186,45 +186,45 @@ char *strtok_r(char *__restrict s, const char *__restrict del, char **__restrict // We use *m = null to memorize that the entire string was consumed. char *tok; - if(s) { + if (s) { tok = s; - }else if(*m) { + } else if (*m) { tok = *m; - }else { + } else { return nullptr; } // Skip initial delimiters. // After this loop: *tok is non-null iff we return a token. - while(*tok && strchr(del, *tok)) + while (*tok && strchr(del, *tok)) tok++; // Replace the following delimiter by a null-terminator. // After this loop: *p is null iff we reached the end of the string. auto p = tok; - while(*p && !strchr(del, *p)) + while (*p && !strchr(del, *p)) p++; - if(*p) { + if (*p) { *p = 0; *m = p + 1; - }else{ + } else { *m = nullptr; } - if(p == tok) + if (p == tok) return nullptr; return tok; } char *strtok(char *__restrict s, const char *__restrict delimiter) { - static char *saved; - return strtok_r(s, delimiter, &saved); + static char *saved; + return strtok_r(s, delimiter, &saved); } // This is a GNU extension. char *strchrnul(const char *s, int c) { size_t i = 0; - while(s[i]) { - if(s[i] == c) + while (s[i]) { + if (s[i] == c) return const_cast(s + i); i++; } @@ -232,31 +232,32 @@ char *strchrnul(const char *s, int c) { } double wcstod(const wchar_t *__restrict, wchar_t **__restrict) MLIBC_STUB_BODY -float wcstof(const wchar_t *__restrict, wchar_t **__restrict) MLIBC_STUB_BODY -long double wcstold(const wchar_t *__restrict, wchar_t **__restrict) MLIBC_STUB_BODY + float wcstof(const wchar_t *__restrict, wchar_t **__restrict) MLIBC_STUB_BODY + long double wcstold(const wchar_t *__restrict, wchar_t **__restrict) MLIBC_STUB_BODY -long wcstol(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { + long wcstol(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { return mlibc::stringToInteger(nptr, endptr, base); } -unsigned long wcstoul(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { +unsigned long wcstoul(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { return mlibc::stringToInteger(nptr, endptr, base); } -long long wcstoll(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { +long long wcstoll(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { return mlibc::stringToInteger(nptr, endptr, base); } -unsigned long long wcstoull(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { +unsigned long long wcstoull(const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { return mlibc::stringToInteger(nptr, endptr, base); } wchar_t *wcscpy(wchar_t *__restrict dest, const wchar_t *__restrict src) { wchar_t *a = dest; - while((*dest++ = *src++)); + while ((*dest++ = *src++)) + ; return a; } wchar_t *wcsncpy(wchar_t *__restrict dest, const wchar_t *__restrict src, size_t n) { wchar_t *a = dest; - while(n && *src) + while (n && *src) n--, *dest++ = *src++; wmemset(dest, 0, n); return a; @@ -277,187 +278,413 @@ wchar_t *wcscat(wchar_t *__restrict dest, const wchar_t *__restrict src) { return dest; } -wchar_t *wcsncat(wchar_t *__restrict, const wchar_t *__restrict, size_t) MLIBC_STUB_BODY +wchar_t *wcsncat(wchar_t *__restrict, const wchar_t *__restrict, size_t) +MLIBC_STUB_BODY int wcscmp(const wchar_t *l, const wchar_t *r) { - for(; *l == *r && *l && *r; l++, r++); + for (; *l == *r && *l && *r; l++, r++) + ; return *l - *r; } int wcscoll(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY -int wcsncmp(const wchar_t *, const wchar_t *, size_t) MLIBC_STUB_BODY -int wcsxfrm(wchar_t *__restrict, const wchar_t *__restrict, size_t) MLIBC_STUB_BODY + int wcsncmp(const wchar_t *, const wchar_t *, size_t) +MLIBC_STUB_BODY +int wcsxfrm(wchar_t *__restrict, const wchar_t *__restrict, size_t) +MLIBC_STUB_BODY int wmemcmp(const wchar_t *a, const wchar_t *b, size_t size) { - for(size_t i = 0; i < size; i++) { + for (size_t i = 0; i < size; i++) { auto a_byte = a[i]; auto b_byte = b[i]; - if(a_byte < b_byte) + if (a_byte < b_byte) return -1; - if(a_byte > b_byte) + if (a_byte > b_byte) return 1; } return 0; } wchar_t *wcschr(const wchar_t *s, wchar_t c) { - if(!c) + if (!c) return (wchar_t *)s + wcslen(s); - for(; *s && *s != c; s++); + for (; *s && *s != c; s++) + ; return *s ? (wchar_t *)s : 0; } -size_t wcscspn(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY -wchar_t *wcspbrk(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY +size_t wcscspn(const wchar_t *, const wchar_t *) + MLIBC_STUB_BODY wchar_t *wcspbrk(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY -wchar_t *wcsrchr(const wchar_t *s, wchar_t c) { + wchar_t *wcsrchr(const wchar_t *s, wchar_t c) { const wchar_t *p; - for(p = s + wcslen(s); p >= s && *p != c; p--); + for (p = s + wcslen(s); p >= s && *p != c; p--) + ; return p >= s ? (wchar_t *)p : 0; } size_t wcsspn(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY -wchar_t *wcsstr(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY -wchar_t *wcstok(wchar_t *__restrict, const wchar_t *__restrict, wchar_t **__restrict) MLIBC_STUB_BODY + wchar_t *wcsstr(const wchar_t *, const wchar_t *) MLIBC_STUB_BODY wchar_t *wcstok( + wchar_t *__restrict, const wchar_t *__restrict, wchar_t **__restrict + ) MLIBC_STUB_BODY -wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t size) { + wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t size) { auto s_bytes = s; - for(size_t i = 0; i < size; i++) - if(s_bytes[i] == c) + for (size_t i = 0; i < size; i++) + if (s_bytes[i] == c) return const_cast(s_bytes + i); return nullptr; } size_t wcslen(const wchar_t *s) { const wchar_t *a; - for(a = s; *s; s++); - return s-a; + for (a = s; *s; s++) + ; + return s - a; } wchar_t *wmemset(wchar_t *d, wchar_t c, size_t n) { wchar_t *ret = d; - while(n--) + while (n--) *d++ = c; return ret; } char *strerror(int e) { const char *s; - switch(e) { - case EAGAIN: s = "Operation would block (EAGAIN)"; break; - case EACCES: s = "Access denied (EACCESS)"; break; - case EBADF: s = "Bad file descriptor (EBADF)"; break; - case EEXIST: s = "File exists already (EEXIST)"; break; - case EFAULT: s = "Access violation (EFAULT)"; break; - case EINTR: s = "Operation interrupted (EINTR)"; break; - case EINVAL: s = "Invalid argument (EINVAL)"; break; - case EIO: s = "I/O error (EIO)"; break; - case EISDIR: s = "Resource is directory (EISDIR)"; break; - case ENOENT: s = "No such file or directory (ENOENT)"; break; - case ENOMEM: s = "Out of memory (ENOMEM)"; break; - case ENOTDIR: s = "Expected directory instead of file (ENOTDIR)"; break; - case ENOSYS: s = "Operation not implemented (ENOSYS)"; break; - case EPERM: s = "Operation not permitted (EPERM)"; break; - case EPIPE: s = "Broken pipe (EPIPE)"; break; - case ESPIPE: s = "Seek not possible (ESPIPE)"; break; - case ENXIO: s = "No such device or address (ENXIO)"; break; - case ENOEXEC: s = "Exec format error (ENOEXEC)"; break; - case ENOSPC: s = "No space left on device (ENOSPC)"; break; - case ENOTSOCK: s = "Socket operation on non-socket (ENOTSOCK)"; break; - case ENOTCONN: s = "Transport endpoint is not connected (ENOTCONN)"; break; - case EDOM: s = "Numerical argument out of domain (EDOM)"; break; - case EILSEQ: s = "Invalid or incomplete multibyte or wide character (EILSEQ)"; break; - case ERANGE: s = "Numerical result out of range (ERANGE)"; break; - case E2BIG: s = "Argument list too long (E2BIG)"; break; - case EADDRINUSE: s = "Address already in use (EADDRINUSE)"; break; - case EADDRNOTAVAIL: s = "Cannot assign requested address (EADDRNOTAVAIL)"; break; - case EAFNOSUPPORT: s = "Address family not supported by protocol (EAFNOSUPPORT)"; break; - case EALREADY: s = "Operation already in progress (EALREADY)"; break; - case EBADMSG: s = "Bad message (EBADMSG)"; break; - case EBUSY: s = "Device or resource busy (EBUSY)"; break; - case ECANCELED: s = "Operation canceled (ECANCELED)"; break; - case ECHILD: s = "No child processes (ECHILD)"; break; - case ECONNABORTED: s = "Software caused connection abort (ECONNABORTED)"; break; - case ECONNREFUSED: s = "Connection refused (ECONNREFUSED)"; break; - case ECONNRESET: s = "Connection reset by peer (ECONNRESET)"; break; - case EDEADLK: s = "Resource deadlock avoided (EDEADLK)"; break; - case EDESTADDRREQ: s = "Destination address required (EDESTADDRREQ)"; break; - case EDQUOT: s = "Disk quota exceeded (EDQUOT)"; break; - case EFBIG: s = "File too large (EFBIG)"; break; - case EHOSTUNREACH: s = "No route to host (EHOSTUNREACH)"; break; - case EIDRM: s = "Identifier removed (EIDRM)"; break; - case EINPROGRESS: s = "Operation now in progress (EINPROGRESS)"; break; - case EISCONN: s = "Transport endpoint is already connected (EISCONN)"; break; - case ELOOP: s = "Too many levels of symbolic links (ELOOP)"; break; - case EMFILE: s = "Too many open files (EMFILE)"; break; - case EMLINK: s = "Too many links (EMLINK)"; break; - case EMSGSIZE: s = "Message too long (EMSGSIZE)"; break; - case EMULTIHOP: s = "Multihop attempted (EMULTIHOP)"; break; - case ENAMETOOLONG: s = "File name too long (ENAMETOOLONG)"; break; - case ENETDOWN: s = "Network is down (ENETDOWN)"; break; - case ENETRESET: s = "Network dropped connection on reset (ENETRESET)"; break; - case ENETUNREACH: s = "Network is unreachable (ENETUNREACH)"; break; - case ENFILE: s = "Too many open files in system (ENFILE)"; break; - case ENOBUFS: s = "No buffer space available (ENOBUFS)"; break; - case ENODEV: s = "No such device (ENODEV)"; break; - case ENOLCK: s = "No locks available (ENOLCK)"; break; - case ENOLINK: s = "Link has been severed (ENOLINK)"; break; - case ENOMSG: s = "No message of desired type (ENOMSG)"; break; - case ENOPROTOOPT: s = "Protocol not available (ENOPROTOOPT)"; break; - case ENOTEMPTY: s = "Directory not empty (ENOTEMPTY)"; break; - case ENOTRECOVERABLE: s = "Sate not recoverable (ENOTRECOVERABLE)"; break; - case ENOTSUP: s = "Operation not supported (ENOTSUP)"; break; - case ENOTTY: s = "Inappropriate ioctl for device (ENOTTY)"; break; - case EOVERFLOW: s = "Value too large for defined datatype (EOVERFLOW)"; break; + switch (e) { + case EAGAIN: + s = "Operation would block (EAGAIN)"; + break; + case EACCES: + s = "Access denied (EACCESS)"; + break; + case EBADF: + s = "Bad file descriptor (EBADF)"; + break; + case EEXIST: + s = "File exists already (EEXIST)"; + break; + case EFAULT: + s = "Access violation (EFAULT)"; + break; + case EINTR: + s = "Operation interrupted (EINTR)"; + break; + case EINVAL: + s = "Invalid argument (EINVAL)"; + break; + case EIO: + s = "I/O error (EIO)"; + break; + case EISDIR: + s = "Resource is directory (EISDIR)"; + break; + case ENOENT: + s = "No such file or directory (ENOENT)"; + break; + case ENOMEM: + s = "Out of memory (ENOMEM)"; + break; + case ENOTDIR: + s = "Expected directory instead of file (ENOTDIR)"; + break; + case ENOSYS: + s = "Operation not implemented (ENOSYS)"; + break; + case EPERM: + s = "Operation not permitted (EPERM)"; + break; + case EPIPE: + s = "Broken pipe (EPIPE)"; + break; + case ESPIPE: + s = "Seek not possible (ESPIPE)"; + break; + case ENXIO: + s = "No such device or address (ENXIO)"; + break; + case ENOEXEC: + s = "Exec format error (ENOEXEC)"; + break; + case ENOSPC: + s = "No space left on device (ENOSPC)"; + break; + case ENOTSOCK: + s = "Socket operation on non-socket (ENOTSOCK)"; + break; + case ENOTCONN: + s = "Transport endpoint is not connected (ENOTCONN)"; + break; + case EDOM: + s = "Numerical argument out of domain (EDOM)"; + break; + case EILSEQ: + s = "Invalid or incomplete multibyte or wide character (EILSEQ)"; + break; + case ERANGE: + s = "Numerical result out of range (ERANGE)"; + break; + case E2BIG: + s = "Argument list too long (E2BIG)"; + break; + case EADDRINUSE: + s = "Address already in use (EADDRINUSE)"; + break; + case EADDRNOTAVAIL: + s = "Cannot assign requested address (EADDRNOTAVAIL)"; + break; + case EAFNOSUPPORT: + s = "Address family not supported by protocol (EAFNOSUPPORT)"; + break; + case EALREADY: + s = "Operation already in progress (EALREADY)"; + break; + case EBADMSG: + s = "Bad message (EBADMSG)"; + break; + case EBUSY: + s = "Device or resource busy (EBUSY)"; + break; + case ECANCELED: + s = "Operation canceled (ECANCELED)"; + break; + case ECHILD: + s = "No child processes (ECHILD)"; + break; + case ECONNABORTED: + s = "Software caused connection abort (ECONNABORTED)"; + break; + case ECONNREFUSED: + s = "Connection refused (ECONNREFUSED)"; + break; + case ECONNRESET: + s = "Connection reset by peer (ECONNRESET)"; + break; + case EDEADLK: + s = "Resource deadlock avoided (EDEADLK)"; + break; + case EDESTADDRREQ: + s = "Destination address required (EDESTADDRREQ)"; + break; + case EDQUOT: + s = "Disk quota exceeded (EDQUOT)"; + break; + case EFBIG: + s = "File too large (EFBIG)"; + break; + case EHOSTUNREACH: + s = "No route to host (EHOSTUNREACH)"; + break; + case EIDRM: + s = "Identifier removed (EIDRM)"; + break; + case EINPROGRESS: + s = "Operation now in progress (EINPROGRESS)"; + break; + case EISCONN: + s = "Transport endpoint is already connected (EISCONN)"; + break; + case ELOOP: + s = "Too many levels of symbolic links (ELOOP)"; + break; + case EMFILE: + s = "Too many open files (EMFILE)"; + break; + case EMLINK: + s = "Too many links (EMLINK)"; + break; + case EMSGSIZE: + s = "Message too long (EMSGSIZE)"; + break; + case EMULTIHOP: + s = "Multihop attempted (EMULTIHOP)"; + break; + case ENAMETOOLONG: + s = "File name too long (ENAMETOOLONG)"; + break; + case ENETDOWN: + s = "Network is down (ENETDOWN)"; + break; + case ENETRESET: + s = "Network dropped connection on reset (ENETRESET)"; + break; + case ENETUNREACH: + s = "Network is unreachable (ENETUNREACH)"; + break; + case ENFILE: + s = "Too many open files in system (ENFILE)"; + break; + case ENOBUFS: + s = "No buffer space available (ENOBUFS)"; + break; + case ENODEV: + s = "No such device (ENODEV)"; + break; + case ENOLCK: + s = "No locks available (ENOLCK)"; + break; + case ENOLINK: + s = "Link has been severed (ENOLINK)"; + break; + case ENOMSG: + s = "No message of desired type (ENOMSG)"; + break; + case ENOPROTOOPT: + s = "Protocol not available (ENOPROTOOPT)"; + break; + case ENOTEMPTY: + s = "Directory not empty (ENOTEMPTY)"; + break; + case ENOTRECOVERABLE: + s = "Sate not recoverable (ENOTRECOVERABLE)"; + break; + case ENOTSUP: + s = "Operation not supported (ENOTSUP)"; + break; + case ENOTTY: + s = "Inappropriate ioctl for device (ENOTTY)"; + break; + case EOVERFLOW: + s = "Value too large for defined datatype (EOVERFLOW)"; + break; #if EOPNOTSUPP != ENOTSUP /* these are aliases on the mlibc abi */ - case EOPNOTSUPP: s = "Operation not supported (EOPNOTSUP)"; break; + case EOPNOTSUPP: + s = "Operation not supported (EOPNOTSUP)"; + break; #endif - case EOWNERDEAD: s = "Owner died (EOWNERDEAD)"; break; - case EPROTO: s = "Protocol error (EPROTO)"; break; - case EPROTONOSUPPORT: s = "Protocol not supported (EPROTONOSUPPORT)"; break; - case EPROTOTYPE: s = "Protocol wrong type for socket (EPROTOTYPE)"; break; - case EROFS: s = "Read-only file system (EROFS)"; break; - case ESRCH: s = "No such process (ESRCH)"; break; - case ESTALE: s = "Stale file handle (ESTALE)"; break; - case ETIMEDOUT: s = "Connection timed out (ETIMEDOUT)"; break; - case ETXTBSY: s = "Text file busy (ETXTBSY)"; break; - case EXDEV: s = "Invalid cross-device link (EXDEV)"; break; - case ENODATA: s = "No data available (ENODATA)"; break; - case ETIME: s = "Timer expired (ETIME)"; break; - case ENOKEY: s = "Required key not available (ENOKEY)"; break; - case ESHUTDOWN: s = "Cannot send after transport endpoint shutdown (ESHUTDOWN)"; break; - case EHOSTDOWN: s = "Host is down (EHOSTDOWN)"; break; - case EBADFD: s = "File descriptor in bad state (EBADFD)"; break; - case ENOMEDIUM: s = "No medium found (ENOMEDIUM)"; break; - case ENOTBLK: s = "Block device required (ENOTBLK)"; break; - case ENONET: s = "Machine is not on the network (ENONET)"; break; - case EPFNOSUPPORT: s = "Protocol family not supported (EPFNOSUPPORT)"; break; - case ESOCKTNOSUPPORT: s = "Socket type not supported (ESOCKTNOSUPPORT)"; break; - case ESTRPIPE: s = "Streams pipe error (ESTRPIPE)"; break; - case EREMOTEIO: s = "Remote I/O error (EREMOTEIO)"; break; - case ERFKILL: s = "Operation not possible due to RF-kill (ERFKILL)"; break; - case EBADR: s = "Invalid request descriptor (EBADR)"; break; - case EUNATCH: s = "Protocol driver not attached (EUNATCH)"; break; - case EMEDIUMTYPE: s = "Wrong medium type (EMEDIUMTYPE)"; break; - case EREMOTE: s = "Object is remote (EREMOTE)"; break; - case EKEYREJECTED: s = "Key was rejected by service (EKEYREJECTED)"; break; - case EUCLEAN: s = "Structure needs cleaning (EUCLEAN)"; break; - case EBADSLT: s = "Invalid slot (EBADSLT)"; break; - case ENOANO: s = "No anode (ENOANO)"; break; - case ENOCSI: s = "No CSI structure available (ENOCSI)"; break; - case ENOSTR: s = "Device not a stream (ENOSTR)"; break; - case ETOOMANYREFS: s = "Too many references: cannot splice (ETOOMANYREFS)"; break; - case ENOPKG: s = "Package not installed (ENOPKG)"; break; - case EKEYREVOKED: s = "Key has been revoked (EKEYREVOKED)"; break; - case EXFULL: s = "Exchange full (EXFULL)"; break; - case ELNRNG: s = "Link number out of range (ELNRNG)"; break; - case ENOTUNIQ: s = "Name not unique on network (ENOTUNIQ)"; break; - case ERESTART: s = "Interrupted system call should be restarted (ERESTART)"; break; - case EUSERS: s = "Too many users (EUSERS)"; break; + case EOWNERDEAD: + s = "Owner died (EOWNERDEAD)"; + break; + case EPROTO: + s = "Protocol error (EPROTO)"; + break; + case EPROTONOSUPPORT: + s = "Protocol not supported (EPROTONOSUPPORT)"; + break; + case EPROTOTYPE: + s = "Protocol wrong type for socket (EPROTOTYPE)"; + break; + case EROFS: + s = "Read-only file system (EROFS)"; + break; + case ESRCH: + s = "No such process (ESRCH)"; + break; + case ESTALE: + s = "Stale file handle (ESTALE)"; + break; + case ETIMEDOUT: + s = "Connection timed out (ETIMEDOUT)"; + break; + case ETXTBSY: + s = "Text file busy (ETXTBSY)"; + break; + case EXDEV: + s = "Invalid cross-device link (EXDEV)"; + break; + case ENODATA: + s = "No data available (ENODATA)"; + break; + case ETIME: + s = "Timer expired (ETIME)"; + break; + case ENOKEY: + s = "Required key not available (ENOKEY)"; + break; + case ESHUTDOWN: + s = "Cannot send after transport endpoint shutdown (ESHUTDOWN)"; + break; + case EHOSTDOWN: + s = "Host is down (EHOSTDOWN)"; + break; + case EBADFD: + s = "File descriptor in bad state (EBADFD)"; + break; + case ENOMEDIUM: + s = "No medium found (ENOMEDIUM)"; + break; + case ENOTBLK: + s = "Block device required (ENOTBLK)"; + break; + case ENONET: + s = "Machine is not on the network (ENONET)"; + break; + case EPFNOSUPPORT: + s = "Protocol family not supported (EPFNOSUPPORT)"; + break; + case ESOCKTNOSUPPORT: + s = "Socket type not supported (ESOCKTNOSUPPORT)"; + break; + case ESTRPIPE: + s = "Streams pipe error (ESTRPIPE)"; + break; + case EREMOTEIO: + s = "Remote I/O error (EREMOTEIO)"; + break; + case ERFKILL: + s = "Operation not possible due to RF-kill (ERFKILL)"; + break; + case EBADR: + s = "Invalid request descriptor (EBADR)"; + break; + case EUNATCH: + s = "Protocol driver not attached (EUNATCH)"; + break; + case EMEDIUMTYPE: + s = "Wrong medium type (EMEDIUMTYPE)"; + break; + case EREMOTE: + s = "Object is remote (EREMOTE)"; + break; + case EKEYREJECTED: + s = "Key was rejected by service (EKEYREJECTED)"; + break; + case EUCLEAN: + s = "Structure needs cleaning (EUCLEAN)"; + break; + case EBADSLT: + s = "Invalid slot (EBADSLT)"; + break; + case ENOANO: + s = "No anode (ENOANO)"; + break; + case ENOCSI: + s = "No CSI structure available (ENOCSI)"; + break; + case ENOSTR: + s = "Device not a stream (ENOSTR)"; + break; + case ETOOMANYREFS: + s = "Too many references: cannot splice (ETOOMANYREFS)"; + break; + case ENOPKG: + s = "Package not installed (ENOPKG)"; + break; + case EKEYREVOKED: + s = "Key has been revoked (EKEYREVOKED)"; + break; + case EXFULL: + s = "Exchange full (EXFULL)"; + break; + case ELNRNG: + s = "Link number out of range (ELNRNG)"; + break; + case ENOTUNIQ: + s = "Name not unique on network (ENOTUNIQ)"; + break; + case ERESTART: + s = "Interrupted system call should be restarted (ERESTART)"; + break; + case EUSERS: + s = "Too many users (EUSERS)"; + break; #ifdef EIEIO - case EIEIO: s = "Computer bought the farm; OS internal error (EIEIO)"; break; + case EIEIO: + s = "Computer bought the farm; OS internal error (EIEIO)"; + break; #endif default: @@ -473,7 +700,7 @@ int strerror_r(int e, char *buffer, size_t bufsz) { auto s = strerror(e); strncpy(buffer, s, bufsz); // Note that strerror_r does not set errno on error! - if(strlen(s) >= bufsz) + if (strlen(s) >= bufsz) return ERANGE; return 0; } @@ -492,26 +719,26 @@ int strverscmp(const char *l0, const char *r0) { /* Find maximal matching prefix and track its maximal digit * suffix and whether those digits are all zeros. */ - for(dp = i = 0; l[i] == r[i]; i++) { + for (dp = i = 0; l[i] == r[i]; i++) { int c = l[i]; - if(!c) + if (!c) return 0; - if(!isdigit(c)) + if (!isdigit(c)) dp = i + 1, z = 1; - else if(c != '0') + else if (c != '0') z = 0; } - if(l[dp] != '0' && r[dp] != '0') { + if (l[dp] != '0' && r[dp] != '0') { /* If we're not looking at a digit sequence that began * with a zero, longest digit string is greater. */ - for(j = i; isdigit(l[j]); j++) { - if(!isdigit(r[j])) + for (j = i; isdigit(l[j]); j++) { + if (!isdigit(r[j])) return 1; } - if(isdigit(r[j])) + if (isdigit(r[j])) return -1; - } else if(z && dp < i && (isdigit(l[i]) || isdigit(r[i]))) { + } else if (z && dp < i && (isdigit(l[i]) || isdigit(r[i]))) { /* Otherwise, if common prefix of digit sequence is * all zeros, digits order less than non-digits. */ return (unsigned char)(l[i] - '0') - (unsigned char)(r[i] - '0'); @@ -534,7 +761,7 @@ void *memmem(const void *hs, size_t haystackLen, const void *nd, size_t needleLe } } - if(found) + if (found) return const_cast(&haystack[i]); } diff --git a/options/ansi/generic/threads.cpp b/options/ansi/generic/threads.cpp index 70fa055fd2..979c818b00 100644 --- a/options/ansi/generic/threads.cpp +++ b/options/ansi/generic/threads.cpp @@ -8,7 +8,7 @@ int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) { int res = mlibc::thread_create(thr, 0, reinterpret_cast(func), arg, true); - if(!res) { + if (!res) { return thrd_success; } @@ -16,15 +16,13 @@ int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) { } int thrd_equal(thrd_t t1, thrd_t t2) { - if(t1 == t2) { + if (t1 == t2) { return 1; } return 0; } -thrd_t thrd_current(void) { - return reinterpret_cast(mlibc::get_current_tcb()); -} +thrd_t thrd_current(void) { return reinterpret_cast(mlibc::get_current_tcb()); } int thrd_sleep(const struct timespec *, struct timespec *) { __ensure(!"Not implemented"); @@ -42,7 +40,7 @@ int thrd_detach(thrd_t) { } int thrd_join(thrd_t thr, int *res) { - if(mlibc::thread_join(thr, res) != 0) { + if (mlibc::thread_join(thr, res) != 0) { return thrd_error; } @@ -58,7 +56,7 @@ int mtx_init(mtx_t *mtx, int type) { struct __mlibc_mutexattr attr; mlibc::thread_mutexattr_init(&attr); - if(type & mtx_recursive) { + if (type & mtx_recursive) { mlibc::thread_mutexattr_settype(&attr, __MLIBC_THREAD_MUTEX_RECURSIVE); } @@ -68,13 +66,9 @@ int mtx_init(mtx_t *mtx, int type) { return res; } -void mtx_destroy(mtx_t *mtx) { - mlibc::thread_mutex_destroy(mtx); -} +void mtx_destroy(mtx_t *mtx) { mlibc::thread_mutex_destroy(mtx); } -int mtx_lock(mtx_t *mtx) { - return mlibc::thread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; -} +int mtx_lock(mtx_t *mtx) { return mlibc::thread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; } int mtx_unlock(mtx_t *mtx) { return mlibc::thread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error; @@ -84,9 +78,7 @@ int cnd_init(cnd_t *cond) { return mlibc::thread_cond_init(cond, 0) == 0 ? thrd_success : thrd_error; } -void cnd_destroy(cnd_t *cond) { - mlibc::thread_cond_destroy(cond); -} +void cnd_destroy(cnd_t *cond) { mlibc::thread_cond_destroy(cond); } int cnd_broadcast(cnd_t *cond) { return mlibc::thread_cond_broadcast(cond) == 0 ? thrd_success : thrd_error; diff --git a/options/ansi/generic/time.cpp b/options/ansi/generic/time.cpp index 614be5c4d5..d56a8dcdab 100644 --- a/options/ansi/generic/time.cpp +++ b/options/ansi/generic/time.cpp @@ -1,22 +1,22 @@ #include #include +#include #include +#include #include +#include #include #include -#include #include -#include -#include #include +#include +#include +#include #include #include -#include -#include -#include #include -#include +#include #include #include @@ -38,28 +38,24 @@ static file_window *get_localtime_window() { clock_t clock(void) { struct timespec ts; - if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts)) + if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts)) return -1; - if(ts.tv_sec > LONG_MAX / 1000000 || ts.tv_nsec / 1000 > LONG_MAX - 1000000 * ts.tv_sec) + if (ts.tv_sec > LONG_MAX / 1000000 || ts.tv_nsec / 1000 > LONG_MAX - 1000000 * ts.tv_sec) return -1; return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; } -double difftime(time_t a, time_t b) { - return a - b; -} +double difftime(time_t a, time_t b) { return a - b; } -time_t mktime(struct tm *tm) { - return timegm(tm); -} +time_t mktime(struct tm *tm) { return timegm(tm); } /* There is no other implemented value than TIME_UTC; all other values * are considered erroneous. */ // Function taken from musl int timespec_get(struct timespec *ts, int base) { - if(base != TIME_UTC) + if (base != TIME_UTC) return 0; int ret = clock_gettime(CLOCK_REALTIME, ts); return ret < 0 ? 0 : base; @@ -72,7 +68,7 @@ char *asctime(const struct tm *ptr) { char *ctime(const time_t *timer) { struct tm *tm = localtime(timer); - if(!tm) { + if (!tm) { return 0; } return asctime(tm); @@ -89,20 +85,24 @@ struct tm *localtime(const time_t *unix_gmt) { return localtime_r(unix_gmt, &per_thread_tm); } -size_t strftime(char *__restrict dest, size_t max_size, - const char *__restrict format, const struct tm *__restrict tm) { +size_t strftime( + char *__restrict dest, + size_t max_size, + const char *__restrict format, + const struct tm *__restrict tm +) { auto c = format; auto p = dest; [[maybe_unused]] bool use_alternative_symbols = false; [[maybe_unused]] bool use_alternative_era_format = false; - while(*c) { + while (*c) { int chunk; auto space = (dest + max_size) - p; __ensure(space >= 0); - if(*c != '%') { - if(!space) + if (*c != '%') { + if (!space) return 0; *p = *c; c++; @@ -110,10 +110,12 @@ size_t strftime(char *__restrict dest, size_t max_size, continue; } - if(*(c + 1) == 'O') { - std::array valid{{'B', 'b', 'd', 'e', 'H', 'I', 'm', 'M', 'S', 'u', 'U', 'V', 'w', 'W', 'y'}}; + if (*(c + 1) == 'O') { + std::array valid{ + {'B', 'b', 'd', 'e', 'H', 'I', 'm', 'M', 'S', 'u', 'U', 'V', 'w', 'W', 'y'} + }; auto next = *(c + 2); - if(std::find(valid.begin(), valid.end(), next) != valid.end()) { + if (std::find(valid.begin(), valid.end(), next) != valid.end()) { use_alternative_symbols = true; c++; } else { @@ -125,10 +127,10 @@ size_t strftime(char *__restrict dest, size_t max_size, c++; continue; } - } else if(*(c + 1) == 'E') { + } else if (*(c + 1) == 'E') { std::array valid{{'c', 'C', 'x', 'X', 'y', 'Y'}}; auto next = *(c + 2); - if(std::find(valid.begin(), valid.end(), next) != valid.end()) { + if (std::find(valid.begin(), valid.end(), next) != valid.end()) { use_alternative_era_format = true; c++; } else { @@ -142,10 +144,10 @@ size_t strftime(char *__restrict dest, size_t max_size, } } - switch(*++c) { + switch (*++c) { case 'Y': { chunk = snprintf(p, space, "%d", 1900 + tm->tm_year); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -153,7 +155,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'm': { chunk = snprintf(p, space, "%.2d", tm->tm_mon + 1); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -161,7 +163,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'd': { chunk = snprintf(p, space, "%.2d", tm->tm_mday); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -169,7 +171,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'Z': { chunk = snprintf(p, space, "%s", "UTC"); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -177,7 +179,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'H': { chunk = snprintf(p, space, "%.2i", tm->tm_hour); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -185,7 +187,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'M': { chunk = snprintf(p, space, "%.2i", tm->tm_min); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -193,7 +195,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'S': { chunk = snprintf(p, space, "%.2d", tm->tm_sec); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -201,7 +203,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'R': { chunk = snprintf(p, space, "%.2i:%.2i", tm->tm_hour, tm->tm_min); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -209,24 +211,26 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'T': { chunk = snprintf(p, space, "%.2i:%.2i:%.2i", tm->tm_hour, tm->tm_min, tm->tm_sec); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; break; } case 'F': { - chunk = snprintf(p, space, "%d-%.2d-%.2d", 1900 + tm->tm_year, tm->tm_mon + 1, - tm->tm_mday); - if(chunk >= space) + chunk = + snprintf(p, space, "%d-%.2d-%.2d", 1900 + tm->tm_year, tm->tm_mon + 1, tm->tm_mday); + if (chunk >= space) return 0; p += chunk; c++; break; } case 'D': { - chunk = snprintf(p, space, "%.2d/%.2d/%.2d", tm->tm_mon + 1, tm->tm_mday, (tm->tm_year + 1900) % 100); - if(chunk >= space) + chunk = snprintf( + p, space, "%.2d/%.2d/%.2d", tm->tm_mon + 1, tm->tm_mday, (tm->tm_year + 1900) % 100 + ); + if (chunk >= space) return 0; p += chunk; c++; @@ -234,11 +238,11 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'a': { int day = tm->tm_wday; - if(day < 0 || day > 6) + if (day < 0 || day > 6) __ensure(!"Day not in bounds."); chunk = snprintf(p, space, "%s", mlibc::nl_langinfo(ABDAY_1 + day)); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -248,13 +252,13 @@ size_t strftime(char *__restrict dest, size_t max_size, case 'B': case 'h': { int mon = tm->tm_mon; - if(mon < 0 || mon > 11) + if (mon < 0 || mon > 11) __ensure(!"Month not in bounds."); nl_item item = (*c == 'B') ? MON_1 : ABMON_1; chunk = snprintf(p, space, "%s", mlibc::nl_langinfo(item + mon)); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -262,16 +266,26 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'c': { int day = tm->tm_wday; - if(day < 0 || day > 6) + if (day < 0 || day > 6) __ensure(!"Day not in bounds."); int mon = tm->tm_mon; - if(mon < 0 || mon > 11) + if (mon < 0 || mon > 11) __ensure(!"Month not in bounds."); - chunk = snprintf(p, space, "%s %s %2d %.2i:%.2i:%.2d %d", mlibc::nl_langinfo(ABDAY_1 + day), - mlibc::nl_langinfo(ABMON_1 + mon), tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, 1900 + tm->tm_year); - if(chunk >= space) + chunk = snprintf( + p, + space, + "%s %s %2d %.2i:%.2i:%.2d %d", + mlibc::nl_langinfo(ABDAY_1 + day), + mlibc::nl_langinfo(ABMON_1 + mon), + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + 1900 + tm->tm_year + ); + if (chunk >= space) return 0; p += chunk; c++; @@ -279,7 +293,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'e': { chunk = snprintf(p, space, "%2d", tm->tm_mday); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -287,12 +301,12 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'l': { int hour = tm->tm_hour; - if(!hour) + if (!hour) hour = 12; - if(hour > 12) + if (hour > 12) hour -= 12; chunk = snprintf(p, space, "%2d", hour); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -300,7 +314,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'k': { chunk = snprintf(p, space, "%2d", tm->tm_hour); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -308,20 +322,21 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'I': { int hour = tm->tm_hour; - if(!hour) + if (!hour) hour = 12; - if(hour > 12) + if (hour > 12) hour -= 12; chunk = snprintf(p, space, "%.2d", hour); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; break; } case 'p': { - chunk = snprintf(p, space, "%s", mlibc::nl_langinfo((tm->tm_hour < 12) ? AM_STR : PM_STR)); - if(chunk >= space) + chunk = + snprintf(p, space, "%s", mlibc::nl_langinfo((tm->tm_hour < 12) ? AM_STR : PM_STR)); + if (chunk >= space) return 0; p += chunk; c++; @@ -330,12 +345,12 @@ size_t strftime(char *__restrict dest, size_t max_size, case 'P': { char *str = mlibc::nl_langinfo((tm->tm_hour < 12) ? AM_STR : PM_STR); char *str_lower = reinterpret_cast(getAllocator().allocate(strlen(str) + 1)); - for(size_t i = 0; str[i]; i++) + for (size_t i = 0; str[i]; i++) str_lower[i] = tolower(str[i]); str_lower[strlen(str)] = '\0'; chunk = snprintf(p, space, "%s", str_lower); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -343,7 +358,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'C': { chunk = snprintf(p, space, "%.2d", (1900 + tm->tm_year) / 100); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -351,7 +366,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'y': { chunk = snprintf(p, space, "%.2d", (1900 + tm->tm_year) % 100); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -359,7 +374,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'j': { chunk = snprintf(p, space, "%.3d", tm->tm_yday + 1); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -367,7 +382,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'A': { chunk = snprintf(p, space, "%s", mlibc::nl_langinfo(DAY_1 + tm->tm_wday)); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -375,13 +390,20 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'r': { int hour = tm->tm_hour; - if(!hour) + if (!hour) hour = 12; - if(hour > 12) + if (hour > 12) hour -= 12; - chunk = snprintf(p, space, "%.2i:%.2i:%.2i %s", hour, tm->tm_min, tm->tm_sec, - mlibc::nl_langinfo((tm->tm_hour < 12) ? AM_STR : PM_STR)); - if(chunk >= space) + chunk = snprintf( + p, + space, + "%.2i:%.2i:%.2i %s", + hour, + tm->tm_min, + tm->tm_sec, + mlibc::nl_langinfo((tm->tm_hour < 12) ? AM_STR : PM_STR) + ); + if (chunk >= space) return 0; p += chunk; c++; @@ -389,7 +411,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case '%': { chunk = snprintf(p, space, "%%"); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -397,7 +419,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 'n': { chunk = snprintf(p, space, "\n"); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -405,7 +427,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case 't': { chunk = snprintf(p, space, "\t"); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; c++; @@ -419,7 +441,7 @@ size_t strftime(char *__restrict dest, size_t max_size, } case '\0': { chunk = snprintf(p, space, "%%"); - if(chunk >= space) + if (chunk >= space) return 0; p += chunk; break; @@ -430,15 +452,15 @@ size_t strftime(char *__restrict dest, size_t max_size, } auto space = (dest + max_size) - p; - if(!space) + if (!space) return 0; *p = '\0'; return (p - dest); } -size_t wcsftime(wchar_t *__restrict, size_t, const wchar_t *__restrict, - const struct tm *__restrict) { +size_t +wcsftime(wchar_t *__restrict, size_t, const wchar_t *__restrict, const struct tm *__restrict) { mlibc::infoLogger() << "mlibc: wcsftime is a stub" << frg::endlog; return 0; } @@ -457,13 +479,13 @@ struct tzfile { uint32_t tzh_charcnt; }; -struct[[gnu::packed]] ttinfo { +struct [[gnu::packed]] ttinfo { int32_t tt_gmtoff; unsigned char tt_isdst; unsigned char tt_abbrind; }; -} +} // namespace // TODO(geert): this function doesn't parse the TZ environment variable // or properly handle the case where information might be missing from /etc/localtime @@ -480,15 +502,14 @@ void tzset(void) { tzfile_time.tzh_typecnt = mlibc::bit_util::byteswap(tzfile_time.tzh_typecnt); tzfile_time.tzh_charcnt = mlibc::bit_util::byteswap(tzfile_time.tzh_charcnt); - if(tzfile_time.magic[0] != 'T' || tzfile_time.magic[1] != 'Z' || tzfile_time.magic[2] != 'i' - || tzfile_time.magic[3] != 'f') { + if (tzfile_time.magic[0] != 'T' || tzfile_time.magic[1] != 'Z' || tzfile_time.magic[2] != 'i' || + tzfile_time.magic[3] != 'f') { mlibc::infoLogger() << "mlibc: /etc/localtime is not a valid TZinfo file" << frg::endlog; return; } - if(tzfile_time.version != '\0' && tzfile_time.version != '2' && tzfile_time.version != '3') { - mlibc::infoLogger() << "mlibc: /etc/localtime has an invalid TZinfo version" - << frg::endlog; + if (tzfile_time.version != '\0' && tzfile_time.version != '2' && tzfile_time.version != '3') { + mlibc::infoLogger() << "mlibc: /etc/localtime has an invalid TZinfo version" << frg::endlog; return; } @@ -496,17 +517,20 @@ void tzset(void) { // TODO: If there is not, we might want to fall back to UTC, no DST (?). __ensure(tzfile_time.tzh_typecnt); - char *abbrevs = reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) - + tzfile_time.tzh_timecnt * sizeof(int32_t) - + tzfile_time.tzh_timecnt * sizeof(uint8_t) - + tzfile_time.tzh_typecnt * sizeof(struct ttinfo); + char *abbrevs = reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) + + tzfile_time.tzh_timecnt * sizeof(int32_t) + + tzfile_time.tzh_timecnt * sizeof(uint8_t) + + tzfile_time.tzh_typecnt * sizeof(struct ttinfo); // start from the last ttinfo entry, this matches the behaviour of glibc and musl for (int i = tzfile_time.tzh_typecnt; i > 0; i--) { ttinfo time_info; - memcpy(&time_info, reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) - + tzfile_time.tzh_timecnt * sizeof(int32_t) - + tzfile_time.tzh_timecnt * sizeof(uint8_t) - + i * sizeof(ttinfo), sizeof(ttinfo)); + memcpy( + &time_info, + reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) + + tzfile_time.tzh_timecnt * sizeof(int32_t) + + tzfile_time.tzh_timecnt * sizeof(uint8_t) + i * sizeof(ttinfo), + sizeof(ttinfo) + ); time_info.tt_gmtoff = mlibc::bit_util::byteswap(time_info.tt_gmtoff); if (!time_info.tt_isdst && !tzname[0]) { tzname[0] = abbrevs + time_info.tt_abbrind; @@ -528,7 +552,7 @@ int nanosleep(const struct timespec *req, struct timespec *) { return -1; } - if(!mlibc::sys_sleep) { + if (!mlibc::sys_sleep) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_sleep()"); } @@ -546,7 +570,7 @@ int nanosleep(const struct timespec *req, struct timespec *) { int clock_getres(clockid_t clockid, struct timespec *res) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_clock_getres, -1); - if(int e = mlibc::sys_clock_getres(clockid, &res->tv_sec, &res->tv_nsec); e) { + if (int e = mlibc::sys_clock_getres(clockid, &res->tv_sec, &res->tv_nsec); e) { errno = e; return -1; } @@ -554,7 +578,7 @@ int clock_getres(clockid_t clockid, struct timespec *res) { } int clock_gettime(clockid_t clock, struct timespec *time) { - if(int e = mlibc::sys_clock_get(clock, &time->tv_sec, &time->tv_nsec); e) { + if (int e = mlibc::sys_clock_get(clock, &time->tv_sec, &time->tv_nsec); e) { errno = e; return -1; } @@ -575,11 +599,11 @@ int clock_settime(clockid_t, const struct timespec *) { time_t time(time_t *out) { time_t secs; long nanos; - if(int e = mlibc::sys_clock_get(CLOCK_REALTIME, &secs, &nanos); e) { + if (int e = mlibc::sys_clock_get(CLOCK_REALTIME, &secs, &nanos); e) { errno = e; return (time_t)-1; } - if(out) + if (out) *out = secs; return secs; } @@ -590,11 +614,11 @@ void civil_from_days(time_t days_since_epoch, int *year, unsigned int *month, un time_t time = days_since_epoch + 719468; int era = (time >= 0 ? time : time - 146096) / 146097; unsigned int doe = static_cast(time - era * 146097); - unsigned int yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; + unsigned int yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; int y = static_cast(yoe) + era * 400; - unsigned int doy = doe - (365*yoe + yoe/4 - yoe/100); - unsigned int mp = (5*doy + 2)/153; - unsigned int d = doy - (153*mp+2)/5 + 1; + unsigned int doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + unsigned int mp = (5 * doy + 2) / 153; + unsigned int d = doy - (153 * mp + 2) / 5 + 1; unsigned int m = mp + (mp < 10 ? 3 : -9); *year = y + (m <= 2); @@ -603,11 +627,13 @@ void civil_from_days(time_t days_since_epoch, int *year, unsigned int *month, un } void weekday_from_days(time_t days_since_epoch, unsigned int *weekday) { - *weekday = static_cast(days_since_epoch >= -4 ? - (days_since_epoch+4) % 7 : (days_since_epoch+5) % 7 + 6); + *weekday = static_cast( + days_since_epoch >= -4 ? (days_since_epoch + 4) % 7 : (days_since_epoch + 5) % 7 + 6 + ); } -void yearday_from_date(unsigned int year, unsigned int month, unsigned int day, unsigned int *yday) { +void +yearday_from_date(unsigned int year, unsigned int month, unsigned int day, unsigned int *yday) { unsigned int n1 = 275 * month / 9; unsigned int n2 = (month + 9) / 12; unsigned int n3 = (1 + (year - 4 * year / 4 + 2) / 3); @@ -630,28 +656,31 @@ int unix_local_from_gmt(time_t unix_gmt, time_t *offset, bool *dst, char **tm_zo tzfile_time.tzh_typecnt = mlibc::bit_util::byteswap(tzfile_time.tzh_typecnt); tzfile_time.tzh_charcnt = mlibc::bit_util::byteswap(tzfile_time.tzh_charcnt); - if(tzfile_time.magic[0] != 'T' || tzfile_time.magic[1] != 'Z' || tzfile_time.magic[2] != 'i' - || tzfile_time.magic[3] != 'f') { + if (tzfile_time.magic[0] != 'T' || tzfile_time.magic[1] != 'Z' || tzfile_time.magic[2] != 'i' || + tzfile_time.magic[3] != 'f') { mlibc::infoLogger() << "mlibc: /etc/localtime is not a valid TZinfo file" << frg::endlog; return -1; } - if(tzfile_time.version != '\0' && tzfile_time.version != '2' && tzfile_time.version != '3') { - mlibc::infoLogger() << "mlibc: /etc/localtime has an invalid TZinfo version" - << frg::endlog; + if (tzfile_time.version != '\0' && tzfile_time.version != '2' && tzfile_time.version != '3') { + mlibc::infoLogger() << "mlibc: /etc/localtime has an invalid TZinfo version" << frg::endlog; return -1; } int index = -1; - for(size_t i = 0; i < tzfile_time.tzh_timecnt; i++) { + for (size_t i = 0; i < tzfile_time.tzh_timecnt; i++) { int32_t ttime; - memcpy(&ttime, reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) - + i * sizeof(int32_t), sizeof(int32_t)); + memcpy( + &ttime, + reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) + + i * sizeof(int32_t), + sizeof(int32_t) + ); ttime = mlibc::bit_util::byteswap(ttime); // If we are before the first transition, the format dicates that // the first ttinfo entry should be used (and not the ttinfo entry pointed // to by the first transition time). - if(i && ttime > unix_gmt) { + if (i && ttime > unix_gmt) { index = i - 1; break; } @@ -660,10 +689,13 @@ int unix_local_from_gmt(time_t unix_gmt, time_t *offset, bool *dst, char **tm_zo // The format dictates that if no transition is applicable, // the first entry in the file is chosen. uint8_t ttinfo_index = 0; - if(index >= 0) { - memcpy(&ttinfo_index, reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) - + tzfile_time.tzh_timecnt * sizeof(int32_t) - + index * sizeof(uint8_t), sizeof(uint8_t)); + if (index >= 0) { + memcpy( + &ttinfo_index, + reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) + + tzfile_time.tzh_timecnt * sizeof(int32_t) + index * sizeof(uint8_t), + sizeof(uint8_t) + ); } // There should be at least one entry in the ttinfo table. @@ -671,16 +703,19 @@ int unix_local_from_gmt(time_t unix_gmt, time_t *offset, bool *dst, char **tm_zo __ensure(tzfile_time.tzh_typecnt); ttinfo time_info; - memcpy(&time_info, reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) - + tzfile_time.tzh_timecnt * sizeof(int32_t) - + tzfile_time.tzh_timecnt * sizeof(uint8_t) - + ttinfo_index * sizeof(ttinfo), sizeof(ttinfo)); + memcpy( + &time_info, + reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) + + tzfile_time.tzh_timecnt * sizeof(int32_t) + tzfile_time.tzh_timecnt * sizeof(uint8_t) + + ttinfo_index * sizeof(ttinfo), + sizeof(ttinfo) + ); time_info.tt_gmtoff = mlibc::bit_util::byteswap(time_info.tt_gmtoff); - char *abbrevs = reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) - + tzfile_time.tzh_timecnt * sizeof(int32_t) - + tzfile_time.tzh_timecnt * sizeof(uint8_t) - + tzfile_time.tzh_typecnt * sizeof(struct ttinfo); + char *abbrevs = reinterpret_cast(get_localtime_window()->get()) + sizeof(tzfile) + + tzfile_time.tzh_timecnt * sizeof(int32_t) + + tzfile_time.tzh_timecnt * sizeof(uint8_t) + + tzfile_time.tzh_typecnt * sizeof(struct ttinfo); *offset = time_info.tt_gmtoff; *dst = time_info.tt_isdst; @@ -688,7 +723,7 @@ int unix_local_from_gmt(time_t unix_gmt, time_t *offset, bool *dst, char **tm_zo return 0; } -} //anonymous namespace +} // anonymous namespace struct tm *gmtime_r(const time_t *unix_gmt, struct tm *res) { int year; @@ -699,14 +734,14 @@ struct tm *gmtime_r(const time_t *unix_gmt, struct tm *res) { time_t unix_local = *unix_gmt; - int days_since_epoch = unix_local / (60*60*24); + int days_since_epoch = unix_local / (60 * 60 * 24); civil_from_days(days_since_epoch, &year, &month, &day); weekday_from_days(days_since_epoch, &weekday); yearday_from_date(year, month, day, &yday); res->tm_sec = unix_local % 60; res->tm_min = (unix_local / 60) % 60; - res->tm_hour = (unix_local / (60*60)) % 24; + res->tm_hour = (unix_local / (60 * 60)) % 24; res->tm_mday = day; res->tm_mon = month - 1; res->tm_year = year - 1900; @@ -731,20 +766,20 @@ struct tm *localtime_r(const time_t *unix_gmt, struct tm *res) { char *tm_zone; frg::unique_lock lock(__time_lock); // TODO: Set errno if the conversion fails. - if(unix_local_from_gmt(*unix_gmt, &offset, &dst, &tm_zone)) { + if (unix_local_from_gmt(*unix_gmt, &offset, &dst, &tm_zone)) { __ensure(!"Error parsing /etc/localtime"); __builtin_unreachable(); } time_t unix_local = *unix_gmt + offset; - int days_since_epoch = unix_local / (60*60*24); + int days_since_epoch = unix_local / (60 * 60 * 24); civil_from_days(days_since_epoch, &year, &month, &day); weekday_from_days(days_since_epoch, &weekday); yearday_from_date(year, month, day, &yday); res->tm_sec = unix_local % 60; res->tm_min = (unix_local / 60) % 60; - res->tm_hour = (unix_local / (60*60)) % 24; + res->tm_hour = (unix_local / (60 * 60)) % 24; res->tm_mday = day; res->tm_mon = month - 1; res->tm_year = year - 1900; @@ -759,25 +794,25 @@ struct tm *localtime_r(const time_t *unix_gmt, struct tm *res) { // This implementation of asctime_r is taken from sortix char *asctime_r(const struct tm *tm, char *buf) { - static char weekday_names[7][4] = - { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; - static char month_names[12][4] = - { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", - "Nov", "Dec" }; - sprintf(buf, "%.3s %.3s%3d %.2d:%.2d%.2d %d\n", - weekday_names[tm->tm_wday], - month_names[tm->tm_mon], - tm->tm_mday, - tm->tm_hour, - tm->tm_min, - tm->tm_sec, - tm->tm_year + 1900); + static char weekday_names[7][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + static char month_names[12][4] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + }; + sprintf( + buf, + "%.3s %.3s%3d %.2d:%.2d%.2d %d\n", + weekday_names[tm->tm_wday], + month_names[tm->tm_mon], + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + tm->tm_year + 1900 + ); return buf; } -char *ctime_r(const time_t *clock, char *buf) { - return asctime_r(localtime(clock), buf); -} +char *ctime_r(const time_t *clock, char *buf) { return asctime_r(localtime(clock), buf); } time_t timelocal(struct tm *) { __ensure(!"Not implemented"); @@ -787,9 +822,9 @@ time_t timelocal(struct tm *) { constexpr static int days_from_civil(int y, unsigned m, unsigned d) noexcept { y -= m <= 2; const int era = (y >= 0 ? y : y - 399) / 400; - const unsigned yoe = static_cast(y - era * 400); // [0, 399] + const unsigned yoe = static_cast(y - era * 400); // [0, 399] const unsigned doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1; // [0, 365] - const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096] return era * 146097 + static_cast(doe) - 719468; } diff --git a/options/ansi/generic/uchar.cpp b/options/ansi/generic/uchar.cpp index cb13c12f4d..26a83208a0 100644 --- a/options/ansi/generic/uchar.cpp +++ b/options/ansi/generic/uchar.cpp @@ -4,13 +4,15 @@ size_t c32rtomb(char *, char32_t, mbstate_t *) MLIBC_STUB_BODY -size_t mbrtoc32(char32_t *__restrict pc32, const char *__restrict pmb, size_t max, mbstate_t *__restrict ps) { + size_t mbrtoc32( + char32_t *__restrict pc32, const char *__restrict pmb, size_t max, mbstate_t *__restrict ps + ) { static mbstate_t internal_state; - if(!ps) + if (!ps) ps = &internal_state; - if(!pmb) + if (!pmb) return mbrtoc32(0, "", 1, ps); wchar_t wc; diff --git a/options/ansi/generic/wchar.cpp b/options/ansi/generic/wchar.cpp index 85fc163b0e..9a3f232b3c 100644 --- a/options/ansi/generic/wchar.cpp +++ b/options/ansi/generic/wchar.cpp @@ -1,31 +1,31 @@ +#include #include -#include #include +#include #include #include -#include #include #include namespace { - // All conversion functions mbrlen(), mbrtowc(), wcrtomb(), - // mbsrtowcs() and wcsrtombs() have an internal state. - __mlibc_mbstate mbrlen_state = __MLIBC_MBSTATE_INITIALIZER; - __mlibc_mbstate mbrtowc_state = __MLIBC_MBSTATE_INITIALIZER; - __mlibc_mbstate mbsrtowcs_state = __MLIBC_MBSTATE_INITIALIZER; - __mlibc_mbstate wcsrtombs_state = __MLIBC_MBSTATE_INITIALIZER; -} +// All conversion functions mbrlen(), mbrtowc(), wcrtomb(), +// mbsrtowcs() and wcsrtombs() have an internal state. +__mlibc_mbstate mbrlen_state = __MLIBC_MBSTATE_INITIALIZER; +__mlibc_mbstate mbrtowc_state = __MLIBC_MBSTATE_INITIALIZER; +__mlibc_mbstate mbsrtowcs_state = __MLIBC_MBSTATE_INITIALIZER; +__mlibc_mbstate wcsrtombs_state = __MLIBC_MBSTATE_INITIALIZER; +} // namespace wint_t btowc(int c) { - if(c == EOF) + if (c == EOF) return WEOF; char nc = c; auto cc = mlibc::current_charcode(); wchar_t wc; - if(auto e = cc->promote_wtranscode(nc, wc); e != mlibc::charcode_error::null) + if (auto e = cc->promote_wtranscode(nc, wc); e != mlibc::charcode_error::null) return WEOF; return wc; } @@ -36,7 +36,7 @@ int wctob(wint_t wc) { } int mbsinit(const mbstate_t *stp) { - if(!stp) + if (!stp) return -1; return !stp->__progress && !stp->__shift; } @@ -45,43 +45,45 @@ size_t mbrlen(const char *__restrict mbs, size_t mb_limit, mbstate_t *__restrict auto cc = mlibc::current_charcode(); wchar_t wc; - if(!stp) + if (!stp) stp = &mbrlen_state; - if(!mbs) { + if (!mbs) { *stp = __MLIBC_MBSTATE_INITIALIZER; return 0; } mlibc::code_seq nseq{mbs, mbs + mb_limit}; mlibc::code_seq wseq{&wc, &wc + 1}; - if(auto e = cc->decode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) + if (auto e = cc->decode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return nseq.it - mbs; } -size_t mbrtowc(wchar_t *__restrict wcp, const char *__restrict mbs, size_t mb_limit, mbstate_t *__restrict stp) { +size_t mbrtowc( + wchar_t *__restrict wcp, const char *__restrict mbs, size_t mb_limit, mbstate_t *__restrict stp +) { auto cc = mlibc::current_charcode(); - if(!stp) + if (!stp) stp = &mbrtowc_state; - if(!mbs) { + if (!mbs) { *stp = __MLIBC_MBSTATE_INITIALIZER; return 0; } wchar_t temp = 0; - if(!wcp) + if (!wcp) wcp = &temp; mlibc::code_seq nseq{mbs, mbs + mb_limit}; mlibc::code_seq wseq{wcp, wcp + 1}; - if(auto e = cc->decode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { - if(e == mlibc::charcode_error::input_underflow) + if (auto e = cc->decode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { + if (e == mlibc::charcode_error::input_underflow) return static_cast(-2); __ensure(e == mlibc::charcode_error::illegal_input); errno = EILSEQ; return static_cast(-1); - }else{ + } else { if (*mbs) { return nseq.it - mbs; } else { @@ -103,18 +105,23 @@ size_t wcrtomb(char *__restrict mbs, wchar_t wc, mbstate_t *__restrict stp) { mlibc::code_seq wseq{&wc, &wc + 1}; mlibc::code_seq nseq{mbs, mbs + 4}; // TODO: Replace 4 by some named constant. - if(auto e = cc->encode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { + if (auto e = cc->encode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { __ensure(!"encode_wtranscode() errors are not handled"); __builtin_unreachable(); - }else{ + } else { size_t n = nseq.it - mbs; - if(!n) // Null-terminate resulting wide string. + if (!n) // Null-terminate resulting wide string. *mbs = 0; return n; } } -size_t mbsrtowcs(wchar_t *__restrict wcs, const char **__restrict mbsp, size_t wc_limit, mbstate_t *__restrict stp) { +size_t mbsrtowcs( + wchar_t *__restrict wcs, + const char **__restrict mbsp, + size_t wc_limit, + mbstate_t *__restrict stp +) { __ensure(mbsp); auto cc = mlibc::current_charcode(); @@ -122,29 +129,36 @@ size_t mbsrtowcs(wchar_t *__restrict wcs, const char **__restrict mbsp, size_t w mlibc::code_seq nseq{*mbsp, nullptr}; mlibc::code_seq wseq{wcs, wcs + wc_limit}; - if(!stp) + if (!stp) stp = &mbsrtowcs_state; - if(!wcs) { + if (!wcs) { size_t size; - if(auto e = cc->decode_wtranscode_length(nseq, &size, st); e != mlibc::charcode_error::null) + if (auto e = cc->decode_wtranscode_length(nseq, &size, st); + e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return size; } - if(auto e = cc->decode_wtranscode(nseq, wseq, st); e != mlibc::charcode_error::null) { + if (auto e = cc->decode_wtranscode(nseq, wseq, st); e != mlibc::charcode_error::null) { __ensure(!"decode_wtranscode() errors are not handled"); __builtin_unreachable(); - }else{ + } else { size_t n = wseq.it - wcs; - if(n < wc_limit) // Null-terminate resulting wide string. + if (n < wc_limit) // Null-terminate resulting wide string. wcs[n] = 0; *mbsp = nullptr; return n; } } -size_t mbsnrtowcs(wchar_t *__restrict wcs, const char **__restrict mbsp, size_t mb_limit, size_t wc_limit, mbstate_t *__restrict stp) { +size_t mbsnrtowcs( + wchar_t *__restrict wcs, + const char **__restrict mbsp, + size_t mb_limit, + size_t wc_limit, + mbstate_t *__restrict stp +) { __ensure(mbsp); auto cc = mlibc::current_charcode(); @@ -152,80 +166,94 @@ size_t mbsnrtowcs(wchar_t *__restrict wcs, const char **__restrict mbsp, size_t mlibc::code_seq nseq{*mbsp, (*mbsp) + mb_limit}; mlibc::code_seq wseq{wcs, wcs + wc_limit}; - if(!stp) + if (!stp) stp = &mbsrtowcs_state; - if(!wcs) { + if (!wcs) { size_t size; - if(auto e = cc->decode_wtranscode_length(nseq, &size, st); e != mlibc::charcode_error::null) + if (auto e = cc->decode_wtranscode_length(nseq, &size, st); + e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return size; } - if(auto e = cc->decode_wtranscode(nseq, wseq, st); e != mlibc::charcode_error::null) { + if (auto e = cc->decode_wtranscode(nseq, wseq, st); e != mlibc::charcode_error::null) { __ensure(!"decode_wtranscode() errors are not handled"); __builtin_unreachable(); - }else{ + } else { size_t n = wseq.it - wcs; - if(n < wc_limit) // Null-terminate resulting wide string. + if (n < wc_limit) // Null-terminate resulting wide string. wcs[n] = 0; *mbsp = nullptr; return n; } } -size_t wcsrtombs(char *__restrict mbs, const wchar_t **__restrict wcsp, size_t mb_limit, mbstate_t *__restrict stp) { +size_t wcsrtombs( + char *__restrict mbs, + const wchar_t **__restrict wcsp, + size_t mb_limit, + mbstate_t *__restrict stp +) { __ensure(wcsp && "wcsrtombs() with null input"); auto cc = mlibc::current_charcode(); mlibc::code_seq wseq{*wcsp, nullptr}; - if(!stp) + if (!stp) stp = &wcsrtombs_state; - if(!mbs) { + if (!mbs) { size_t size; - if(auto e = cc->encode_wtranscode_length(wseq, &size, *stp); e != mlibc::charcode_error::null) + if (auto e = cc->encode_wtranscode_length(wseq, &size, *stp); + e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return size; } mlibc::code_seq nseq{mbs, mbs + mb_limit}; - if(auto e = cc->encode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { + if (auto e = cc->encode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { __ensure(!"encode_wtranscode() errors are not handled"); __builtin_unreachable(); - }else{ + } else { *wcsp = wseq.it; size_t n = nseq.it - mbs; - if(n < mb_limit) // Null-terminate resulting narrow string. + if (n < mb_limit) // Null-terminate resulting narrow string. mbs[n] = 0; return n; } } -size_t wcsnrtombs(char *__restrict mbs, const wchar_t **__restrict wcsp, size_t wc_limit, size_t mb_limit, mbstate_t *__restrict stp) { +size_t wcsnrtombs( + char *__restrict mbs, + const wchar_t **__restrict wcsp, + size_t wc_limit, + size_t mb_limit, + mbstate_t *__restrict stp +) { __ensure(wcsp && "wcsrtombs() with null input"); auto cc = mlibc::current_charcode(); mlibc::code_seq nseq{mbs, mbs + mb_limit}; mlibc::code_seq wseq{*wcsp, (*wcsp) + wc_limit}; - if(!stp) + if (!stp) stp = &wcsrtombs_state; - if(!mbs) { + if (!mbs) { size_t size; - if(auto e = cc->encode_wtranscode_length(wseq, &size, *stp); e != mlibc::charcode_error::null) + if (auto e = cc->encode_wtranscode_length(wseq, &size, *stp); + e != mlibc::charcode_error::null) __ensure(!"decode_wtranscode() errors are not handled"); return size; } - if(auto e = cc->encode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { + if (auto e = cc->encode_wtranscode(nseq, wseq, *stp); e != mlibc::charcode_error::null) { __ensure(!"encode_wtranscode() errors are not handled"); __builtin_unreachable(); - }else{ + } else { *wcsp = wseq.it; size_t n = nseq.it - mbs; - if(n < mb_limit) // Null-terminate resulting narrow string. + if (n < mb_limit) // Null-terminate resulting narrow string. mbs[n] = 0; return n; } @@ -255,456 +283,457 @@ struct width_interval { // From https://github.com/jquast/wcwidth/blob/master/wcwidth/table_zero.py // at commit b29897e5a1b403a0e36f7fc991614981cbc42475 (2020-07-14): struct width_interval ZERO_WIDTH[] = { - {0x00300, 0x0036f}, // Combining Grave Accent ..Combining Latin Small Le - {0x00483, 0x00489}, // Combining Cyrillic Titlo..Combining Cyrillic Milli - {0x00591, 0x005bd}, // Hebrew Accent Etnahta ..Hebrew Point Meteg - {0x005bf, 0x005bf}, // Hebrew Point Rafe ..Hebrew Point Rafe - {0x005c1, 0x005c2}, // Hebrew Point Shin Dot ..Hebrew Point Sin Dot - {0x005c4, 0x005c5}, // Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot - {0x005c7, 0x005c7}, // Hebrew Point Qamats Qata..Hebrew Point Qamats Qata - {0x00610, 0x0061a}, // Arabic Sign Sallallahou ..Arabic Small Kasra - {0x0064b, 0x0065f}, // Arabic Fathatan ..Arabic Wavy Hamza Below - {0x00670, 0x00670}, // Arabic Letter Superscrip..Arabic Letter Superscrip - {0x006d6, 0x006dc}, // Arabic Small High Ligatu..Arabic Small High Seen - {0x006df, 0x006e4}, // Arabic Small High Rounde..Arabic Small High Madda - {0x006e7, 0x006e8}, // Arabic Small High Yeh ..Arabic Small High Noon - {0x006ea, 0x006ed}, // Arabic Empty Centre Low ..Arabic Small Low Meem - {0x00711, 0x00711}, // Syriac Letter Superscrip..Syriac Letter Superscrip - {0x00730, 0x0074a}, // Syriac Pthaha Above ..Syriac Barrekh - {0x007a6, 0x007b0}, // Thaana Abafili ..Thaana Sukun - {0x007eb, 0x007f3}, // Nko Combining Short High..Nko Combining Double Dot - {0x007fd, 0x007fd}, // Nko Dantayalan ..Nko Dantayalan - {0x00816, 0x00819}, // Samaritan Mark In ..Samaritan Mark Dagesh - {0x0081b, 0x00823}, // Samaritan Mark Epentheti..Samaritan Vowel Sign A - {0x00825, 0x00827}, // Samaritan Vowel Sign Sho..Samaritan Vowel Sign U - {0x00829, 0x0082d}, // Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa - {0x00859, 0x0085b}, // Mandaic Affrication Mark..Mandaic Gemination Mark - {0x008d3, 0x008e1}, // Arabic Small Low Waw ..Arabic Small High Sign S - {0x008e3, 0x00902}, // Arabic Turned Damma Belo..Devanagari Sign Anusvara - {0x0093a, 0x0093a}, // Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe - {0x0093c, 0x0093c}, // Devanagari Sign Nukta ..Devanagari Sign Nukta - {0x00941, 0x00948}, // Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai - {0x0094d, 0x0094d}, // Devanagari Sign Virama ..Devanagari Sign Virama - {0x00951, 0x00957}, // Devanagari Stress Sign U..Devanagari Vowel Sign Uu - {0x00962, 0x00963}, // Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo - {0x00981, 0x00981}, // Bengali Sign Candrabindu..Bengali Sign Candrabindu - {0x009bc, 0x009bc}, // Bengali Sign Nukta ..Bengali Sign Nukta - {0x009c1, 0x009c4}, // Bengali Vowel Sign U ..Bengali Vowel Sign Vocal - {0x009cd, 0x009cd}, // Bengali Sign Virama ..Bengali Sign Virama - {0x009e2, 0x009e3}, // Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal - {0x009fe, 0x009fe}, // Bengali Sandhi Mark ..Bengali Sandhi Mark - {0x00a01, 0x00a02}, // Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi - {0x00a3c, 0x00a3c}, // Gurmukhi Sign Nukta ..Gurmukhi Sign Nukta - {0x00a41, 0x00a42}, // Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu - {0x00a47, 0x00a48}, // Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai - {0x00a4b, 0x00a4d}, // Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama - {0x00a51, 0x00a51}, // Gurmukhi Sign Udaat ..Gurmukhi Sign Udaat - {0x00a70, 0x00a71}, // Gurmukhi Tippi ..Gurmukhi Addak - {0x00a75, 0x00a75}, // Gurmukhi Sign Yakash ..Gurmukhi Sign Yakash - {0x00a81, 0x00a82}, // Gujarati Sign Candrabind..Gujarati Sign Anusvara - {0x00abc, 0x00abc}, // Gujarati Sign Nukta ..Gujarati Sign Nukta - {0x00ac1, 0x00ac5}, // Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand - {0x00ac7, 0x00ac8}, // Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai - {0x00acd, 0x00acd}, // Gujarati Sign Virama ..Gujarati Sign Virama - {0x00ae2, 0x00ae3}, // Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca - {0x00afa, 0x00aff}, // Gujarati Sign Sukun ..Gujarati Sign Two-circle - {0x00b01, 0x00b01}, // Oriya Sign Candrabindu ..Oriya Sign Candrabindu - {0x00b3c, 0x00b3c}, // Oriya Sign Nukta ..Oriya Sign Nukta - {0x00b3f, 0x00b3f}, // Oriya Vowel Sign I ..Oriya Vowel Sign I - {0x00b41, 0x00b44}, // Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic - {0x00b4d, 0x00b4d}, // Oriya Sign Virama ..Oriya Sign Virama - {0x00b55, 0x00b56}, // (nil) ..Oriya Ai Length Mark - {0x00b62, 0x00b63}, // Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic - {0x00b82, 0x00b82}, // Tamil Sign Anusvara ..Tamil Sign Anusvara - {0x00bc0, 0x00bc0}, // Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii - {0x00bcd, 0x00bcd}, // Tamil Sign Virama ..Tamil Sign Virama - {0x00c00, 0x00c00}, // Telugu Sign Combining Ca..Telugu Sign Combining Ca - {0x00c04, 0x00c04}, // Telugu Sign Combining An..Telugu Sign Combining An - {0x00c3e, 0x00c40}, // Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii - {0x00c46, 0x00c48}, // Telugu Vowel Sign E ..Telugu Vowel Sign Ai - {0x00c4a, 0x00c4d}, // Telugu Vowel Sign O ..Telugu Sign Virama - {0x00c55, 0x00c56}, // Telugu Length Mark ..Telugu Ai Length Mark - {0x00c62, 0x00c63}, // Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali - {0x00c81, 0x00c81}, // Kannada Sign Candrabindu..Kannada Sign Candrabindu - {0x00cbc, 0x00cbc}, // Kannada Sign Nukta ..Kannada Sign Nukta - {0x00cbf, 0x00cbf}, // Kannada Vowel Sign I ..Kannada Vowel Sign I - {0x00cc6, 0x00cc6}, // Kannada Vowel Sign E ..Kannada Vowel Sign E - {0x00ccc, 0x00ccd}, // Kannada Vowel Sign Au ..Kannada Sign Virama - {0x00ce2, 0x00ce3}, // Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal - {0x00d00, 0x00d01}, // Malayalam Sign Combining..Malayalam Sign Candrabin - {0x00d3b, 0x00d3c}, // Malayalam Sign Vertical ..Malayalam Sign Circular - {0x00d41, 0x00d44}, // Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc - {0x00d4d, 0x00d4d}, // Malayalam Sign Virama ..Malayalam Sign Virama - {0x00d62, 0x00d63}, // Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc - {0x00d81, 0x00d81}, // (nil) ..(nil) - {0x00dca, 0x00dca}, // Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna - {0x00dd2, 0x00dd4}, // Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti - {0x00dd6, 0x00dd6}, // Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga - {0x00e31, 0x00e31}, // Thai Character Mai Han-a..Thai Character Mai Han-a - {0x00e34, 0x00e3a}, // Thai Character Sara I ..Thai Character Phinthu - {0x00e47, 0x00e4e}, // Thai Character Maitaikhu..Thai Character Yamakkan - {0x00eb1, 0x00eb1}, // Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan - {0x00eb4, 0x00ebc}, // Lao Vowel Sign I ..Lao Semivowel Sign Lo - {0x00ec8, 0x00ecd}, // Lao Tone Mai Ek ..Lao Niggahita - {0x00f18, 0x00f19}, // Tibetan Astrological Sig..Tibetan Astrological Sig - {0x00f35, 0x00f35}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung - {0x00f37, 0x00f37}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung - {0x00f39, 0x00f39}, // Tibetan Mark Tsa -phru ..Tibetan Mark Tsa -phru - {0x00f71, 0x00f7e}, // Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga - {0x00f80, 0x00f84}, // Tibetan Vowel Sign Rever..Tibetan Mark Halanta - {0x00f86, 0x00f87}, // Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags - {0x00f8d, 0x00f97}, // Tibetan Subjoined Sign L..Tibetan Subjoined Letter - {0x00f99, 0x00fbc}, // Tibetan Subjoined Letter..Tibetan Subjoined Letter - {0x00fc6, 0x00fc6}, // Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda - {0x0102d, 0x01030}, // Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu - {0x01032, 0x01037}, // Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below - {0x01039, 0x0103a}, // Myanmar Sign Virama ..Myanmar Sign Asat - {0x0103d, 0x0103e}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M - {0x01058, 0x01059}, // Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal - {0x0105e, 0x01060}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M - {0x01071, 0x01074}, // Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah - {0x01082, 0x01082}, // Myanmar Consonant Sign S..Myanmar Consonant Sign S - {0x01085, 0x01086}, // Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan - {0x0108d, 0x0108d}, // Myanmar Sign Shan Counci..Myanmar Sign Shan Counci - {0x0109d, 0x0109d}, // Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton - {0x0135d, 0x0135f}, // Ethiopic Combining Gemin..Ethiopic Combining Gemin - {0x01712, 0x01714}, // Tagalog Vowel Sign I ..Tagalog Sign Virama - {0x01732, 0x01734}, // Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod - {0x01752, 0x01753}, // Buhid Vowel Sign I ..Buhid Vowel Sign U - {0x01772, 0x01773}, // Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U - {0x017b4, 0x017b5}, // Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa - {0x017b7, 0x017bd}, // Khmer Vowel Sign I ..Khmer Vowel Sign Ua - {0x017c6, 0x017c6}, // Khmer Sign Nikahit ..Khmer Sign Nikahit - {0x017c9, 0x017d3}, // Khmer Sign Muusikatoan ..Khmer Sign Bathamasat - {0x017dd, 0x017dd}, // Khmer Sign Atthacan ..Khmer Sign Atthacan - {0x0180b, 0x0180d}, // Mongolian Free Variation..Mongolian Free Variation - {0x01885, 0x01886}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal - {0x018a9, 0x018a9}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal - {0x01920, 0x01922}, // Limbu Vowel Sign A ..Limbu Vowel Sign U - {0x01927, 0x01928}, // Limbu Vowel Sign E ..Limbu Vowel Sign O - {0x01932, 0x01932}, // Limbu Small Letter Anusv..Limbu Small Letter Anusv - {0x01939, 0x0193b}, // Limbu Sign Mukphreng ..Limbu Sign Sa-i - {0x01a17, 0x01a18}, // Buginese Vowel Sign I ..Buginese Vowel Sign U - {0x01a1b, 0x01a1b}, // Buginese Vowel Sign Ae ..Buginese Vowel Sign Ae - {0x01a56, 0x01a56}, // Tai Tham Consonant Sign ..Tai Tham Consonant Sign - {0x01a58, 0x01a5e}, // Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign - {0x01a60, 0x01a60}, // Tai Tham Sign Sakot ..Tai Tham Sign Sakot - {0x01a62, 0x01a62}, // Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai - {0x01a65, 0x01a6c}, // Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B - {0x01a73, 0x01a7c}, // Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue - {0x01a7f, 0x01a7f}, // Tai Tham Combining Crypt..Tai Tham Combining Crypt - {0x01ab0, 0x01ac0}, // Combining Doubled Circum..(nil) - {0x01b00, 0x01b03}, // Balinese Sign Ulu Ricem ..Balinese Sign Surang - {0x01b34, 0x01b34}, // Balinese Sign Rerekan ..Balinese Sign Rerekan - {0x01b36, 0x01b3a}, // Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R - {0x01b3c, 0x01b3c}, // Balinese Vowel Sign La L..Balinese Vowel Sign La L - {0x01b42, 0x01b42}, // Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe - {0x01b6b, 0x01b73}, // Balinese Musical Symbol ..Balinese Musical Symbol - {0x01b80, 0x01b81}, // Sundanese Sign Panyecek ..Sundanese Sign Panglayar - {0x01ba2, 0x01ba5}, // Sundanese Consonant Sign..Sundanese Vowel Sign Pan - {0x01ba8, 0x01ba9}, // Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan - {0x01bab, 0x01bad}, // Sundanese Sign Virama ..Sundanese Consonant Sign - {0x01be6, 0x01be6}, // Batak Sign Tompi ..Batak Sign Tompi - {0x01be8, 0x01be9}, // Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee - {0x01bed, 0x01bed}, // Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O - {0x01bef, 0x01bf1}, // Batak Vowel Sign U For S..Batak Consonant Sign H - {0x01c2c, 0x01c33}, // Lepcha Vowel Sign E ..Lepcha Consonant Sign T - {0x01c36, 0x01c37}, // Lepcha Sign Ran ..Lepcha Sign Nukta - {0x01cd0, 0x01cd2}, // Vedic Tone Karshana ..Vedic Tone Prenkha - {0x01cd4, 0x01ce0}, // Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash - {0x01ce2, 0x01ce8}, // Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda - {0x01ced, 0x01ced}, // Vedic Sign Tiryak ..Vedic Sign Tiryak - {0x01cf4, 0x01cf4}, // Vedic Tone Candra Above ..Vedic Tone Candra Above - {0x01cf8, 0x01cf9}, // Vedic Tone Ring Above ..Vedic Tone Double Ring A - {0x01dc0, 0x01df9}, // Combining Dotted Grave A..Combining Wide Inverted - {0x01dfb, 0x01dff}, // Combining Deletion Mark ..Combining Right Arrowhea - {0x020d0, 0x020f0}, // Combining Left Harpoon A..Combining Asterisk Above - {0x02cef, 0x02cf1}, // Coptic Combining Ni Abov..Coptic Combining Spiritu - {0x02d7f, 0x02d7f}, // Tifinagh Consonant Joine..Tifinagh Consonant Joine - {0x02de0, 0x02dff}, // Combining Cyrillic Lette..Combining Cyrillic Lette - {0x0302a, 0x0302d}, // Ideographic Level Tone M..Ideographic Entering Ton - {0x03099, 0x0309a}, // Combining Katakana-hirag..Combining Katakana-hirag - {0x0a66f, 0x0a672}, // Combining Cyrillic Vzmet..Combining Cyrillic Thous - {0x0a674, 0x0a67d}, // Combining Cyrillic Lette..Combining Cyrillic Payer - {0x0a69e, 0x0a69f}, // Combining Cyrillic Lette..Combining Cyrillic Lette - {0x0a6f0, 0x0a6f1}, // Bamum Combining Mark Koq..Bamum Combining Mark Tuk - {0x0a802, 0x0a802}, // Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva - {0x0a806, 0x0a806}, // Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant - {0x0a80b, 0x0a80b}, // Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva - {0x0a825, 0x0a826}, // Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign - {0x0a82c, 0x0a82c}, // (nil) ..(nil) - {0x0a8c4, 0x0a8c5}, // Saurashtra Sign Virama ..Saurashtra Sign Candrabi - {0x0a8e0, 0x0a8f1}, // Combining Devanagari Dig..Combining Devanagari Sig - {0x0a8ff, 0x0a8ff}, // Devanagari Vowel Sign Ay..Devanagari Vowel Sign Ay - {0x0a926, 0x0a92d}, // Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop - {0x0a947, 0x0a951}, // Rejang Vowel Sign I ..Rejang Consonant Sign R - {0x0a980, 0x0a982}, // Javanese Sign Panyangga ..Javanese Sign Layar - {0x0a9b3, 0x0a9b3}, // Javanese Sign Cecak Telu..Javanese Sign Cecak Telu - {0x0a9b6, 0x0a9b9}, // Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku - {0x0a9bc, 0x0a9bd}, // Javanese Vowel Sign Pepe..Javanese Consonant Sign - {0x0a9e5, 0x0a9e5}, // Myanmar Sign Shan Saw ..Myanmar Sign Shan Saw - {0x0aa29, 0x0aa2e}, // Cham Vowel Sign Aa ..Cham Vowel Sign Oe - {0x0aa31, 0x0aa32}, // Cham Vowel Sign Au ..Cham Vowel Sign Ue - {0x0aa35, 0x0aa36}, // Cham Consonant Sign La ..Cham Consonant Sign Wa - {0x0aa43, 0x0aa43}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina - {0x0aa4c, 0x0aa4c}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina - {0x0aa7c, 0x0aa7c}, // Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T - {0x0aab0, 0x0aab0}, // Tai Viet Mai Kang ..Tai Viet Mai Kang - {0x0aab2, 0x0aab4}, // Tai Viet Vowel I ..Tai Viet Vowel U - {0x0aab7, 0x0aab8}, // Tai Viet Mai Khit ..Tai Viet Vowel Ia - {0x0aabe, 0x0aabf}, // Tai Viet Vowel Am ..Tai Viet Tone Mai Ek - {0x0aac1, 0x0aac1}, // Tai Viet Tone Mai Tho ..Tai Viet Tone Mai Tho - {0x0aaec, 0x0aaed}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign - {0x0aaf6, 0x0aaf6}, // Meetei Mayek Virama ..Meetei Mayek Virama - {0x0abe5, 0x0abe5}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign - {0x0abe8, 0x0abe8}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign - {0x0abed, 0x0abed}, // Meetei Mayek Apun Iyek ..Meetei Mayek Apun Iyek - {0x0fb1e, 0x0fb1e}, // Hebrew Point Judeo-spani..Hebrew Point Judeo-spani - {0x0fe00, 0x0fe0f}, // Variation Selector-1 ..Variation Selector-16 - {0x0fe20, 0x0fe2f}, // Combining Ligature Left ..Combining Cyrillic Titlo - {0x101fd, 0x101fd}, // Phaistos Disc Sign Combi..Phaistos Disc Sign Combi - {0x102e0, 0x102e0}, // Coptic Epact Thousands M..Coptic Epact Thousands M - {0x10376, 0x1037a}, // Combining Old Permic Let..Combining Old Permic Let - {0x10a01, 0x10a03}, // Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo - {0x10a05, 0x10a06}, // Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O - {0x10a0c, 0x10a0f}, // Kharoshthi Vowel Length ..Kharoshthi Sign Visarga - {0x10a38, 0x10a3a}, // Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo - {0x10a3f, 0x10a3f}, // Kharoshthi Virama ..Kharoshthi Virama - {0x10ae5, 0x10ae6}, // Manichaean Abbreviation ..Manichaean Abbreviation - {0x10d24, 0x10d27}, // Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas - {0x10eab, 0x10eac}, // (nil) ..(nil) - {0x10f46, 0x10f50}, // Sogdian Combining Dot Be..Sogdian Combining Stroke - {0x11001, 0x11001}, // Brahmi Sign Anusvara ..Brahmi Sign Anusvara - {0x11038, 0x11046}, // Brahmi Vowel Sign Aa ..Brahmi Virama - {0x1107f, 0x11081}, // Brahmi Number Joiner ..Kaithi Sign Anusvara - {0x110b3, 0x110b6}, // Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai - {0x110b9, 0x110ba}, // Kaithi Sign Virama ..Kaithi Sign Nukta - {0x11100, 0x11102}, // Chakma Sign Candrabindu ..Chakma Sign Visarga - {0x11127, 0x1112b}, // Chakma Vowel Sign A ..Chakma Vowel Sign Uu - {0x1112d, 0x11134}, // Chakma Vowel Sign Ai ..Chakma Maayyaa - {0x11173, 0x11173}, // Mahajani Sign Nukta ..Mahajani Sign Nukta - {0x11180, 0x11181}, // Sharada Sign Candrabindu..Sharada Sign Anusvara - {0x111b6, 0x111be}, // Sharada Vowel Sign U ..Sharada Vowel Sign O - {0x111c9, 0x111cc}, // Sharada Sandhi Mark ..Sharada Extra Short Vowe - {0x111cf, 0x111cf}, // (nil) ..(nil) - {0x1122f, 0x11231}, // Khojki Vowel Sign U ..Khojki Vowel Sign Ai - {0x11234, 0x11234}, // Khojki Sign Anusvara ..Khojki Sign Anusvara - {0x11236, 0x11237}, // Khojki Sign Nukta ..Khojki Sign Shadda - {0x1123e, 0x1123e}, // Khojki Sign Sukun ..Khojki Sign Sukun - {0x112df, 0x112df}, // Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara - {0x112e3, 0x112ea}, // Khudawadi Vowel Sign U ..Khudawadi Sign Virama - {0x11300, 0x11301}, // Grantha Sign Combining A..Grantha Sign Candrabindu - {0x1133b, 0x1133c}, // Combining Bindu Below ..Grantha Sign Nukta - {0x11340, 0x11340}, // Grantha Vowel Sign Ii ..Grantha Vowel Sign Ii - {0x11366, 0x1136c}, // Combining Grantha Digit ..Combining Grantha Digit - {0x11370, 0x11374}, // Combining Grantha Letter..Combining Grantha Letter - {0x11438, 0x1143f}, // Newa Vowel Sign U ..Newa Vowel Sign Ai - {0x11442, 0x11444}, // Newa Sign Virama ..Newa Sign Anusvara - {0x11446, 0x11446}, // Newa Sign Nukta ..Newa Sign Nukta - {0x1145e, 0x1145e}, // Newa Sandhi Mark ..Newa Sandhi Mark - {0x114b3, 0x114b8}, // Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal - {0x114ba, 0x114ba}, // Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short - {0x114bf, 0x114c0}, // Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara - {0x114c2, 0x114c3}, // Tirhuta Sign Virama ..Tirhuta Sign Nukta - {0x115b2, 0x115b5}, // Siddham Vowel Sign U ..Siddham Vowel Sign Vocal - {0x115bc, 0x115bd}, // Siddham Sign Candrabindu..Siddham Sign Anusvara - {0x115bf, 0x115c0}, // Siddham Sign Virama ..Siddham Sign Nukta - {0x115dc, 0x115dd}, // Siddham Vowel Sign Alter..Siddham Vowel Sign Alter - {0x11633, 0x1163a}, // Modi Vowel Sign U ..Modi Vowel Sign Ai - {0x1163d, 0x1163d}, // Modi Sign Anusvara ..Modi Sign Anusvara - {0x1163f, 0x11640}, // Modi Sign Virama ..Modi Sign Ardhacandra - {0x116ab, 0x116ab}, // Takri Sign Anusvara ..Takri Sign Anusvara - {0x116ad, 0x116ad}, // Takri Vowel Sign Aa ..Takri Vowel Sign Aa - {0x116b0, 0x116b5}, // Takri Vowel Sign U ..Takri Vowel Sign Au - {0x116b7, 0x116b7}, // Takri Sign Nukta ..Takri Sign Nukta - {0x1171d, 0x1171f}, // Ahom Consonant Sign Medi..Ahom Consonant Sign Medi - {0x11722, 0x11725}, // Ahom Vowel Sign I ..Ahom Vowel Sign Uu - {0x11727, 0x1172b}, // Ahom Vowel Sign Aw ..Ahom Sign Killer - {0x1182f, 0x11837}, // Dogra Vowel Sign U ..Dogra Sign Anusvara - {0x11839, 0x1183a}, // Dogra Sign Virama ..Dogra Sign Nukta - {0x1193b, 0x1193c}, // (nil) ..(nil) - {0x1193e, 0x1193e}, // (nil) ..(nil) - {0x11943, 0x11943}, // (nil) ..(nil) - {0x119d4, 0x119d7}, // Nandinagari Vowel Sign U..Nandinagari Vowel Sign V - {0x119da, 0x119db}, // Nandinagari Vowel Sign E..Nandinagari Vowel Sign A - {0x119e0, 0x119e0}, // Nandinagari Sign Virama ..Nandinagari Sign Virama - {0x11a01, 0x11a0a}, // Zanabazar Square Vowel S..Zanabazar Square Vowel L - {0x11a33, 0x11a38}, // Zanabazar Square Final C..Zanabazar Square Sign An - {0x11a3b, 0x11a3e}, // Zanabazar Square Cluster..Zanabazar Square Cluster - {0x11a47, 0x11a47}, // Zanabazar Square Subjoin..Zanabazar Square Subjoin - {0x11a51, 0x11a56}, // Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe - {0x11a59, 0x11a5b}, // Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar - {0x11a8a, 0x11a96}, // Soyombo Final Consonant ..Soyombo Sign Anusvara - {0x11a98, 0x11a99}, // Soyombo Gemination Mark ..Soyombo Subjoiner - {0x11c30, 0x11c36}, // Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc - {0x11c38, 0x11c3d}, // Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara - {0x11c3f, 0x11c3f}, // Bhaiksuki Sign Virama ..Bhaiksuki Sign Virama - {0x11c92, 0x11ca7}, // Marchen Subjoined Letter..Marchen Subjoined Letter - {0x11caa, 0x11cb0}, // Marchen Subjoined Letter..Marchen Vowel Sign Aa - {0x11cb2, 0x11cb3}, // Marchen Vowel Sign U ..Marchen Vowel Sign E - {0x11cb5, 0x11cb6}, // Marchen Sign Anusvara ..Marchen Sign Candrabindu - {0x11d31, 0x11d36}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign - {0x11d3a, 0x11d3a}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign - {0x11d3c, 0x11d3d}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign - {0x11d3f, 0x11d45}, // Masaram Gondi Vowel Sign..Masaram Gondi Virama - {0x11d47, 0x11d47}, // Masaram Gondi Ra-kara ..Masaram Gondi Ra-kara - {0x11d90, 0x11d91}, // Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign - {0x11d95, 0x11d95}, // Gunjala Gondi Sign Anusv..Gunjala Gondi Sign Anusv - {0x11d97, 0x11d97}, // Gunjala Gondi Virama ..Gunjala Gondi Virama - {0x11ef3, 0x11ef4}, // Makasar Vowel Sign I ..Makasar Vowel Sign U - {0x16af0, 0x16af4}, // Bassa Vah Combining High..Bassa Vah Combining High - {0x16b30, 0x16b36}, // Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta - {0x16f4f, 0x16f4f}, // Miao Sign Consonant Modi..Miao Sign Consonant Modi - {0x16f8f, 0x16f92}, // Miao Tone Right ..Miao Tone Below - {0x16fe4, 0x16fe4}, // (nil) ..(nil) - {0x1bc9d, 0x1bc9e}, // Duployan Thick Letter Se..Duployan Double Mark - {0x1d167, 0x1d169}, // Musical Symbol Combining..Musical Symbol Combining - {0x1d17b, 0x1d182}, // Musical Symbol Combining..Musical Symbol Combining - {0x1d185, 0x1d18b}, // Musical Symbol Combining..Musical Symbol Combining - {0x1d1aa, 0x1d1ad}, // Musical Symbol Combining..Musical Symbol Combining - {0x1d242, 0x1d244}, // Combining Greek Musical ..Combining Greek Musical - {0x1da00, 0x1da36}, // Signwriting Head Rim ..Signwriting Air Sucking - {0x1da3b, 0x1da6c}, // Signwriting Mouth Closed..Signwriting Excitement - {0x1da75, 0x1da75}, // Signwriting Upper Body T..Signwriting Upper Body T - {0x1da84, 0x1da84}, // Signwriting Location Hea..Signwriting Location Hea - {0x1da9b, 0x1da9f}, // Signwriting Fill Modifie..Signwriting Fill Modifie - {0x1daa1, 0x1daaf}, // Signwriting Rotation Mod..Signwriting Rotation Mod - {0x1e000, 0x1e006}, // Combining Glagolitic Let..Combining Glagolitic Let - {0x1e008, 0x1e018}, // Combining Glagolitic Let..Combining Glagolitic Let - {0x1e01b, 0x1e021}, // Combining Glagolitic Let..Combining Glagolitic Let - {0x1e023, 0x1e024}, // Combining Glagolitic Let..Combining Glagolitic Let - {0x1e026, 0x1e02a}, // Combining Glagolitic Let..Combining Glagolitic Let - {0x1e130, 0x1e136}, // Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T - {0x1e2ec, 0x1e2ef}, // Wancho Tone Tup ..Wancho Tone Koini - {0x1e8d0, 0x1e8d6}, // Mende Kikakui Combining ..Mende Kikakui Combining - {0x1e944, 0x1e94a}, // Adlam Alif Lengthener ..Adlam Nukta - {0xe0100, 0xe01ef}, // Variation Selector-17 ..Variation Selector-256 + {0x00300, 0x0036f}, // Combining Grave Accent ..Combining Latin Small Le + {0x00483, 0x00489}, // Combining Cyrillic Titlo..Combining Cyrillic Milli + {0x00591, 0x005bd}, // Hebrew Accent Etnahta ..Hebrew Point Meteg + {0x005bf, 0x005bf}, // Hebrew Point Rafe ..Hebrew Point Rafe + {0x005c1, 0x005c2}, // Hebrew Point Shin Dot ..Hebrew Point Sin Dot + {0x005c4, 0x005c5}, // Hebrew Mark Upper Dot ..Hebrew Mark Lower Dot + {0x005c7, 0x005c7}, // Hebrew Point Qamats Qata..Hebrew Point Qamats Qata + {0x00610, 0x0061a}, // Arabic Sign Sallallahou ..Arabic Small Kasra + {0x0064b, 0x0065f}, // Arabic Fathatan ..Arabic Wavy Hamza Below + {0x00670, 0x00670}, // Arabic Letter Superscrip..Arabic Letter Superscrip + {0x006d6, 0x006dc}, // Arabic Small High Ligatu..Arabic Small High Seen + {0x006df, 0x006e4}, // Arabic Small High Rounde..Arabic Small High Madda + {0x006e7, 0x006e8}, // Arabic Small High Yeh ..Arabic Small High Noon + {0x006ea, 0x006ed}, // Arabic Empty Centre Low ..Arabic Small Low Meem + {0x00711, 0x00711}, // Syriac Letter Superscrip..Syriac Letter Superscrip + {0x00730, 0x0074a}, // Syriac Pthaha Above ..Syriac Barrekh + {0x007a6, 0x007b0}, // Thaana Abafili ..Thaana Sukun + {0x007eb, 0x007f3}, // Nko Combining Short High..Nko Combining Double Dot + {0x007fd, 0x007fd}, // Nko Dantayalan ..Nko Dantayalan + {0x00816, 0x00819}, // Samaritan Mark In ..Samaritan Mark Dagesh + {0x0081b, 0x00823}, // Samaritan Mark Epentheti..Samaritan Vowel Sign A + {0x00825, 0x00827}, // Samaritan Vowel Sign Sho..Samaritan Vowel Sign U + {0x00829, 0x0082d}, // Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa + {0x00859, 0x0085b}, // Mandaic Affrication Mark..Mandaic Gemination Mark + {0x008d3, 0x008e1}, // Arabic Small Low Waw ..Arabic Small High Sign S + {0x008e3, 0x00902}, // Arabic Turned Damma Belo..Devanagari Sign Anusvara + {0x0093a, 0x0093a}, // Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe + {0x0093c, 0x0093c}, // Devanagari Sign Nukta ..Devanagari Sign Nukta + {0x00941, 0x00948}, // Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai + {0x0094d, 0x0094d}, // Devanagari Sign Virama ..Devanagari Sign Virama + {0x00951, 0x00957}, // Devanagari Stress Sign U..Devanagari Vowel Sign Uu + {0x00962, 0x00963}, // Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo + {0x00981, 0x00981}, // Bengali Sign Candrabindu..Bengali Sign Candrabindu + {0x009bc, 0x009bc}, // Bengali Sign Nukta ..Bengali Sign Nukta + {0x009c1, 0x009c4}, // Bengali Vowel Sign U ..Bengali Vowel Sign Vocal + {0x009cd, 0x009cd}, // Bengali Sign Virama ..Bengali Sign Virama + {0x009e2, 0x009e3}, // Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal + {0x009fe, 0x009fe}, // Bengali Sandhi Mark ..Bengali Sandhi Mark + {0x00a01, 0x00a02}, // Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi + {0x00a3c, 0x00a3c}, // Gurmukhi Sign Nukta ..Gurmukhi Sign Nukta + {0x00a41, 0x00a42}, // Gurmukhi Vowel Sign U ..Gurmukhi Vowel Sign Uu + {0x00a47, 0x00a48}, // Gurmukhi Vowel Sign Ee ..Gurmukhi Vowel Sign Ai + {0x00a4b, 0x00a4d}, // Gurmukhi Vowel Sign Oo ..Gurmukhi Sign Virama + {0x00a51, 0x00a51}, // Gurmukhi Sign Udaat ..Gurmukhi Sign Udaat + {0x00a70, 0x00a71}, // Gurmukhi Tippi ..Gurmukhi Addak + {0x00a75, 0x00a75}, // Gurmukhi Sign Yakash ..Gurmukhi Sign Yakash + {0x00a81, 0x00a82}, // Gujarati Sign Candrabind..Gujarati Sign Anusvara + {0x00abc, 0x00abc}, // Gujarati Sign Nukta ..Gujarati Sign Nukta + {0x00ac1, 0x00ac5}, // Gujarati Vowel Sign U ..Gujarati Vowel Sign Cand + {0x00ac7, 0x00ac8}, // Gujarati Vowel Sign E ..Gujarati Vowel Sign Ai + {0x00acd, 0x00acd}, // Gujarati Sign Virama ..Gujarati Sign Virama + {0x00ae2, 0x00ae3}, // Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca + {0x00afa, 0x00aff}, // Gujarati Sign Sukun ..Gujarati Sign Two-circle + {0x00b01, 0x00b01}, // Oriya Sign Candrabindu ..Oriya Sign Candrabindu + {0x00b3c, 0x00b3c}, // Oriya Sign Nukta ..Oriya Sign Nukta + {0x00b3f, 0x00b3f}, // Oriya Vowel Sign I ..Oriya Vowel Sign I + {0x00b41, 0x00b44}, // Oriya Vowel Sign U ..Oriya Vowel Sign Vocalic + {0x00b4d, 0x00b4d}, // Oriya Sign Virama ..Oriya Sign Virama + {0x00b55, 0x00b56}, // (nil) ..Oriya Ai Length Mark + {0x00b62, 0x00b63}, // Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic + {0x00b82, 0x00b82}, // Tamil Sign Anusvara ..Tamil Sign Anusvara + {0x00bc0, 0x00bc0}, // Tamil Vowel Sign Ii ..Tamil Vowel Sign Ii + {0x00bcd, 0x00bcd}, // Tamil Sign Virama ..Tamil Sign Virama + {0x00c00, 0x00c00}, // Telugu Sign Combining Ca..Telugu Sign Combining Ca + {0x00c04, 0x00c04}, // Telugu Sign Combining An..Telugu Sign Combining An + {0x00c3e, 0x00c40}, // Telugu Vowel Sign Aa ..Telugu Vowel Sign Ii + {0x00c46, 0x00c48}, // Telugu Vowel Sign E ..Telugu Vowel Sign Ai + {0x00c4a, 0x00c4d}, // Telugu Vowel Sign O ..Telugu Sign Virama + {0x00c55, 0x00c56}, // Telugu Length Mark ..Telugu Ai Length Mark + {0x00c62, 0x00c63}, // Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali + {0x00c81, 0x00c81}, // Kannada Sign Candrabindu..Kannada Sign Candrabindu + {0x00cbc, 0x00cbc}, // Kannada Sign Nukta ..Kannada Sign Nukta + {0x00cbf, 0x00cbf}, // Kannada Vowel Sign I ..Kannada Vowel Sign I + {0x00cc6, 0x00cc6}, // Kannada Vowel Sign E ..Kannada Vowel Sign E + {0x00ccc, 0x00ccd}, // Kannada Vowel Sign Au ..Kannada Sign Virama + {0x00ce2, 0x00ce3}, // Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal + {0x00d00, 0x00d01}, // Malayalam Sign Combining..Malayalam Sign Candrabin + {0x00d3b, 0x00d3c}, // Malayalam Sign Vertical ..Malayalam Sign Circular + {0x00d41, 0x00d44}, // Malayalam Vowel Sign U ..Malayalam Vowel Sign Voc + {0x00d4d, 0x00d4d}, // Malayalam Sign Virama ..Malayalam Sign Virama + {0x00d62, 0x00d63}, // Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc + {0x00d81, 0x00d81}, // (nil) ..(nil) + {0x00dca, 0x00dca}, // Sinhala Sign Al-lakuna ..Sinhala Sign Al-lakuna + {0x00dd2, 0x00dd4}, // Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti + {0x00dd6, 0x00dd6}, // Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga + {0x00e31, 0x00e31}, // Thai Character Mai Han-a..Thai Character Mai Han-a + {0x00e34, 0x00e3a}, // Thai Character Sara I ..Thai Character Phinthu + {0x00e47, 0x00e4e}, // Thai Character Maitaikhu..Thai Character Yamakkan + {0x00eb1, 0x00eb1}, // Lao Vowel Sign Mai Kan ..Lao Vowel Sign Mai Kan + {0x00eb4, 0x00ebc}, // Lao Vowel Sign I ..Lao Semivowel Sign Lo + {0x00ec8, 0x00ecd}, // Lao Tone Mai Ek ..Lao Niggahita + {0x00f18, 0x00f19}, // Tibetan Astrological Sig..Tibetan Astrological Sig + {0x00f35, 0x00f35}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung + {0x00f37, 0x00f37}, // Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung + {0x00f39, 0x00f39}, // Tibetan Mark Tsa -phru ..Tibetan Mark Tsa -phru + {0x00f71, 0x00f7e}, // Tibetan Vowel Sign Aa ..Tibetan Sign Rjes Su Nga + {0x00f80, 0x00f84}, // Tibetan Vowel Sign Rever..Tibetan Mark Halanta + {0x00f86, 0x00f87}, // Tibetan Sign Lci Rtags ..Tibetan Sign Yang Rtags + {0x00f8d, 0x00f97}, // Tibetan Subjoined Sign L..Tibetan Subjoined Letter + {0x00f99, 0x00fbc}, // Tibetan Subjoined Letter..Tibetan Subjoined Letter + {0x00fc6, 0x00fc6}, // Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda + {0x0102d, 0x01030}, // Myanmar Vowel Sign I ..Myanmar Vowel Sign Uu + {0x01032, 0x01037}, // Myanmar Vowel Sign Ai ..Myanmar Sign Dot Below + {0x01039, 0x0103a}, // Myanmar Sign Virama ..Myanmar Sign Asat + {0x0103d, 0x0103e}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M + {0x01058, 0x01059}, // Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal + {0x0105e, 0x01060}, // Myanmar Consonant Sign M..Myanmar Consonant Sign M + {0x01071, 0x01074}, // Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah + {0x01082, 0x01082}, // Myanmar Consonant Sign S..Myanmar Consonant Sign S + {0x01085, 0x01086}, // Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan + {0x0108d, 0x0108d}, // Myanmar Sign Shan Counci..Myanmar Sign Shan Counci + {0x0109d, 0x0109d}, // Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton + {0x0135d, 0x0135f}, // Ethiopic Combining Gemin..Ethiopic Combining Gemin + {0x01712, 0x01714}, // Tagalog Vowel Sign I ..Tagalog Sign Virama + {0x01732, 0x01734}, // Hanunoo Vowel Sign I ..Hanunoo Sign Pamudpod + {0x01752, 0x01753}, // Buhid Vowel Sign I ..Buhid Vowel Sign U + {0x01772, 0x01773}, // Tagbanwa Vowel Sign I ..Tagbanwa Vowel Sign U + {0x017b4, 0x017b5}, // Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa + {0x017b7, 0x017bd}, // Khmer Vowel Sign I ..Khmer Vowel Sign Ua + {0x017c6, 0x017c6}, // Khmer Sign Nikahit ..Khmer Sign Nikahit + {0x017c9, 0x017d3}, // Khmer Sign Muusikatoan ..Khmer Sign Bathamasat + {0x017dd, 0x017dd}, // Khmer Sign Atthacan ..Khmer Sign Atthacan + {0x0180b, 0x0180d}, // Mongolian Free Variation..Mongolian Free Variation + {0x01885, 0x01886}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal + {0x018a9, 0x018a9}, // Mongolian Letter Ali Gal..Mongolian Letter Ali Gal + {0x01920, 0x01922}, // Limbu Vowel Sign A ..Limbu Vowel Sign U + {0x01927, 0x01928}, // Limbu Vowel Sign E ..Limbu Vowel Sign O + {0x01932, 0x01932}, // Limbu Small Letter Anusv..Limbu Small Letter Anusv + {0x01939, 0x0193b}, // Limbu Sign Mukphreng ..Limbu Sign Sa-i + {0x01a17, 0x01a18}, // Buginese Vowel Sign I ..Buginese Vowel Sign U + {0x01a1b, 0x01a1b}, // Buginese Vowel Sign Ae ..Buginese Vowel Sign Ae + {0x01a56, 0x01a56}, // Tai Tham Consonant Sign ..Tai Tham Consonant Sign + {0x01a58, 0x01a5e}, // Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign + {0x01a60, 0x01a60}, // Tai Tham Sign Sakot ..Tai Tham Sign Sakot + {0x01a62, 0x01a62}, // Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai + {0x01a65, 0x01a6c}, // Tai Tham Vowel Sign I ..Tai Tham Vowel Sign Oa B + {0x01a73, 0x01a7c}, // Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue + {0x01a7f, 0x01a7f}, // Tai Tham Combining Crypt..Tai Tham Combining Crypt + {0x01ab0, 0x01ac0}, // Combining Doubled Circum..(nil) + {0x01b00, 0x01b03}, // Balinese Sign Ulu Ricem ..Balinese Sign Surang + {0x01b34, 0x01b34}, // Balinese Sign Rerekan ..Balinese Sign Rerekan + {0x01b36, 0x01b3a}, // Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R + {0x01b3c, 0x01b3c}, // Balinese Vowel Sign La L..Balinese Vowel Sign La L + {0x01b42, 0x01b42}, // Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe + {0x01b6b, 0x01b73}, // Balinese Musical Symbol ..Balinese Musical Symbol + {0x01b80, 0x01b81}, // Sundanese Sign Panyecek ..Sundanese Sign Panglayar + {0x01ba2, 0x01ba5}, // Sundanese Consonant Sign..Sundanese Vowel Sign Pan + {0x01ba8, 0x01ba9}, // Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan + {0x01bab, 0x01bad}, // Sundanese Sign Virama ..Sundanese Consonant Sign + {0x01be6, 0x01be6}, // Batak Sign Tompi ..Batak Sign Tompi + {0x01be8, 0x01be9}, // Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee + {0x01bed, 0x01bed}, // Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O + {0x01bef, 0x01bf1}, // Batak Vowel Sign U For S..Batak Consonant Sign H + {0x01c2c, 0x01c33}, // Lepcha Vowel Sign E ..Lepcha Consonant Sign T + {0x01c36, 0x01c37}, // Lepcha Sign Ran ..Lepcha Sign Nukta + {0x01cd0, 0x01cd2}, // Vedic Tone Karshana ..Vedic Tone Prenkha + {0x01cd4, 0x01ce0}, // Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash + {0x01ce2, 0x01ce8}, // Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda + {0x01ced, 0x01ced}, // Vedic Sign Tiryak ..Vedic Sign Tiryak + {0x01cf4, 0x01cf4}, // Vedic Tone Candra Above ..Vedic Tone Candra Above + {0x01cf8, 0x01cf9}, // Vedic Tone Ring Above ..Vedic Tone Double Ring A + {0x01dc0, 0x01df9}, // Combining Dotted Grave A..Combining Wide Inverted + {0x01dfb, 0x01dff}, // Combining Deletion Mark ..Combining Right Arrowhea + {0x020d0, 0x020f0}, // Combining Left Harpoon A..Combining Asterisk Above + {0x02cef, 0x02cf1}, // Coptic Combining Ni Abov..Coptic Combining Spiritu + {0x02d7f, 0x02d7f}, // Tifinagh Consonant Joine..Tifinagh Consonant Joine + {0x02de0, 0x02dff}, // Combining Cyrillic Lette..Combining Cyrillic Lette + {0x0302a, 0x0302d}, // Ideographic Level Tone M..Ideographic Entering Ton + {0x03099, 0x0309a}, // Combining Katakana-hirag..Combining Katakana-hirag + {0x0a66f, 0x0a672}, // Combining Cyrillic Vzmet..Combining Cyrillic Thous + {0x0a674, 0x0a67d}, // Combining Cyrillic Lette..Combining Cyrillic Payer + {0x0a69e, 0x0a69f}, // Combining Cyrillic Lette..Combining Cyrillic Lette + {0x0a6f0, 0x0a6f1}, // Bamum Combining Mark Koq..Bamum Combining Mark Tuk + {0x0a802, 0x0a802}, // Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva + {0x0a806, 0x0a806}, // Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant + {0x0a80b, 0x0a80b}, // Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva + {0x0a825, 0x0a826}, // Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign + {0x0a82c, 0x0a82c}, // (nil) ..(nil) + {0x0a8c4, 0x0a8c5}, // Saurashtra Sign Virama ..Saurashtra Sign Candrabi + {0x0a8e0, 0x0a8f1}, // Combining Devanagari Dig..Combining Devanagari Sig + {0x0a8ff, 0x0a8ff}, // Devanagari Vowel Sign Ay..Devanagari Vowel Sign Ay + {0x0a926, 0x0a92d}, // Kayah Li Vowel Ue ..Kayah Li Tone Calya Plop + {0x0a947, 0x0a951}, // Rejang Vowel Sign I ..Rejang Consonant Sign R + {0x0a980, 0x0a982}, // Javanese Sign Panyangga ..Javanese Sign Layar + {0x0a9b3, 0x0a9b3}, // Javanese Sign Cecak Telu..Javanese Sign Cecak Telu + {0x0a9b6, 0x0a9b9}, // Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku + {0x0a9bc, 0x0a9bd}, // Javanese Vowel Sign Pepe..Javanese Consonant Sign + {0x0a9e5, 0x0a9e5}, // Myanmar Sign Shan Saw ..Myanmar Sign Shan Saw + {0x0aa29, 0x0aa2e}, // Cham Vowel Sign Aa ..Cham Vowel Sign Oe + {0x0aa31, 0x0aa32}, // Cham Vowel Sign Au ..Cham Vowel Sign Ue + {0x0aa35, 0x0aa36}, // Cham Consonant Sign La ..Cham Consonant Sign Wa + {0x0aa43, 0x0aa43}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina + {0x0aa4c, 0x0aa4c}, // Cham Consonant Sign Fina..Cham Consonant Sign Fina + {0x0aa7c, 0x0aa7c}, // Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T + {0x0aab0, 0x0aab0}, // Tai Viet Mai Kang ..Tai Viet Mai Kang + {0x0aab2, 0x0aab4}, // Tai Viet Vowel I ..Tai Viet Vowel U + {0x0aab7, 0x0aab8}, // Tai Viet Mai Khit ..Tai Viet Vowel Ia + {0x0aabe, 0x0aabf}, // Tai Viet Vowel Am ..Tai Viet Tone Mai Ek + {0x0aac1, 0x0aac1}, // Tai Viet Tone Mai Tho ..Tai Viet Tone Mai Tho + {0x0aaec, 0x0aaed}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + {0x0aaf6, 0x0aaf6}, // Meetei Mayek Virama ..Meetei Mayek Virama + {0x0abe5, 0x0abe5}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + {0x0abe8, 0x0abe8}, // Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign + {0x0abed, 0x0abed}, // Meetei Mayek Apun Iyek ..Meetei Mayek Apun Iyek + {0x0fb1e, 0x0fb1e}, // Hebrew Point Judeo-spani..Hebrew Point Judeo-spani + {0x0fe00, 0x0fe0f}, // Variation Selector-1 ..Variation Selector-16 + {0x0fe20, 0x0fe2f}, // Combining Ligature Left ..Combining Cyrillic Titlo + {0x101fd, 0x101fd}, // Phaistos Disc Sign Combi..Phaistos Disc Sign Combi + {0x102e0, 0x102e0}, // Coptic Epact Thousands M..Coptic Epact Thousands M + {0x10376, 0x1037a}, // Combining Old Permic Let..Combining Old Permic Let + {0x10a01, 0x10a03}, // Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo + {0x10a05, 0x10a06}, // Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O + {0x10a0c, 0x10a0f}, // Kharoshthi Vowel Length ..Kharoshthi Sign Visarga + {0x10a38, 0x10a3a}, // Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo + {0x10a3f, 0x10a3f}, // Kharoshthi Virama ..Kharoshthi Virama + {0x10ae5, 0x10ae6}, // Manichaean Abbreviation ..Manichaean Abbreviation + {0x10d24, 0x10d27}, // Hanifi Rohingya Sign Har..Hanifi Rohingya Sign Tas + {0x10eab, 0x10eac}, // (nil) ..(nil) + {0x10f46, 0x10f50}, // Sogdian Combining Dot Be..Sogdian Combining Stroke + {0x11001, 0x11001}, // Brahmi Sign Anusvara ..Brahmi Sign Anusvara + {0x11038, 0x11046}, // Brahmi Vowel Sign Aa ..Brahmi Virama + {0x1107f, 0x11081}, // Brahmi Number Joiner ..Kaithi Sign Anusvara + {0x110b3, 0x110b6}, // Kaithi Vowel Sign U ..Kaithi Vowel Sign Ai + {0x110b9, 0x110ba}, // Kaithi Sign Virama ..Kaithi Sign Nukta + {0x11100, 0x11102}, // Chakma Sign Candrabindu ..Chakma Sign Visarga + {0x11127, 0x1112b}, // Chakma Vowel Sign A ..Chakma Vowel Sign Uu + {0x1112d, 0x11134}, // Chakma Vowel Sign Ai ..Chakma Maayyaa + {0x11173, 0x11173}, // Mahajani Sign Nukta ..Mahajani Sign Nukta + {0x11180, 0x11181}, // Sharada Sign Candrabindu..Sharada Sign Anusvara + {0x111b6, 0x111be}, // Sharada Vowel Sign U ..Sharada Vowel Sign O + {0x111c9, 0x111cc}, // Sharada Sandhi Mark ..Sharada Extra Short Vowe + {0x111cf, 0x111cf}, // (nil) ..(nil) + {0x1122f, 0x11231}, // Khojki Vowel Sign U ..Khojki Vowel Sign Ai + {0x11234, 0x11234}, // Khojki Sign Anusvara ..Khojki Sign Anusvara + {0x11236, 0x11237}, // Khojki Sign Nukta ..Khojki Sign Shadda + {0x1123e, 0x1123e}, // Khojki Sign Sukun ..Khojki Sign Sukun + {0x112df, 0x112df}, // Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara + {0x112e3, 0x112ea}, // Khudawadi Vowel Sign U ..Khudawadi Sign Virama + {0x11300, 0x11301}, // Grantha Sign Combining A..Grantha Sign Candrabindu + {0x1133b, 0x1133c}, // Combining Bindu Below ..Grantha Sign Nukta + {0x11340, 0x11340}, // Grantha Vowel Sign Ii ..Grantha Vowel Sign Ii + {0x11366, 0x1136c}, // Combining Grantha Digit ..Combining Grantha Digit + {0x11370, 0x11374}, // Combining Grantha Letter..Combining Grantha Letter + {0x11438, 0x1143f}, // Newa Vowel Sign U ..Newa Vowel Sign Ai + {0x11442, 0x11444}, // Newa Sign Virama ..Newa Sign Anusvara + {0x11446, 0x11446}, // Newa Sign Nukta ..Newa Sign Nukta + {0x1145e, 0x1145e}, // Newa Sandhi Mark ..Newa Sandhi Mark + {0x114b3, 0x114b8}, // Tirhuta Vowel Sign U ..Tirhuta Vowel Sign Vocal + {0x114ba, 0x114ba}, // Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short + {0x114bf, 0x114c0}, // Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara + {0x114c2, 0x114c3}, // Tirhuta Sign Virama ..Tirhuta Sign Nukta + {0x115b2, 0x115b5}, // Siddham Vowel Sign U ..Siddham Vowel Sign Vocal + {0x115bc, 0x115bd}, // Siddham Sign Candrabindu..Siddham Sign Anusvara + {0x115bf, 0x115c0}, // Siddham Sign Virama ..Siddham Sign Nukta + {0x115dc, 0x115dd}, // Siddham Vowel Sign Alter..Siddham Vowel Sign Alter + {0x11633, 0x1163a}, // Modi Vowel Sign U ..Modi Vowel Sign Ai + {0x1163d, 0x1163d}, // Modi Sign Anusvara ..Modi Sign Anusvara + {0x1163f, 0x11640}, // Modi Sign Virama ..Modi Sign Ardhacandra + {0x116ab, 0x116ab}, // Takri Sign Anusvara ..Takri Sign Anusvara + {0x116ad, 0x116ad}, // Takri Vowel Sign Aa ..Takri Vowel Sign Aa + {0x116b0, 0x116b5}, // Takri Vowel Sign U ..Takri Vowel Sign Au + {0x116b7, 0x116b7}, // Takri Sign Nukta ..Takri Sign Nukta + {0x1171d, 0x1171f}, // Ahom Consonant Sign Medi..Ahom Consonant Sign Medi + {0x11722, 0x11725}, // Ahom Vowel Sign I ..Ahom Vowel Sign Uu + {0x11727, 0x1172b}, // Ahom Vowel Sign Aw ..Ahom Sign Killer + {0x1182f, 0x11837}, // Dogra Vowel Sign U ..Dogra Sign Anusvara + {0x11839, 0x1183a}, // Dogra Sign Virama ..Dogra Sign Nukta + {0x1193b, 0x1193c}, // (nil) ..(nil) + {0x1193e, 0x1193e}, // (nil) ..(nil) + {0x11943, 0x11943}, // (nil) ..(nil) + {0x119d4, 0x119d7}, // Nandinagari Vowel Sign U..Nandinagari Vowel Sign V + {0x119da, 0x119db}, // Nandinagari Vowel Sign E..Nandinagari Vowel Sign A + {0x119e0, 0x119e0}, // Nandinagari Sign Virama ..Nandinagari Sign Virama + {0x11a01, 0x11a0a}, // Zanabazar Square Vowel S..Zanabazar Square Vowel L + {0x11a33, 0x11a38}, // Zanabazar Square Final C..Zanabazar Square Sign An + {0x11a3b, 0x11a3e}, // Zanabazar Square Cluster..Zanabazar Square Cluster + {0x11a47, 0x11a47}, // Zanabazar Square Subjoin..Zanabazar Square Subjoin + {0x11a51, 0x11a56}, // Soyombo Vowel Sign I ..Soyombo Vowel Sign Oe + {0x11a59, 0x11a5b}, // Soyombo Vowel Sign Vocal..Soyombo Vowel Length Mar + {0x11a8a, 0x11a96}, // Soyombo Final Consonant ..Soyombo Sign Anusvara + {0x11a98, 0x11a99}, // Soyombo Gemination Mark ..Soyombo Subjoiner + {0x11c30, 0x11c36}, // Bhaiksuki Vowel Sign I ..Bhaiksuki Vowel Sign Voc + {0x11c38, 0x11c3d}, // Bhaiksuki Vowel Sign E ..Bhaiksuki Sign Anusvara + {0x11c3f, 0x11c3f}, // Bhaiksuki Sign Virama ..Bhaiksuki Sign Virama + {0x11c92, 0x11ca7}, // Marchen Subjoined Letter..Marchen Subjoined Letter + {0x11caa, 0x11cb0}, // Marchen Subjoined Letter..Marchen Vowel Sign Aa + {0x11cb2, 0x11cb3}, // Marchen Vowel Sign U ..Marchen Vowel Sign E + {0x11cb5, 0x11cb6}, // Marchen Sign Anusvara ..Marchen Sign Candrabindu + {0x11d31, 0x11d36}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + {0x11d3a, 0x11d3a}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + {0x11d3c, 0x11d3d}, // Masaram Gondi Vowel Sign..Masaram Gondi Vowel Sign + {0x11d3f, 0x11d45}, // Masaram Gondi Vowel Sign..Masaram Gondi Virama + {0x11d47, 0x11d47}, // Masaram Gondi Ra-kara ..Masaram Gondi Ra-kara + {0x11d90, 0x11d91}, // Gunjala Gondi Vowel Sign..Gunjala Gondi Vowel Sign + {0x11d95, 0x11d95}, // Gunjala Gondi Sign Anusv..Gunjala Gondi Sign Anusv + {0x11d97, 0x11d97}, // Gunjala Gondi Virama ..Gunjala Gondi Virama + {0x11ef3, 0x11ef4}, // Makasar Vowel Sign I ..Makasar Vowel Sign U + {0x16af0, 0x16af4}, // Bassa Vah Combining High..Bassa Vah Combining High + {0x16b30, 0x16b36}, // Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta + {0x16f4f, 0x16f4f}, // Miao Sign Consonant Modi..Miao Sign Consonant Modi + {0x16f8f, 0x16f92}, // Miao Tone Right ..Miao Tone Below + {0x16fe4, 0x16fe4}, // (nil) ..(nil) + {0x1bc9d, 0x1bc9e}, // Duployan Thick Letter Se..Duployan Double Mark + {0x1d167, 0x1d169}, // Musical Symbol Combining..Musical Symbol Combining + {0x1d17b, 0x1d182}, // Musical Symbol Combining..Musical Symbol Combining + {0x1d185, 0x1d18b}, // Musical Symbol Combining..Musical Symbol Combining + {0x1d1aa, 0x1d1ad}, // Musical Symbol Combining..Musical Symbol Combining + {0x1d242, 0x1d244}, // Combining Greek Musical ..Combining Greek Musical + {0x1da00, 0x1da36}, // Signwriting Head Rim ..Signwriting Air Sucking + {0x1da3b, 0x1da6c}, // Signwriting Mouth Closed..Signwriting Excitement + {0x1da75, 0x1da75}, // Signwriting Upper Body T..Signwriting Upper Body T + {0x1da84, 0x1da84}, // Signwriting Location Hea..Signwriting Location Hea + {0x1da9b, 0x1da9f}, // Signwriting Fill Modifie..Signwriting Fill Modifie + {0x1daa1, 0x1daaf}, // Signwriting Rotation Mod..Signwriting Rotation Mod + {0x1e000, 0x1e006}, // Combining Glagolitic Let..Combining Glagolitic Let + {0x1e008, 0x1e018}, // Combining Glagolitic Let..Combining Glagolitic Let + {0x1e01b, 0x1e021}, // Combining Glagolitic Let..Combining Glagolitic Let + {0x1e023, 0x1e024}, // Combining Glagolitic Let..Combining Glagolitic Let + {0x1e026, 0x1e02a}, // Combining Glagolitic Let..Combining Glagolitic Let + {0x1e130, 0x1e136}, // Nyiakeng Puachue Hmong T..Nyiakeng Puachue Hmong T + {0x1e2ec, 0x1e2ef}, // Wancho Tone Tup ..Wancho Tone Koini + {0x1e8d0, 0x1e8d6}, // Mende Kikakui Combining ..Mende Kikakui Combining + {0x1e944, 0x1e94a}, // Adlam Alif Lengthener ..Adlam Nukta + {0xe0100, 0xe01ef}, // Variation Selector-17 ..Variation Selector-256 }; // https://github.com/jquast/wcwidth/blob/master/wcwidth/table_wide.py // at commit b29897e5a1b403a0e36f7fc991614981cbc42475 (2020-07-14): struct width_interval WIDE_EASTASIAN[] = { - {0x01100, 0x0115f}, // Hangul Choseong Kiyeok ..Hangul Choseong Filler - {0x0231a, 0x0231b}, // Watch ..Hourglass - {0x02329, 0x0232a}, // Left-pointing Angle Brac..Right-pointing Angle Bra - {0x023e9, 0x023ec}, // Black Right-pointing Dou..Black Down-pointing Doub - {0x023f0, 0x023f0}, // Alarm Clock ..Alarm Clock - {0x023f3, 0x023f3}, // Hourglass With Flowing S..Hourglass With Flowing S - {0x025fd, 0x025fe}, // White Medium Small Squar..Black Medium Small Squar - {0x02614, 0x02615}, // Umbrella With Rain Drops..Hot Beverage - {0x02648, 0x02653}, // Aries ..Pisces - {0x0267f, 0x0267f}, // Wheelchair Symbol ..Wheelchair Symbol - {0x02693, 0x02693}, // Anchor ..Anchor - {0x026a1, 0x026a1}, // High Voltage Sign ..High Voltage Sign - {0x026aa, 0x026ab}, // Medium White Circle ..Medium Black Circle - {0x026bd, 0x026be}, // Soccer Ball ..Baseball - {0x026c4, 0x026c5}, // Snowman Without Snow ..Sun Behind Cloud - {0x026ce, 0x026ce}, // Ophiuchus ..Ophiuchus - {0x026d4, 0x026d4}, // No Entry ..No Entry - {0x026ea, 0x026ea}, // Church ..Church - {0x026f2, 0x026f3}, // Fountain ..Flag In Hole - {0x026f5, 0x026f5}, // Sailboat ..Sailboat - {0x026fa, 0x026fa}, // Tent ..Tent - {0x026fd, 0x026fd}, // Fuel Pump ..Fuel Pump - {0x02705, 0x02705}, // White Heavy Check Mark ..White Heavy Check Mark - {0x0270a, 0x0270b}, // Raised Fist ..Raised Hand - {0x02728, 0x02728}, // Sparkles ..Sparkles - {0x0274c, 0x0274c}, // Cross Mark ..Cross Mark - {0x0274e, 0x0274e}, // Negative Squared Cross M..Negative Squared Cross M - {0x02753, 0x02755}, // Black Question Mark Orna..White Exclamation Mark O - {0x02757, 0x02757}, // Heavy Exclamation Mark S..Heavy Exclamation Mark S - {0x02795, 0x02797}, // Heavy Plus Sign ..Heavy Division Sign - {0x027b0, 0x027b0}, // Curly Loop ..Curly Loop - {0x027bf, 0x027bf}, // Double Curly Loop ..Double Curly Loop - {0x02b1b, 0x02b1c}, // Black Large Square ..White Large Square - {0x02b50, 0x02b50}, // White Medium Star ..White Medium Star - {0x02b55, 0x02b55}, // Heavy Large Circle ..Heavy Large Circle - {0x02e80, 0x02e99}, // Cjk Radical Repeat ..Cjk Radical Rap - {0x02e9b, 0x02ef3}, // Cjk Radical Choke ..Cjk Radical C-simplified - {0x02f00, 0x02fd5}, // Kangxi Radical One ..Kangxi Radical Flute - {0x02ff0, 0x02ffb}, // Ideographic Description ..Ideographic Description - {0x03000, 0x0303e}, // Ideographic Space ..Ideographic Variation In - {0x03041, 0x03096}, // Hiragana Letter Small A ..Hiragana Letter Small Ke - {0x03099, 0x030ff}, // Combining Katakana-hirag..Katakana Digraph Koto - {0x03105, 0x0312f}, // Bopomofo Letter B ..Bopomofo Letter Nn - {0x03131, 0x0318e}, // Hangul Letter Kiyeok ..Hangul Letter Araeae - {0x03190, 0x031e3}, // Ideographic Annotation L..Cjk Stroke Q - {0x031f0, 0x0321e}, // Katakana Letter Small Ku..Parenthesized Korean Cha - {0x03220, 0x03247}, // Parenthesized Ideograph ..Circled Ideograph Koto - {0x03250, 0x04dbf}, // Partnership Sign ..(nil) - {0x04e00, 0x0a48c}, // Cjk Unified Ideograph-4e..Yi Syllable Yyr - {0x0a490, 0x0a4c6}, // Yi Radical Qot ..Yi Radical Ke - {0x0a960, 0x0a97c}, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo - {0x0ac00, 0x0d7a3}, // Hangul Syllable Ga ..Hangul Syllable Hih - {0x0f900, 0x0faff}, // Cjk Compatibility Ideogr..(nil) - {0x0fe10, 0x0fe19}, // Presentation Form For Ve..Presentation Form For Ve - {0x0fe30, 0x0fe52}, // Presentation Form For Ve..Small Full Stop - {0x0fe54, 0x0fe66}, // Small Semicolon ..Small Equals Sign - {0x0fe68, 0x0fe6b}, // Small Reverse Solidus ..Small Commercial At - {0x0ff01, 0x0ff60}, // Fullwidth Exclamation Ma..Fullwidth Right White Pa - {0x0ffe0, 0x0ffe6}, // Fullwidth Cent Sign ..Fullwidth Won Sign - {0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..(nil) - {0x16ff0, 0x16ff1}, // (nil) ..(nil) - {0x17000, 0x187f7}, // (nil) ..(nil) - {0x18800, 0x18cd5}, // Tangut Component-001 ..(nil) - {0x18d00, 0x18d08}, // (nil) ..(nil) - {0x1b000, 0x1b11e}, // Katakana Letter Archaic ..Hentaigana Letter N-mu-m - {0x1b150, 0x1b152}, // Hiragana Letter Small Wi..Hiragana Letter Small Wo - {0x1b164, 0x1b167}, // Katakana Letter Small Wi..Katakana Letter Small N - {0x1b170, 0x1b2fb}, // Nushu Character-1b170 ..Nushu Character-1b2fb - {0x1f004, 0x1f004}, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon - {0x1f0cf, 0x1f0cf}, // Playing Card Black Joker..Playing Card Black Joker - {0x1f18e, 0x1f18e}, // Negative Squared Ab ..Negative Squared Ab - {0x1f191, 0x1f19a}, // Squared Cl ..Squared Vs - {0x1f200, 0x1f202}, // Square Hiragana Hoka ..Squared Katakana Sa - {0x1f210, 0x1f23b}, // Squared Cjk Unified Ideo..Squared Cjk Unified Ideo - {0x1f240, 0x1f248}, // Tortoise Shell Bracketed..Tortoise Shell Bracketed - {0x1f250, 0x1f251}, // Circled Ideograph Advant..Circled Ideograph Accept - {0x1f260, 0x1f265}, // Rounded Symbol For Fu ..Rounded Symbol For Cai - {0x1f300, 0x1f320}, // Cyclone ..Shooting Star - {0x1f32d, 0x1f335}, // Hot Dog ..Cactus - {0x1f337, 0x1f37c}, // Tulip ..Baby Bottle - {0x1f37e, 0x1f393}, // Bottle With Popping Cork..Graduation Cap - {0x1f3a0, 0x1f3ca}, // Carousel Horse ..Swimmer - {0x1f3cf, 0x1f3d3}, // Cricket Bat And Ball ..Table Tennis Paddle And - {0x1f3e0, 0x1f3f0}, // House Building ..European Castle - {0x1f3f4, 0x1f3f4}, // Waving Black Flag ..Waving Black Flag - {0x1f3f8, 0x1f43e}, // Badminton Racquet And Sh..Paw Prints - {0x1f440, 0x1f440}, // Eyes ..Eyes - {0x1f442, 0x1f4fc}, // Ear ..Videocassette - {0x1f4ff, 0x1f53d}, // Prayer Beads ..Down-pointing Small Red - {0x1f54b, 0x1f54e}, // Kaaba ..Menorah With Nine Branch - {0x1f550, 0x1f567}, // Clock Face One Oclock ..Clock Face Twelve-thirty - {0x1f57a, 0x1f57a}, // Man Dancing ..Man Dancing - {0x1f595, 0x1f596}, // Reversed Hand With Middl..Raised Hand With Part Be - {0x1f5a4, 0x1f5a4}, // Black Heart ..Black Heart - {0x1f5fb, 0x1f64f}, // Mount Fuji ..Person With Folded Hands - {0x1f680, 0x1f6c5}, // Rocket ..Left Luggage - {0x1f6cc, 0x1f6cc}, // Sleeping Accommodation ..Sleeping Accommodation - {0x1f6d0, 0x1f6d2}, // Place Of Worship ..Shopping Trolley - {0x1f6d5, 0x1f6d7}, // Hindu Temple ..(nil) - {0x1f6eb, 0x1f6ec}, // Airplane Departure ..Airplane Arriving - {0x1f6f4, 0x1f6fc}, // Scooter ..(nil) - {0x1f7e0, 0x1f7eb}, // Large Orange Circle ..Large Brown Square - {0x1f90c, 0x1f93a}, // (nil) ..Fencer - {0x1f93c, 0x1f945}, // Wrestlers ..Goal Net - {0x1f947, 0x1f978}, // First Place Medal ..(nil) - {0x1f97a, 0x1f9cb}, // Face With Pleading Eyes ..(nil) - {0x1f9cd, 0x1f9ff}, // Standing Person ..Nazar Amulet - {0x1fa70, 0x1fa74}, // Ballet Shoes ..(nil) - {0x1fa78, 0x1fa7a}, // Drop Of Blood ..Stethoscope - {0x1fa80, 0x1fa86}, // Yo-yo ..(nil) - {0x1fa90, 0x1faa8}, // Ringed Planet ..(nil) - {0x1fab0, 0x1fab6}, // (nil) ..(nil) - {0x1fac0, 0x1fac2}, // (nil) ..(nil) - {0x1fad0, 0x1fad6}, // (nil) ..(nil) - {0x20000, 0x2fffd}, // Cjk Unified Ideograph-20..(nil) - {0x30000, 0x3fffd}, // (nil) ..(nil) + {0x01100, 0x0115f}, // Hangul Choseong Kiyeok ..Hangul Choseong Filler + {0x0231a, 0x0231b}, // Watch ..Hourglass + {0x02329, 0x0232a}, // Left-pointing Angle Brac..Right-pointing Angle Bra + {0x023e9, 0x023ec}, // Black Right-pointing Dou..Black Down-pointing Doub + {0x023f0, 0x023f0}, // Alarm Clock ..Alarm Clock + {0x023f3, 0x023f3}, // Hourglass With Flowing S..Hourglass With Flowing S + {0x025fd, 0x025fe}, // White Medium Small Squar..Black Medium Small Squar + {0x02614, 0x02615}, // Umbrella With Rain Drops..Hot Beverage + {0x02648, 0x02653}, // Aries ..Pisces + {0x0267f, 0x0267f}, // Wheelchair Symbol ..Wheelchair Symbol + {0x02693, 0x02693}, // Anchor ..Anchor + {0x026a1, 0x026a1}, // High Voltage Sign ..High Voltage Sign + {0x026aa, 0x026ab}, // Medium White Circle ..Medium Black Circle + {0x026bd, 0x026be}, // Soccer Ball ..Baseball + {0x026c4, 0x026c5}, // Snowman Without Snow ..Sun Behind Cloud + {0x026ce, 0x026ce}, // Ophiuchus ..Ophiuchus + {0x026d4, 0x026d4}, // No Entry ..No Entry + {0x026ea, 0x026ea}, // Church ..Church + {0x026f2, 0x026f3}, // Fountain ..Flag In Hole + {0x026f5, 0x026f5}, // Sailboat ..Sailboat + {0x026fa, 0x026fa}, // Tent ..Tent + {0x026fd, 0x026fd}, // Fuel Pump ..Fuel Pump + {0x02705, 0x02705}, // White Heavy Check Mark ..White Heavy Check Mark + {0x0270a, 0x0270b}, // Raised Fist ..Raised Hand + {0x02728, 0x02728}, // Sparkles ..Sparkles + {0x0274c, 0x0274c}, // Cross Mark ..Cross Mark + {0x0274e, 0x0274e}, // Negative Squared Cross M..Negative Squared Cross M + {0x02753, 0x02755}, // Black Question Mark Orna..White Exclamation Mark O + {0x02757, 0x02757}, // Heavy Exclamation Mark S..Heavy Exclamation Mark S + {0x02795, 0x02797}, // Heavy Plus Sign ..Heavy Division Sign + {0x027b0, 0x027b0}, // Curly Loop ..Curly Loop + {0x027bf, 0x027bf}, // Double Curly Loop ..Double Curly Loop + {0x02b1b, 0x02b1c}, // Black Large Square ..White Large Square + {0x02b50, 0x02b50}, // White Medium Star ..White Medium Star + {0x02b55, 0x02b55}, // Heavy Large Circle ..Heavy Large Circle + {0x02e80, 0x02e99}, // Cjk Radical Repeat ..Cjk Radical Rap + {0x02e9b, 0x02ef3}, // Cjk Radical Choke ..Cjk Radical C-simplified + {0x02f00, 0x02fd5}, // Kangxi Radical One ..Kangxi Radical Flute + {0x02ff0, 0x02ffb}, // Ideographic Description ..Ideographic Description + {0x03000, 0x0303e}, // Ideographic Space ..Ideographic Variation In + {0x03041, 0x03096}, // Hiragana Letter Small A ..Hiragana Letter Small Ke + {0x03099, 0x030ff}, // Combining Katakana-hirag..Katakana Digraph Koto + {0x03105, 0x0312f}, // Bopomofo Letter B ..Bopomofo Letter Nn + {0x03131, 0x0318e}, // Hangul Letter Kiyeok ..Hangul Letter Araeae + {0x03190, 0x031e3}, // Ideographic Annotation L..Cjk Stroke Q + {0x031f0, 0x0321e}, // Katakana Letter Small Ku..Parenthesized Korean Cha + {0x03220, 0x03247}, // Parenthesized Ideograph ..Circled Ideograph Koto + {0x03250, 0x04dbf}, // Partnership Sign ..(nil) + {0x04e00, 0x0a48c}, // Cjk Unified Ideograph-4e..Yi Syllable Yyr + {0x0a490, 0x0a4c6}, // Yi Radical Qot ..Yi Radical Ke + {0x0a960, 0x0a97c}, // Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo + {0x0ac00, 0x0d7a3}, // Hangul Syllable Ga ..Hangul Syllable Hih + {0x0f900, 0x0faff}, // Cjk Compatibility Ideogr..(nil) + {0x0fe10, 0x0fe19}, // Presentation Form For Ve..Presentation Form For Ve + {0x0fe30, 0x0fe52}, // Presentation Form For Ve..Small Full Stop + {0x0fe54, 0x0fe66}, // Small Semicolon ..Small Equals Sign + {0x0fe68, 0x0fe6b}, // Small Reverse Solidus ..Small Commercial At + {0x0ff01, 0x0ff60}, // Fullwidth Exclamation Ma..Fullwidth Right White Pa + {0x0ffe0, 0x0ffe6}, // Fullwidth Cent Sign ..Fullwidth Won Sign + {0x16fe0, 0x16fe4}, // Tangut Iteration Mark ..(nil) + {0x16ff0, 0x16ff1}, // (nil) ..(nil) + {0x17000, 0x187f7}, // (nil) ..(nil) + {0x18800, 0x18cd5}, // Tangut Component-001 ..(nil) + {0x18d00, 0x18d08}, // (nil) ..(nil) + {0x1b000, 0x1b11e}, // Katakana Letter Archaic ..Hentaigana Letter N-mu-m + {0x1b150, 0x1b152}, // Hiragana Letter Small Wi..Hiragana Letter Small Wo + {0x1b164, 0x1b167}, // Katakana Letter Small Wi..Katakana Letter Small N + {0x1b170, 0x1b2fb}, // Nushu Character-1b170 ..Nushu Character-1b2fb + {0x1f004, 0x1f004}, // Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon + {0x1f0cf, 0x1f0cf}, // Playing Card Black Joker..Playing Card Black Joker + {0x1f18e, 0x1f18e}, // Negative Squared Ab ..Negative Squared Ab + {0x1f191, 0x1f19a}, // Squared Cl ..Squared Vs + {0x1f200, 0x1f202}, // Square Hiragana Hoka ..Squared Katakana Sa + {0x1f210, 0x1f23b}, // Squared Cjk Unified Ideo..Squared Cjk Unified Ideo + {0x1f240, 0x1f248}, // Tortoise Shell Bracketed..Tortoise Shell Bracketed + {0x1f250, 0x1f251}, // Circled Ideograph Advant..Circled Ideograph Accept + {0x1f260, 0x1f265}, // Rounded Symbol For Fu ..Rounded Symbol For Cai + {0x1f300, 0x1f320}, // Cyclone ..Shooting Star + {0x1f32d, 0x1f335}, // Hot Dog ..Cactus + {0x1f337, 0x1f37c}, // Tulip ..Baby Bottle + {0x1f37e, 0x1f393}, // Bottle With Popping Cork..Graduation Cap + {0x1f3a0, 0x1f3ca}, // Carousel Horse ..Swimmer + {0x1f3cf, 0x1f3d3}, // Cricket Bat And Ball ..Table Tennis Paddle And + {0x1f3e0, 0x1f3f0}, // House Building ..European Castle + {0x1f3f4, 0x1f3f4}, // Waving Black Flag ..Waving Black Flag + {0x1f3f8, 0x1f43e}, // Badminton Racquet And Sh..Paw Prints + {0x1f440, 0x1f440}, // Eyes ..Eyes + {0x1f442, 0x1f4fc}, // Ear ..Videocassette + {0x1f4ff, 0x1f53d}, // Prayer Beads ..Down-pointing Small Red + {0x1f54b, 0x1f54e}, // Kaaba ..Menorah With Nine Branch + {0x1f550, 0x1f567}, // Clock Face One Oclock ..Clock Face Twelve-thirty + {0x1f57a, 0x1f57a}, // Man Dancing ..Man Dancing + {0x1f595, 0x1f596}, // Reversed Hand With Middl..Raised Hand With Part Be + {0x1f5a4, 0x1f5a4}, // Black Heart ..Black Heart + {0x1f5fb, 0x1f64f}, // Mount Fuji ..Person With Folded Hands + {0x1f680, 0x1f6c5}, // Rocket ..Left Luggage + {0x1f6cc, 0x1f6cc}, // Sleeping Accommodation ..Sleeping Accommodation + {0x1f6d0, 0x1f6d2}, // Place Of Worship ..Shopping Trolley + {0x1f6d5, 0x1f6d7}, // Hindu Temple ..(nil) + {0x1f6eb, 0x1f6ec}, // Airplane Departure ..Airplane Arriving + {0x1f6f4, 0x1f6fc}, // Scooter ..(nil) + {0x1f7e0, 0x1f7eb}, // Large Orange Circle ..Large Brown Square + {0x1f90c, 0x1f93a}, // (nil) ..Fencer + {0x1f93c, 0x1f945}, // Wrestlers ..Goal Net + {0x1f947, 0x1f978}, // First Place Medal ..(nil) + {0x1f97a, 0x1f9cb}, // Face With Pleading Eyes ..(nil) + {0x1f9cd, 0x1f9ff}, // Standing Person ..Nazar Amulet + {0x1fa70, 0x1fa74}, // Ballet Shoes ..(nil) + {0x1fa78, 0x1fa7a}, // Drop Of Blood ..Stethoscope + {0x1fa80, 0x1fa86}, // Yo-yo ..(nil) + {0x1fa90, 0x1faa8}, // Ringed Planet ..(nil) + {0x1fab0, 0x1fab6}, // (nil) ..(nil) + {0x1fac0, 0x1fac2}, // (nil) ..(nil) + {0x1fad0, 0x1fad6}, // (nil) ..(nil) + {0x20000, 0x2fffd}, // Cjk Unified Ideograph-20..(nil) + {0x30000, 0x3fffd}, // (nil) ..(nil) }; -bool intable(struct width_interval* table, int table_length, int c) { +bool intable(struct width_interval *table, int table_length, int c) { // First quick check for Latin1 etc. characters. - if (c < table[0].start) return false; + if (c < table[0].start) + return false; // Binary search in table. int bot = 0; @@ -722,30 +751,32 @@ bool intable(struct width_interval* table, int table_length, int c) { return false; } -} +} // namespace int wcwidth(wchar_t ucs) { // NOTE: created by hand, there isn't anything identifiable other than // general Cf category code to identify these, and some characters in Cf // category code are of non-zero width. - if (ucs == 0 || ucs == 0x034F || (0x200B <= ucs && ucs <= 0x200F) || - ucs == 0x2028 || ucs == 0x2029 || (0x202A <= ucs && ucs <= 0x202E) || - (0x2060 <= ucs && ucs <= 0x2063)) { + if (ucs == 0 || ucs == 0x034F || (0x200B <= ucs && ucs <= 0x200F) || ucs == 0x2028 || + ucs == 0x2029 || (0x202A <= ucs && ucs <= 0x202E) || (0x2060 <= ucs && ucs <= 0x2063)) { return 0; } // C0/C1 control characters. - if (ucs < 32 || (0x07F <= ucs && ucs < 0x0A0)) return -1; + if (ucs < 32 || (0x07F <= ucs && ucs < 0x0A0)) + return -1; // Combining characters with zero width. - if (intable(ZERO_WIDTH, sizeof(ZERO_WIDTH) / sizeof(struct width_interval), ucs)) return 0; + if (intable(ZERO_WIDTH, sizeof(ZERO_WIDTH) / sizeof(struct width_interval), ucs)) + return 0; - return intable(WIDE_EASTASIAN, sizeof(WIDE_EASTASIAN) / sizeof(struct width_interval), ucs) ? 2 : 1; + return intable(WIDE_EASTASIAN, sizeof(WIDE_EASTASIAN) / sizeof(struct width_interval), ucs) ? 2 + : 1; } int wcswidth(const wchar_t *wcs, size_t n) { int ret = 0; - for(size_t i = 0; i < n && wcs[i]; i++) { + for (size_t i = 0; i < n && wcs[i]; i++) { int cols = wcwidth(wcs[i]); if (cols < 0) return -1; @@ -757,22 +788,22 @@ int wcswidth(const wchar_t *wcs, size_t n) { wchar_t *wcsdup(const wchar_t *s) { size_t len = wcslen(s); - wchar_t *ret = (wchar_t *) malloc(sizeof(wchar_t) * (len + 1)); - if(!ret) + wchar_t *ret = (wchar_t *)malloc(sizeof(wchar_t) * (len + 1)); + if (!ret) return NULL; wmemcpy(ret, s, len + 1); return ret; } -int wcsncasecmp(const wchar_t* s1, const wchar_t* s2, size_t n) { - for(size_t i = 0; i < n; i++) { +int wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n) { + for (size_t i = 0; i < n; i++) { wint_t c1 = towlower(s1[i]); wint_t c2 = towlower(s2[i]); - if(c1 == L'\0' && c2 == L'\0') + if (c1 == L'\0' && c2 == L'\0') return 0; - if(c1 < c2) + if (c1 < c2) return -1; - if(c1 > c2) + if (c1 > c2) return 1; } return 0; diff --git a/options/ansi/generic/wctype.cpp b/options/ansi/generic/wctype.cpp index 57dcbc9fd2..ad4389959f 100644 --- a/options/ansi/generic/wctype.cpp +++ b/options/ansi/generic/wctype.cpp @@ -1,9 +1,7 @@ -#include #include -#include #include +#include +#include -wctrans_t wctrans(const char *) MLIBC_STUB_BODY -wint_t towctrans(wint_t, wctrans_t) MLIBC_STUB_BODY - +wctrans_t wctrans(const char *) MLIBC_STUB_BODY wint_t towctrans(wint_t, wctrans_t) MLIBC_STUB_BODY diff --git a/options/ansi/include/alloca.h b/options/ansi/include/alloca.h index edfc80d337..679dd01405 100644 --- a/options/ansi/include/alloca.h +++ b/options/ansi/include/alloca.h @@ -5,4 +5,3 @@ #define alloca __builtin_alloca #endif /* _ALLOCA_H */ - diff --git a/options/ansi/include/assert.h b/options/ansi/include/assert.h index dbad1f0ae7..2f812f3c9e 100644 --- a/options/ansi/include/assert.h +++ b/options/ansi/include/assert.h @@ -9,8 +9,8 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY /* NOTE: This is not ISO C. Declared in LSB */ -__attribute__ ((__noreturn__)) void __assert_fail(const char *assertion, const char *file, unsigned int line, - const char *function); +__attribute__((__noreturn__)) void +__assert_fail(const char *assertion, const char *file, unsigned int line, const char *function); #endif /* !__MLIBC_ABI_ONLY */ @@ -23,7 +23,7 @@ __attribute__ ((__noreturn__)) void __assert_fail(const char *assertion, const c #include #if __MLIBC_GLIBC_OPTION -# include +#include #endif /* NOTE: [7.2] requires this be outside the include guard */ @@ -35,8 +35,8 @@ __attribute__ ((__noreturn__)) void __assert_fail(const char *assertion, const c #else /* NDEBUG */ #undef assert -#define assert(assertion) ((void)((assertion) \ - || (__assert_fail(#assertion, __FILE__, __LINE__, __func__), 0))) +#define assert(assertion) \ + ((void)((assertion) || (__assert_fail(#assertion, __FILE__, __LINE__, __func__), 0))) #endif /* NDEBUG */ diff --git a/options/ansi/include/bits/ansi/fenv.h b/options/ansi/include/bits/ansi/fenv.h index 6122628288..55c05c4ad3 100644 --- a/options/ansi/include/bits/ansi/fenv.h +++ b/options/ansi/include/bits/ansi/fenv.h @@ -10,7 +10,8 @@ #define FE_OVERFLOW 8 #define FE_UNDERFLOW 16 -#define FE_ALL_EXCEPT (FE_DENORMAL | FE_DIVBYZERO | FE_INEXACT | FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW) +#define FE_ALL_EXCEPT \ + (FE_DENORMAL | FE_DIVBYZERO | FE_INEXACT | FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW) #define FE_TONEAREST 0 #define FE_DOWNWARD 0x400 @@ -47,27 +48,27 @@ #define FE_DOWNWARD 2 #define FE_UPWARD 3 -#elif defined (__m68k__) +#elif defined(__m68k__) #if __HAVE_68881__ || __mcffpu__ || __HAVE_FPU_ -#define FE_INEXACT 8 -#define FE_DIVBYZERO 16 -#define FE_UNDERFLOW 32 -#define FE_OVERFLOW 64 -#define FE_INVALID 128 +#define FE_INEXACT 8 +#define FE_DIVBYZERO 16 +#define FE_UNDERFLOW 32 +#define FE_OVERFLOW 64 +#define FE_INVALID 128 #define FE_ALL_EXCEPT 0xf8 -#define FE_TONEAREST 0 +#define FE_TONEAREST 0 #define FE_TOWARDZERO 16 -#define FE_DOWNWARD 32 -#define FE_UPWARD 48 +#define FE_DOWNWARD 32 +#define FE_UPWARD 48 #else #define FE_ALL_EXCEPT 0 -#define FE_TONEAREST 0 +#define FE_TONEAREST 0 #endif diff --git a/options/ansi/include/bits/ansi/time_t.h b/options/ansi/include/bits/ansi/time_t.h index 1c29fa0f67..90a8d436ab 100644 --- a/options/ansi/include/bits/ansi/time_t.h +++ b/options/ansi/include/bits/ansi/time_t.h @@ -5,4 +5,3 @@ typedef long time_t; #endif - diff --git a/options/ansi/include/bits/ansi/timespec.h b/options/ansi/include/bits/ansi/timespec.h index e4ab91e892..3b6be65255 100644 --- a/options/ansi/include/bits/ansi/timespec.h +++ b/options/ansi/include/bits/ansi/timespec.h @@ -10,4 +10,3 @@ struct timespec { }; #endif /* MLIBC_TIMESPEC_H */ - diff --git a/options/ansi/include/complex.h b/options/ansi/include/complex.h index 1eae120379..0a7bf9fbbf 100644 --- a/options/ansi/include/complex.h +++ b/options/ansi/include/complex.h @@ -5,8 +5,8 @@ * Public domain. */ -#ifndef _COMPLEX_H -#define _COMPLEX_H +#ifndef _COMPLEX_H +#define _COMPLEX_H #define complex _Complex #define _Complex_I 1.0fi @@ -101,7 +101,7 @@ double complex csqrt(double complex __x); float complex csqrtf(float complex __x); /* 7.3.9 Manipulation functions */ -/* 7.3.9.1 The carg functions */ +/* 7.3.9.1 The carg functions */ double carg(double complex __x); float cargf(float complex __x); @@ -131,4 +131,4 @@ long double creall(long double complex __x); } #endif -#endif /* ! _COMPLEX_H */ +#endif /* ! _COMPLEX_H */ diff --git a/options/ansi/include/ctype.h b/options/ansi/include/ctype.h index 151f1f8823..fc75db4f1f 100644 --- a/options/ansi/include/ctype.h +++ b/options/ansi/include/ctype.h @@ -33,14 +33,14 @@ int toupper(int __c); #endif /* !__MLIBC_ABI_ONLY */ /* Borrowed from glibc */ -#define toascii(c) ((c) & 0x7f) +#define toascii(c) ((c) & 0x7f) #ifdef __cplusplus } #endif #if __MLIBC_POSIX_OPTION -# include +#include #endif #endif /* _CTYPE_H */ diff --git a/options/ansi/include/fenv.h b/options/ansi/include/fenv.h index 7366706fa9..4979a0b55e 100644 --- a/options/ansi/include/fenv.h +++ b/options/ansi/include/fenv.h @@ -2,8 +2,8 @@ #ifndef _FENV_H #define _FENV_H -#include #include +#include #ifdef __cplusplus extern "C" { @@ -38,7 +38,6 @@ int feupdateenv(const fenv_t *__envp); } #endif -#define FE_DFL_ENV ((const fenv_t *) -1) +#define FE_DFL_ENV ((const fenv_t *)-1) #endif /* _FENV_H */ - diff --git a/options/ansi/include/inttypes.h b/options/ansi/include/inttypes.h index b30fee872e..70ab498c79 100644 --- a/options/ansi/include/inttypes.h +++ b/options/ansi/include/inttypes.h @@ -1,19 +1,19 @@ #ifndef _STDINT_H #define _STDINT_H -#include #include +#include /* Even though this is not strictly not-ABI, it is mlibc-printf specific therefore */ /* gate behind !__MLIBC_ABI_ONLY */ #ifndef __MLIBC_ABI_ONLY #if UINTPTR_MAX == UINT64_MAX -# define __PRI64 "l" -# define __PRIPTR "l" +#define __PRI64 "l" +#define __PRIPTR "l" #else -# define __PRI64 "ll" -# define __PRIPTR "" +#define __PRI64 "ll" +#define __PRIPTR "" #endif /* TODO: This is extremly unelegant and fragile. */ diff --git a/options/ansi/include/limits.h b/options/ansi/include/limits.h index 83057747db..cdc26fccc4 100644 --- a/options/ansi/include/limits.h +++ b/options/ansi/include/limits.h @@ -4,25 +4,25 @@ #define CHAR_BIT 8 #ifndef MB_LEN_MAX -# define MB_LEN_MAX 4 +#define MB_LEN_MAX 4 #endif #ifdef LONG_MAX -# ifdef LONG_MAX == INT32_MAX -# define LONG_BIT 32 -# else +#ifdef LONG_MAX == INT32_MAX +#define LONG_BIT 32 +#else /* Safe assumption */ -# define LONG_BIT 64 -# endif +#define LONG_BIT 64 +#endif #elif defined __LONG_MAX__ -# if __LONG_MAX__ == INT32_MAX -# define LONG_BIT 32 -# else +#if __LONG_MAX__ == INT32_MAX +#define LONG_BIT 32 +#else /* Safe assumption */ -# define LONG_BIT 64 -# endif +#define LONG_BIT 64 +#endif #else -# error "Unsupported configuration, please define either LONG_MAX or __LONG_MAX__" +#error "Unsupported configuration, please define either LONG_MAX or __LONG_MAX__" #endif #undef SCHAR_MIN @@ -46,29 +46,29 @@ #define SCHAR_MIN (-__SCHAR_MAX__ - 1) #define SCHAR_MAX __SCHAR_MAX__ #if __SCHAR_MAX__ == __INT_MAX__ -# define UCHAR_MAX (__SCHAR_MAX__ * 2U + 1U) +#define UCHAR_MAX (__SCHAR_MAX__ * 2U + 1U) #else -# define UCHAR_MAX (__SCHAR_MAX__ * 2 + 1) +#define UCHAR_MAX (__SCHAR_MAX__ * 2 + 1) #endif #ifdef __CHAR_UNSIGNED__ -# define CHAR_MAX UCHAR_MAX -# if __SCHAR_MAX__ == __INT_MAX__ -# define CHAR_MIN 0U -# else -# define CHAR_MIN 0 -# endif +#define CHAR_MAX UCHAR_MAX +#if __SCHAR_MAX__ == __INT_MAX__ +#define CHAR_MIN 0U +#else +#define CHAR_MIN 0 +#endif #else -# define CHAR_MAX SCHAR_MAX -# define CHAR_MIN SCHAR_MIN +#define CHAR_MAX SCHAR_MAX +#define CHAR_MIN SCHAR_MIN #endif #define SHRT_MIN (-__SHRT_MAX__ - 1) #define SHRT_MAX __SHRT_MAX__ #if __SHRT_MAX__ == __INT_MAX__ -# define USHRT_MAX (__SHRT_MAX__ * 2U + 1U) +#define USHRT_MAX (__SHRT_MAX__ * 2U + 1U) #else -# define USHRT_MAX (__SHRT_MAX__ * 2 + 1) +#define USHRT_MAX (__SHRT_MAX__ * 2 + 1) #endif #define INT_MIN (-__INT_MAX__ - 1) @@ -97,9 +97,9 @@ #define NL_ARGMAX 9 #if INTPTR_MAX == INT64_MAX -# define SSIZE_MAX LONG_MAX +#define SSIZE_MAX LONG_MAX #elif INTPTR_MAX == INT32_MAX -# define SSIZE_MAX INT_MAX +#define SSIZE_MAX INT_MAX #endif #define _POSIX_ARG_MAX 4096 diff --git a/options/ansi/include/locale.h b/options/ansi/include/locale.h index 7851152476..cf31b1599c 100644 --- a/options/ansi/include/locale.h +++ b/options/ansi/include/locale.h @@ -14,14 +14,14 @@ #define LC_TIME 6 #define LC_MESSAGES 7 -#define LC_GLOBAL_LOCALE ((locale_t) -1L) - -#define LC_CTYPE_MASK (1< +#include #endif /* __MLIBC_POSIX_OPTION */ #ifdef __cplusplus @@ -78,4 +78,3 @@ struct lconv *localeconv(void); #endif #endif /* _LOCALE_H */ - diff --git a/options/ansi/include/math.h b/options/ansi/include/math.h index a4ffd3231f..7f90a19876 100644 --- a/options/ansi/include/math.h +++ b/options/ansi/include/math.h @@ -5,20 +5,20 @@ #include /* this is a posix extension */ -#define M_E 2.7182818284590452354 -#define M_LOG2E 1.4426950408889634074 -#define M_LOG10E 0.43429448190325182765 -#define M_LN2 0.69314718055994530942 -#define M_LN10 2.30258509299404568402 -#define M_PI 3.14159265358979323846 -#define M_PI_2 1.57079632679489661923 -#define M_PI_4 0.78539816339744830962 -#define M_1_PI 0.31830988618379067154 -#define M_2_PI 0.63661977236758134308 -#define M_2_SQRTPI 1.12837916709551257390 -#define M_SQRT2 1.41421356237309504880 -#define M_SQRT1_2 0.70710678118654752440 -#define M_PIl 3.141592653589793238462643383279502884L +#define M_E 2.7182818284590452354 +#define M_LOG2E 1.4426950408889634074 +#define M_LOG10E 0.43429448190325182765 +#define M_LN2 0.69314718055994530942 +#define M_LN10 2.30258509299404568402 +#define M_PI 3.14159265358979323846 +#define M_PI_2 1.57079632679489661923 +#define M_PI_4 0.78539816339744830962 +#define M_1_PI 0.31830988618379067154 +#define M_2_PI 0.63661977236758134308 +#define M_2_SQRTPI 1.12837916709551257390 +#define M_SQRT2 1.41421356237309504880 +#define M_SQRT1_2 0.70710678118654752440 +#define M_PIl 3.141592653589793238462643383279502884L /* The following two definitions are from musl. */ #define FP_ILOGBNAN (-1 - (int)(((unsigned)-1) >> 1)) @@ -59,11 +59,12 @@ int __fpclassify(double __x); int __fpclassifyf(float __x); int __fpclassifyl(long double __x); -#define fpclassify(x) \ - (sizeof(x) == sizeof(double) ? __fpclassify(x) : \ - (sizeof(x) == sizeof(float) ? __fpclassifyf(x) : \ - (sizeof(x) == sizeof(long double) ? __fpclassifyl(x) : \ - 0))) +#define fpclassify(x) \ + (sizeof(x) == sizeof(double) \ + ? __fpclassify(x) \ + : (sizeof(x) == sizeof(float) \ + ? __fpclassifyf(x) \ + : (sizeof(x) == sizeof(long double) ? __fpclassifyl(x) : 0))) #define isfinite(x) (fpclassify(x) & (FP_NORMAL | FP_SUBNORMAL | FP_ZERO)) #define isnan(x) (fpclassify(x) == FP_NAN) @@ -74,29 +75,59 @@ int __fpclassifyl(long double __x); #define signbit(x) (__builtin_signbit(x)) /* [C11/7.12.14 Comparison macros] */ -#define isunordered(x,y) (isnan((x)) ? ((void)(y),1) : isnan((y))) - -__MLIBC_INLINE_DEFINITION int __mlibc_isless(double_t __x, double_t __y) { return !isunordered(__x, __y) && __x < __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessf(float_t __x, float_t __y) { return !isunordered(__x, __y) && __x < __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessl(long double __x, long double __y) { return !isunordered(__x, __y) && __x < __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessequal(double_t __x, double_t __y) { return !isunordered(__x, __y) && __x <= __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessequalf(float_t __x, float_t __y) { return !isunordered(__x, __y) && __x <= __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessequall(long double __x, long double __y) { return !isunordered(__x, __y) && __x <= __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessgreater(double_t __x, double_t __y) { return !isunordered(__x, __y) && __x != __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessgreaterf(float_t __x, float_t __y) { return !isunordered(__x, __y) && __x != __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_islessgreaterl(long double __x, long double __y) { return !isunordered(__x, __y) && __x != __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_isgreater(double_t __x, double_t __y) { return !isunordered(__x, __y) && __x > __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterf(float_t __x, float_t __y) { return !isunordered(__x, __y) && __x > __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterl(long double __x, long double __y) { return !isunordered(__x, __y) && __x > __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterequal(double_t __x, double_t __y) { return !isunordered(__x, __y) && __x >= __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterequalf(float_t __x, float_t __y) { return !isunordered(__x, __y) && __x >= __y; } -__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterequall(long double __x, long double __y) { return !isunordered(__x, __y) && __x >= __y; } +#define isunordered(x, y) (isnan((x)) ? ((void)(y), 1) : isnan((y))) + +__MLIBC_INLINE_DEFINITION int __mlibc_isless(double_t __x, double_t __y) { + return !isunordered(__x, __y) && __x < __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessf(float_t __x, float_t __y) { + return !isunordered(__x, __y) && __x < __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessl(long double __x, long double __y) { + return !isunordered(__x, __y) && __x < __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessequal(double_t __x, double_t __y) { + return !isunordered(__x, __y) && __x <= __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessequalf(float_t __x, float_t __y) { + return !isunordered(__x, __y) && __x <= __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessequall(long double __x, long double __y) { + return !isunordered(__x, __y) && __x <= __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessgreater(double_t __x, double_t __y) { + return !isunordered(__x, __y) && __x != __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessgreaterf(float_t __x, float_t __y) { + return !isunordered(__x, __y) && __x != __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_islessgreaterl(long double __x, long double __y) { + return !isunordered(__x, __y) && __x != __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_isgreater(double_t __x, double_t __y) { + return !isunordered(__x, __y) && __x > __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterf(float_t __x, float_t __y) { + return !isunordered(__x, __y) && __x > __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterl(long double __x, long double __y) { + return !isunordered(__x, __y) && __x > __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterequal(double_t __x, double_t __y) { + return !isunordered(__x, __y) && __x >= __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterequalf(float_t __x, float_t __y) { + return !isunordered(__x, __y) && __x >= __y; +} +__MLIBC_INLINE_DEFINITION int __mlibc_isgreaterequall(long double __x, long double __y) { + return !isunordered(__x, __y) && __x >= __y; +} /* TODO: We chould use _Generic here but that does not work in C++ code. */ -#define __MLIBC_CHOOSE_COMPARISON(x, y, p) ( \ - sizeof((x)+(y)) == sizeof(float) ? p##f(x, y) : \ - sizeof((x)+(y)) == sizeof(double) ? p(x, y) : \ - p##l(x, y) ) +#define __MLIBC_CHOOSE_COMPARISON(x, y, p) \ + (sizeof((x) + (y)) == sizeof(float) ? p##f(x, y) \ + : sizeof((x) + (y)) == sizeof(double) ? p(x, y) \ + : p##l(x, y)) #define isless(x, y) __MLIBC_CHOOSE_COMPARISON(x, y, __mlibc_isless) #define islessequal(x, y) __MLIBC_CHOOSE_COMPARISON(x, y, __mlibc_islessequal) @@ -380,4 +411,3 @@ int finitef(float __x); #endif #endif /* _MATH_H */ - diff --git a/options/ansi/include/mlibc/ansi-sysdeps.hpp b/options/ansi/include/mlibc/ansi-sysdeps.hpp index 203084e4da..26a8218546 100644 --- a/options/ansi/include/mlibc/ansi-sysdeps.hpp +++ b/options/ansi/include/mlibc/ansi-sysdeps.hpp @@ -3,13 +3,13 @@ #include +#include +#include #include #include -#include -#include +#include #include #include -#include #include #include @@ -22,7 +22,15 @@ namespace [[gnu::visibility("hidden")]] mlibc { // If *stack is not null, it should point to the lowest addressable byte of the stack. // Returns the new stack pointer in *stack and the stack base in *stack_base. -[[gnu::weak]] int sys_prepare_stack(void **stack, void *entry, void *user_arg, void* tcb, size_t *stack_size, size_t *guard_size, void **stack_base); +[[gnu::weak]] int sys_prepare_stack( + void **stack, + void *entry, + void *user_arg, + void *tcb, + size_t *stack_size, + size_t *guard_size, + void **stack_base +); [[gnu::weak]] int sys_clone(void *tcb, pid_t *pid_out, void *stack); int sys_futex_wait(int *pointer, int expected, const struct timespec *time); @@ -32,8 +40,7 @@ int sys_open(const char *pathname, int flags, mode_t mode, int *fd); [[gnu::weak]] int sys_flock(int fd, int options); [[gnu::weak]] int sys_open_dir(const char *path, int *handle); -[[gnu::weak]] int sys_read_entries(int handle, void *buffer, size_t max_size, - size_t *bytes_read); +[[gnu::weak]] int sys_read_entries(int handle, void *buffer, size_t max_size, size_t *bytes_read); int sys_read(int fd, void *buf, size_t count, ssize_t *bytes_read); @@ -52,12 +59,13 @@ int sys_clock_get(int clock, time_t *secs, long *nanos); [[gnu::weak]] int sys_rmdir(const char *path); [[gnu::weak]] int sys_unlinkat(int dirfd, const char *path, int flags); [[gnu::weak]] int sys_rename(const char *path, const char *new_path); -[[gnu::weak]] int sys_renameat(int olddirfd, const char *old_path, int newdirfd, const char *new_path); +[[gnu::weak]] int +sys_renameat(int olddirfd, const char *old_path, int newdirfd, const char *new_path); -[[gnu::weak]] int sys_sigprocmask(int how, const sigset_t *__restrict set, - sigset_t *__restrict retrieve); -[[gnu::weak]] int sys_sigaction(int, const struct sigaction *__restrict, - struct sigaction *__restrict); +[[gnu::weak]] int +sys_sigprocmask(int how, const sigset_t *__restrict set, sigset_t *__restrict retrieve); +[[gnu::weak]] int +sys_sigaction(int, const struct sigaction *__restrict, struct sigaction *__restrict); [[gnu::weak]] int sys_fork(pid_t *child); [[gnu::weak]] int sys_waitpid(pid_t pid, int *status, int flags, struct rusage *ru, pid_t *ret_pid); @@ -66,6 +74,6 @@ int sys_clock_get(int clock, time_t *secs, long *nanos); [[gnu::weak]] pid_t sys_getpid(); [[gnu::weak]] int sys_kill(int, int); -} //namespace mlibc +} // namespace mlibc #endif // MLIBC_ANSI_SYSDEPS diff --git a/options/ansi/include/mlibc/file-io.hpp b/options/ansi/include/mlibc/file-io.hpp index 1155a2b3cc..28868f0855 100644 --- a/options/ansi/include/mlibc/file-io.hpp +++ b/options/ansi/include/mlibc/file-io.hpp @@ -3,32 +3,23 @@ #include -#include -#include #include +#include +#include namespace mlibc { -enum class stream_type { - unknown, - file_like, - pipe_like -}; +enum class stream_type { unknown, file_like, pipe_like }; -enum class buffer_mode { - unknown, - no_buffer, - line_buffer, - full_buffer -}; +enum class buffer_mode { unknown, no_buffer, line_buffer, full_buffer }; struct abstract_file : __mlibc_file_base { -public: + public: abstract_file(void (*do_dispose)(abstract_file *) = nullptr); abstract_file(const abstract_file &) = delete; - abstract_file &operator= (const abstract_file &) = delete; + abstract_file &operator=(const abstract_file &) = delete; virtual ~abstract_file(); @@ -49,7 +40,7 @@ struct abstract_file : __mlibc_file_base { int tell(off_t *current_offset); int seek(off_t offset, int whence); -protected: + protected: virtual int determine_type(stream_type *type) = 0; virtual int determine_bufmode(buffer_mode *mode) = 0; virtual int io_read(char *buffer, size_t max_size, size_t *actual_size) = 0; @@ -57,7 +48,8 @@ struct abstract_file : __mlibc_file_base { virtual int io_seek(off_t offset, int whence, off_t *new_offset) = 0; int _reset(); -private: + + private: int _init_type(); int _init_bufmode(); @@ -70,7 +62,7 @@ struct abstract_file : __mlibc_file_base { buffer_mode _bufmode; void (*_do_dispose)(abstract_file *); -public: + public: // lock for file operations RecursiveFutexLock _lock; // All files are stored in a global linked list, so that they can be flushed at exit(). @@ -87,7 +79,7 @@ struct fd_file : abstract_file { static int parse_modestring(const char *mode); -protected: + protected: int determine_type(stream_type *type) override; int determine_bufmode(buffer_mode *mode) override; @@ -95,14 +87,13 @@ struct fd_file : abstract_file { int io_write(const char *buffer, size_t max_size, size_t *actual_size) override; int io_seek(off_t offset, int whence, off_t *new_offset) override; -private: + private: // Underlying file descriptor. int _fd; bool _force_unbuffered; }; -template -void file_dispose_cb(abstract_file *base) { +template void file_dispose_cb(abstract_file *base) { frg::destruct(getAllocator(), static_cast(base)); } diff --git a/options/ansi/include/setjmp.h b/options/ansi/include/setjmp.h index 91c0ecabbe..32936aa8f7 100644 --- a/options/ansi/include/setjmp.h +++ b/options/ansi/include/setjmp.h @@ -2,9 +2,9 @@ #ifndef _SETJMP_H #define _SETJMP_H -#include -#include #include +#include +#include #ifdef __cplusplus extern "C" { @@ -45,4 +45,3 @@ __attribute__((__noreturn__)) void siglongjmp(sigjmp_buf __buffer, int __value); #endif #endif /* _SETJMP_H */ - diff --git a/options/ansi/include/signal.h b/options/ansi/include/signal.h index 69eee4ae96..83643d89c5 100644 --- a/options/ansi/include/signal.h +++ b/options/ansi/include/signal.h @@ -38,11 +38,11 @@ int raise(int __sig); #endif #if __MLIBC_POSIX_OPTION -# include +#include #endif #if __MLIBC_GLIBC_OPTION -# include +#include #endif #endif /* _SIGNAL_H */ diff --git a/options/ansi/include/stdio.h b/options/ansi/include/stdio.h index 8b6de9f1c0..4600075ba2 100644 --- a/options/ansi/include/stdio.h +++ b/options/ansi/include/stdio.h @@ -3,14 +3,14 @@ #define _STDIO_H #include -#include #include +#include #include #include /* Glibc extensions require ssize_t. */ -#include #include +#include #ifdef __cplusplus extern "C" { @@ -94,7 +94,9 @@ char *tmpnam(char *__buffer); int fclose(FILE *__stream); int fflush(FILE *__stream); FILE *fopen(const char *__restrict __filename, const char *__restrict __mode); -FILE *freopen(const char *__restrict __filename, const char *__restrict __mode, FILE *__restrict __stream); +FILE *freopen( + const char *__restrict __filename, const char *__restrict __mode, FILE *__restrict __stream +); void setbuf(FILE *__restrict __stream, char *__restrict __buffer); int setvbuf(FILE *__restrict __stream, char *__restrict __buffer, int __mode, size_t __size); void setlinebuf(FILE *__stream); @@ -102,52 +104,53 @@ void setbuffer(FILE *__stream, char *__buffer, size_t __size); /* [C11-7.21.6] Formatted input/output functions */ -__attribute__((__format__(__printf__, 2, 3))) -int fprintf(FILE *__restrict __stream, const char *__restrict __format, ...); +__attribute__((__format__(__printf__, 2, 3))) int +fprintf(FILE *__restrict __stream, const char *__restrict __format, ...); -__attribute__((__format__(__scanf__, 2, 3))) -int fscanf(FILE *__restrict __stream, const char *__restrict __format, ...); +__attribute__((__format__(__scanf__, 2, 3))) int +fscanf(FILE *__restrict __stream, const char *__restrict __format, ...); -__attribute__((__format__(__printf__, 1, 2))) -int printf(const char *__restrict __format, ...); +__attribute__((__format__(__printf__, 1, 2))) int printf(const char *__restrict __format, ...); -__attribute__((__format__(__scanf__, 1, 2))) -int scanf(const char *__restrict __format, ...); +__attribute__((__format__(__scanf__, 1, 2))) int scanf(const char *__restrict __format, ...); -__attribute__((__format__(__printf__, 3, 4))) -int snprintf(char *__restrict __buffer, size_t __max_size, const char *__restrict __format, ...); +__attribute__((__format__(__printf__, 3, 4))) int +snprintf(char *__restrict __buffer, size_t __max_size, const char *__restrict __format, ...); -__attribute__((__format__(__printf__, 2, 3))) -int sprintf(char *__restrict __buffer, const char *__restrict __format, ...); +__attribute__((__format__(__printf__, 2, 3))) int +sprintf(char *__restrict __buffer, const char *__restrict __format, ...); -__attribute__((__format__(__scanf__, 2, 3))) -int sscanf(const char *__restrict __buffer, const char *__restrict __format, ...); +__attribute__((__format__(__scanf__, 2, 3))) int +sscanf(const char *__restrict __buffer, const char *__restrict __format, ...); -__attribute__((__format__(__printf__, 2, 0))) -int vfprintf(FILE *__restrict __stream, const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__printf__, 2, 0))) int +vfprintf(FILE *__restrict __stream, const char *__restrict __format, __builtin_va_list __args); -__attribute__((__format__(__scanf__, 2, 0))) -int vfscanf(FILE *__restrict __stream, const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__scanf__, 2, 0))) int +vfscanf(FILE *__restrict __stream, const char *__restrict __format, __builtin_va_list __args); -__attribute__((__format__(__printf__, 1, 0))) -int vprintf(const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__printf__, 1, 0))) int +vprintf(const char *__restrict __format, __builtin_va_list __args); -__attribute__((__format__(__scanf__, 1, 0))) -int vscanf(const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__scanf__, 1, 0))) int +vscanf(const char *__restrict __format, __builtin_va_list __args); -__attribute__((__format__(__printf__, 3, 0))) -int vsnprintf(char *__restrict __buffer, size_t __max_size, - const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__printf__, 3, 0))) int vsnprintf( + char *__restrict __buffer, + size_t __max_size, + const char *__restrict __format, + __builtin_va_list __args +); -__attribute__((__format__(__printf__, 2, 0))) -int vsprintf(char *__restrict __buffer, const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__printf__, 2, 0))) int +vsprintf(char *__restrict __buffer, const char *__restrict __format, __builtin_va_list __args); -__attribute__((__format__(__scanf__, 2, 0))) -int vsscanf(const char *__restrict __buffer, const char *__restrict __format, __builtin_va_list __args); +__attribute__((__format__(__scanf__, 2, 0))) int +vsscanf(const char *__restrict __buffer, const char *__restrict __format, __builtin_va_list __args); /* this is a gnu extension */ -__attribute__((__format__(__printf__, 2, 0))) -int vasprintf(char **__buffer, const char *__format, __builtin_va_list __args); +__attribute__((__format__(__printf__, 2, 0))) int +vasprintf(char **__buffer, const char *__format, __builtin_va_list __args); /* [C11-7.21.7] Character input/output functions */ @@ -166,7 +169,8 @@ int ungetc(int __c, FILE *__stream); /* [C11-7.21.8] Direct input/output functions */ size_t fread(void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream); -size_t fwrite(const void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream); +size_t +fwrite(const void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream); /* [C11-7.21.9] File positioning functions */ @@ -195,8 +199,8 @@ int putchar_unlocked(int __c); ssize_t getline(char **__linep, size_t *__sizep, FILE *__stream); ssize_t getdelim(char **__linep, size_t *__sizep, int __delim, FILE *__stream); -__attribute__((__format__(__printf__, 2, 3))) -int asprintf(char **__buffer, const char *__format, ...); +__attribute__((__format__(__printf__, 2, 3))) int +asprintf(char **__buffer, const char *__format, ...); /* Linux unlocked I/O extensions. */ @@ -211,8 +215,11 @@ int fileno_unlocked(FILE *__stream); int fflush_unlocked(FILE *__stream); int fgetc_unlocked(FILE *__stream); int fputc_unlocked(int __c, FILE *__stream); -size_t fread_unlocked(void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream); -size_t fwrite_unlocked(const void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream); +size_t +fread_unlocked(void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream); +size_t fwrite_unlocked( + const void *__restrict __buffer, size_t __size, size_t __count, FILE *__restrict __stream +); char *fgets_unlocked(char *__restrict __buffer, int __size, FILE *__restrict __stream); int fputs_unlocked(const char *__restrict __buffer, FILE *__restrict __stream); @@ -224,8 +231,7 @@ int fputs_unlocked(const char *__restrict __buffer, FILE *__restrict __stream); #endif #if __MLIBC_POSIX_OPTION -# include +#include #endif #endif /* _STDIO_H */ - diff --git a/options/ansi/include/stdlib.h b/options/ansi/include/stdlib.h index 7a8564ab4e..6f62e1bfaf 100644 --- a/options/ansi/include/stdlib.h +++ b/options/ansi/include/stdlib.h @@ -1,12 +1,12 @@ #ifndef _STDLIB_H #define _STDLIB_H -#include -#include #include +#include #include #include #include +#include #ifdef __cplusplus extern "C" { @@ -82,13 +82,23 @@ char *mktemp(char *__pattern); /* [7.22.5] Searching and sorting utilities */ -void *bsearch(const void *__key, const void *__base, size_t __count, size_t __size, - int (*__compare)(const void *__a, const void *__b)); -void qsort(void *__base, size_t __count, size_t __size, - int (*__compare)(const void *__a, const void *__b)); -void qsort_r(void *__base, size_t __nmemb, size_t __size, - int (*__compar)(const void *__a, const void *__b, void *__arg), - void *__arg); +void *bsearch( + const void *__key, + const void *__base, + size_t __count, + size_t __size, + int (*__compare)(const void *__a, const void *__b) +); +void qsort( + void *__base, size_t __count, size_t __size, int (*__compare)(const void *__a, const void *__b) +); +void qsort_r( + void *__base, + size_t __nmemb, + size_t __size, + int (*__compar)(const void *__a, const void *__b, void *__arg), + void *__arg +); /* [7.22.6] Integer arithmetic functions */ @@ -108,13 +118,15 @@ int wctomb(char *__mb_chr, wchar_t __wc); /* [7.22.8] Multibyte string conversion functions */ -size_t mbstowcs(wchar_t *__restrict __wc_string, const char *__restrict __mb_string, size_t __max_size); -size_t wcstombs(char *__restrict __mb_string, const wchar_t *__restrict __wc_string, size_t __max_size); +size_t +mbstowcs(wchar_t *__restrict __wc_string, const char *__restrict __mb_string, size_t __max_size); +size_t +wcstombs(char *__restrict __mb_string, const wchar_t *__restrict __wc_string, size_t __max_size); #endif /* !__MLIBC_ABI_ONLY */ #if __MLIBC_GLIBC_OPTION -typedef int (*comparison_fn_t) (const void *__a, const void *__b); +typedef int (*comparison_fn_t)(const void *__a, const void *__b); #endif #ifdef __cplusplus @@ -122,8 +134,7 @@ typedef int (*comparison_fn_t) (const void *__a, const void *__b); #endif #if __MLIBC_POSIX_OPTION -# include +#include #endif #endif /* _STDLIB_H */ - diff --git a/options/ansi/include/string.h b/options/ansi/include/string.h index 00b15cd4d4..09d6fabe72 100644 --- a/options/ansi/include/string.h +++ b/options/ansi/include/string.h @@ -1,9 +1,9 @@ #ifndef _STRING_H #define _STRING_H -#include #include #include +#include #ifdef __cplusplus extern "C" { @@ -43,7 +43,7 @@ char *strstr(const char *__pattern, const char *__s); char *strtok(char *__restrict __s, const char *__restrict __delimiter); /* This is a GNU extension. */ -char *strchrnul(const char * __s, int __c); +char *strchrnul(const char *__s, int __c); /* [7.24.6] Miscellaneous functions */ @@ -67,7 +67,8 @@ void *mempcpy(void *__dest, const void *__src, size_t __size); int strverscmp(const char *__l0, const char *__r0); int ffsl(long __i); int ffsll(long long __i); -void *memmem(const void *__haystack, size_t __haystacklen, const void *__needle, size_t __needlelen); +void * +memmem(const void *__haystack, size_t __haystacklen, const void *__needle, size_t __needlelen); /* Handling the basename mess: * If is included *at all*, we use the XPG-defined basename @@ -78,18 +79,16 @@ void *memmem(const void *__haystack, size_t __haystacklen, const void *__needle, #if __MLIBC_GLIBC_OPTION && defined(_GNU_SOURCE) && !defined(basename) char *__mlibc_gnu_basename_c(const char *__path); -# ifdef __cplusplus +#ifdef __cplusplus extern "C++" { static inline const char *__mlibc_gnu_basename(const char *__path) { return __mlibc_gnu_basename_c(__path); } -static inline char *__mlibc_gnu_basename(char *__path) { - return __mlibc_gnu_basename_c(__path); -} +static inline char *__mlibc_gnu_basename(char *__path) { return __mlibc_gnu_basename_c(__path); } } -# else -# define __mlibc_gnu_basename __mlibc_gnu_basename_c -# endif +#else +#define __mlibc_gnu_basename __mlibc_gnu_basename_c +#endif #define basename __mlibc_gnu_basename #endif @@ -101,7 +100,7 @@ static inline char *__mlibc_gnu_basename(char *__path) { #endif #if __MLIBC_POSIX_OPTION -# include +#include #endif #endif /* _STRING_H */ diff --git a/options/ansi/include/threads.h b/options/ansi/include/threads.h index dab2c9b256..5543932b5e 100644 --- a/options/ansi/include/threads.h +++ b/options/ansi/include/threads.h @@ -7,19 +7,9 @@ extern "C" { #include -enum { - mtx_plain, - mtx_recursive, - mtx_timed -}; - -enum { - thrd_success, - thrd_timedout, - thrd_busy, - thrd_error, - thrd_nomem -}; +enum { mtx_plain, mtx_recursive, mtx_timed }; + +enum { thrd_success, thrd_timedout, thrd_busy, thrd_error, thrd_nomem }; typedef struct __mlibc_thread_data *thrd_t; typedef struct __mlibc_mutex mtx_t; @@ -28,7 +18,7 @@ typedef struct __mlibc_cond cnd_t; #define thread_local _Thread_local #endif -typedef int (*thrd_start_t)(void* __arg); +typedef int (*thrd_start_t)(void *__arg); #ifndef __MLIBC_ABI_ONLY @@ -58,4 +48,3 @@ int cnd_wait(cnd_t *__cond, mtx_t *__mtx); #endif #endif /* _THREADS_H */ - diff --git a/options/ansi/include/time.h b/options/ansi/include/time.h index 627dfc2313..2d801a0711 100644 --- a/options/ansi/include/time.h +++ b/options/ansi/include/time.h @@ -1,10 +1,10 @@ #ifndef _TIME_H #define _TIME_H -#include -#include #include #include +#include +#include #include /* [7.27.1] Components of time */ @@ -65,8 +65,12 @@ char *ctime(const time_t *__timer); struct tm *gmtime(const time_t *__timer); struct tm *gmtime_r(const time_t *__restrict __timer, struct tm *__restrict __result); struct tm *localtime(const time_t *__timer); -size_t strftime(char *__restrict __dest, size_t __max_size, - const char *__restrict __format, const struct tm *__restrict __ptr); +size_t strftime( + char *__restrict __dest, + size_t __max_size, + const char *__restrict __format, + const struct tm *__restrict __ptr +); void tzset(void); @@ -79,8 +83,8 @@ void tzset(void); /* POSIX extensions. */ #if __MLIBC_POSIX_OPTION -# include -# include +#include +#include #endif /* __MLIBC_POSIX_OPTION */ #include @@ -101,7 +105,9 @@ int nanosleep(const struct timespec *__req, struct timespec *__rem); int clock_getres(clockid_t __clockid, struct timespec *__res); int clock_gettime(clockid_t __clockid, struct timespec *__res); -int clock_nanosleep(clockid_t __clockid, int __flags, const struct timespec *__req, struct timespec *__rem); +int clock_nanosleep( + clockid_t __clockid, int __flags, const struct timespec *__req, struct timespec *__rem +); int clock_settime(clockid_t __clockid, const struct timespec *__time); struct tm *localtime_r(const time_t *__timer, struct tm *__buf); @@ -109,8 +115,8 @@ char *asctime_r(const struct tm *__tm, char *__buf); char *ctime_r(const time_t *__timer, char *__buf); #if __MLIBC_POSIX_OPTION -char *strptime(const char *__restrict __buf, const char *__restrict __format, - struct tm *__restrict __tm); +char * +strptime(const char *__restrict __buf, const char *__restrict __format, struct tm *__restrict __tm); #endif /* __MLIBC_POSIX_OPTION */ #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/ansi/include/wchar.h b/options/ansi/include/wchar.h index 3921e5fa8e..90f8172538 100644 --- a/options/ansi/include/wchar.h +++ b/options/ansi/include/wchar.h @@ -1,13 +1,13 @@ #ifndef _WCHAR_H #define _WCHAR_H +#include +#include #include #include -#include #include +#include #include -#include -#include #define WEOF 0xffffffffU @@ -23,13 +23,23 @@ extern "C" { int fwprintf(FILE *__restrict __stream, const wchar_t *__restrict __format, ...); int fwscanf(FILE *__restrict __stream, const wchar_t *__restrict __format, ...); -int vfwprintf(FILE *__restrict __stream, const wchar_t *__restrict __format, __builtin_va_list __args); -int vfwscanf(FILE *__restrict __stream, const wchar_t *__restrict __format, __builtin_va_list __args); +int +vfwprintf(FILE *__restrict __stream, const wchar_t *__restrict __format, __builtin_va_list __args); +int +vfwscanf(FILE *__restrict __stream, const wchar_t *__restrict __format, __builtin_va_list __args); -int swprintf(wchar_t *__restrict __buffer, size_t __max_size, const wchar_t *__restrict __format, ...); +int +swprintf(wchar_t *__restrict __buffer, size_t __max_size, const wchar_t *__restrict __format, ...); int swscanf(wchar_t *__restrict __buffer, const wchar_t *__restrict __format, ...); -int vswprintf(wchar_t *__restrict __buffer, size_t __max_size, const wchar_t *__restrict __format, __builtin_va_list __args); -int vswscanf(wchar_t *__restrict __buffer, const wchar_t *__restrict __format, __builtin_va_list __args); +int vswprintf( + wchar_t *__restrict __buffer, + size_t __max_size, + const wchar_t *__restrict __format, + __builtin_va_list __args +); +int vswscanf( + wchar_t *__restrict __buffer, const wchar_t *__restrict __format, __builtin_va_list __args +); int wprintf(const wchar_t *__restrict __format, ...); int wscanf(const wchar_t *__restrict __format, ...); @@ -58,7 +68,8 @@ long double wcstold(const wchar_t *__restrict __nptr, wchar_t **__restrict __end long wcstol(const wchar_t *__restrict __nptr, wchar_t **__restrict __endptr, int __base); long long wcstoll(const wchar_t *__restrict __nptr, wchar_t **__restrict __endptr, int __base); unsigned long wcstoul(const wchar_t *__restrict __nptr, wchar_t **__restrict __endptr, int __base); -unsigned long long wcstoull(const wchar_t *__restrict __nptr, wchar_t **__restrict __endptr, int __base); +unsigned long long +wcstoull(const wchar_t *__restrict __nptr, wchar_t **__restrict __endptr, int __base); wchar_t *wcscpy(wchar_t *__restrict __dest, const wchar_t *__restrict __src); wchar_t *wcsncpy(wchar_t *__restrict __dest, const wchar_t *__restrict __src, size_t __size); @@ -80,7 +91,8 @@ wchar_t *wcspbrk(const wchar_t *__s, const wchar_t *__wchrs); wchar_t *wcsrchr(const wchar_t *__s, wchar_t __wc); size_t wcsspn(const wchar_t *__s, const wchar_t *__wchrs); wchar_t *wcsstr(const wchar_t *__s, const wchar_t *__b); -wchar_t *wcstok(wchar_t *__restrict __s, const wchar_t *__restrict __delimiter, wchar_t **__restrict __ptr); +wchar_t * +wcstok(wchar_t *__restrict __s, const wchar_t *__restrict __delimiter, wchar_t **__restrict __ptr); wchar_t *wmemchr(const wchar_t *__s, wchar_t __wc, size_t __size); size_t wcslen(const wchar_t *__s); @@ -92,8 +104,12 @@ wchar_t *wmemset(wchar_t *__dest, wchar_t __wc, size_t __size); * The tag tm is declared as naming an incomplete structure type, the contents of which are * described in the header . */ struct tm; -size_t wcsftime(wchar_t *__restrict __buffer, size_t __max_size, const wchar_t *__restrict __format, - const struct tm *__restrict __time); +size_t wcsftime( + wchar_t *__restrict __buffer, + size_t __max_size, + const wchar_t *__restrict __format, + const struct tm *__restrict __time +); /* [7.28.6] Wide conversion functions */ @@ -102,14 +118,39 @@ int wctob(wint_t __wc); int mbsinit(const mbstate_t *__state); size_t mbrlen(const char *__restrict __mbs, size_t __mbs_limit, mbstate_t *__restrict __stp); -size_t mbrtowc(wchar_t *__restrict __wcp, const char *__restrict __mbs, size_t __mbs_limit, mbstate_t *__restrict __stp); +size_t mbrtowc( + wchar_t *__restrict __wcp, + const char *__restrict __mbs, + size_t __mbs_limit, + mbstate_t *__restrict __stp +); size_t wcrtomb(char *__restrict __mbs, wchar_t __wc, mbstate_t *__restrict __stp); -size_t mbsrtowcs(wchar_t *__restrict __wcs, const char **__restrict __mbs, size_t __mb_limit, mbstate_t *__restrict __stp); -size_t mbsnrtowcs(wchar_t *__restrict __wcs, const char **__restrict __mbs, size_t __mb_limit, size_t __wc_limit, - mbstate_t *__restrict __stp); -size_t wcsrtombs(char *__restrict __mbs, const wchar_t **__restrict __wcs, size_t __mb_limit, mbstate_t *__restrict __stp); -size_t wcsnrtombs(char *__restrict __mbs, const wchar_t **__restrict __wcs, size_t __mb_limit, size_t __wc_limit, - mbstate_t *__restrict __stp); +size_t mbsrtowcs( + wchar_t *__restrict __wcs, + const char **__restrict __mbs, + size_t __mb_limit, + mbstate_t *__restrict __stp +); +size_t mbsnrtowcs( + wchar_t *__restrict __wcs, + const char **__restrict __mbs, + size_t __mb_limit, + size_t __wc_limit, + mbstate_t *__restrict __stp +); +size_t wcsrtombs( + char *__restrict __mbs, + const wchar_t **__restrict __wcs, + size_t __mb_limit, + mbstate_t *__restrict __stp +); +size_t wcsnrtombs( + char *__restrict __mbs, + const wchar_t **__restrict __wcs, + size_t __mb_limit, + size_t __wc_limit, + mbstate_t *__restrict __stp +); /* POSIX extensions */ int wcwidth(wchar_t __wc); diff --git a/options/ansi/include/wctype.h b/options/ansi/include/wctype.h index ab66f15662..0bbf499d6d 100644 --- a/options/ansi/include/wctype.h +++ b/options/ansi/include/wctype.h @@ -1,10 +1,10 @@ #ifndef _WCTYPE_H #define _WCTYPE_H -#include -#include -#include #include +#include +#include +#include #ifdef __cplusplus extern "C" { @@ -45,7 +45,7 @@ wint_t towctrans(wint_t __wc, wctrans_t __trans); #endif #if __MLIBC_POSIX_OPTION -# include +#include #endif #endif /* _WCTYPE_H */ diff --git a/options/bsd/generic/arpa-nameser.cpp b/options/bsd/generic/arpa-nameser.cpp index e89f2bb39b..3b938091c1 100644 --- a/options/bsd/generic/arpa-nameser.cpp +++ b/options/bsd/generic/arpa-nameser.cpp @@ -1,12 +1,10 @@ -#include #include #include +#include #include // The ns_get* and ns_put* functions are taken from musl. -unsigned ns_get16(const unsigned char *cp) { - return cp[0] << 8 | cp[1]; -} +unsigned ns_get16(const unsigned char *cp) { return cp[0] << 8 | cp[1]; } unsigned long ns_get32(const unsigned char *cp) { return (unsigned)cp[0] << 24 | cp[1] << 16 | cp[2] << 8 | cp[3]; @@ -34,8 +32,9 @@ int ns_parserr(ns_msg *, ns_sect, int, ns_rr *) { __builtin_unreachable(); } -int ns_name_uncompress(const unsigned char *, const unsigned char *, - const unsigned char *, char *, size_t) { +int ns_name_uncompress( + const unsigned char *, const unsigned char *, const unsigned char *, char *, size_t +) { __ensure(!"Not implemented"); __builtin_unreachable(); } diff --git a/options/bsd/generic/ether.cpp b/options/bsd/generic/ether.cpp index 0ff0cd9eec..68610a4a84 100644 --- a/options/bsd/generic/ether.cpp +++ b/options/bsd/generic/ether.cpp @@ -1,16 +1,16 @@ -#include #include #include +#include char *ether_ntoa(const struct ether_addr *addr) { static char x[18]; - return ether_ntoa_r (addr, x); + return ether_ntoa_r(addr, x); } char *ether_ntoa_r(const struct ether_addr *addr, char *buf) { char *orig_ptr = buf; - for(int i = 0; i < ETH_ALEN; i++) { + for (int i = 0; i < ETH_ALEN; i++) { buf += sprintf(buf, i == 0 ? "%.2X" : ":%.2X", addr->ether_addr_octet[i]); } diff --git a/options/bsd/include/arpa/nameser.h b/options/bsd/include/arpa/nameser.h index 7e2e9f1910..2fb93f2adf 100644 --- a/options/bsd/include/arpa/nameser.h +++ b/options/bsd/include/arpa/nameser.h @@ -1,8 +1,8 @@ #ifndef _ARPA_NAMESER_H #define _ARPA_NAMESER_H -#include #include +#include #ifdef __cplusplus extern "C" { @@ -12,7 +12,7 @@ extern "C" { #define NS_MAXDNAME 1025 #define NS_MAXLABEL 63 -typedef enum __ns_rcode { +typedef enum __ns_rcode { ns_r_noerror = 0, ns_r_formerr = 1, ns_r_servfail = 2, @@ -109,12 +109,12 @@ typedef enum __ns_sect { } ns_sect; typedef struct __ns_msg { - const unsigned char *_msg, *_eom; + const unsigned char *_msg, *_eom; uint16_t _id, _flags, _counts[ns_s_max]; - const unsigned char *_sections[ns_s_max]; + const unsigned char *_sections[ns_s_max]; ns_sect _sect; int _rrnum; - const unsigned char *_msg_ptr; + const unsigned char *_msg_ptr; } ns_msg; #define ns_msg_id(handle) ((handle)._id + 0) @@ -123,7 +123,7 @@ typedef struct __ns_msg { #define ns_msg_size(handle) ((handle)._eom - (handle)._msg) #define ns_msg_count(handle, section) ((handle)._counts[section] + 0) -typedef struct __ns_rr { +typedef struct __ns_rr { char name[NS_MAXDNAME]; uint16_t type; uint16_t rr_class; @@ -132,12 +132,12 @@ typedef struct __ns_rr { const unsigned char *rdata; } ns_rr; -#define ns_rr_name(rr) (((rr).name[0] != '\0') ? (rr).name : ".") -#define ns_rr_type(rr) ((ns_type)((rr).type + 0)) -#define ns_rr_class(rr) ((ns_class)((rr).rr_class + 0)) -#define ns_rr_ttl(rr) ((rr).ttl + 0) -#define ns_rr_rdlen(rr) ((rr).rdlength + 0) -#define ns_rr_rdata(rr) ((rr).rdata + 0) +#define ns_rr_name(rr) (((rr).name[0] != '\0') ? (rr).name : ".") +#define ns_rr_type(rr) ((ns_type)((rr).type + 0)) +#define ns_rr_class(rr) ((ns_class)((rr).rr_class + 0)) +#define ns_rr_ttl(rr) ((rr).ttl + 0) +#define ns_rr_rdlen(rr) ((rr).rdlength + 0) +#define ns_rr_rdata(rr) ((rr).rdata + 0) #ifndef __MLIBC_ABI_ONLY @@ -153,111 +153,116 @@ void ns_put32(unsigned long __value, unsigned char *__src); int ns_initparse(const unsigned char *__msg, int __msglen, ns_msg *__handle); int ns_parserr(ns_msg *__msg, ns_sect __section, int __rrnum, ns_rr *__rr); -int ns_name_uncompress(const unsigned char *__msg, const unsigned char *__eom, - const unsigned char *__src, char *__dst, size_t __dstsize); +int ns_name_uncompress( + const unsigned char *__msg, + const unsigned char *__eom, + const unsigned char *__src, + char *__dst, + size_t __dstsize +); #endif /* !__MLIBC_ABI_ONLY */ typedef struct { - unsigned id :16; + unsigned id : 16; #if __BYTE_ORDER == __BIG_ENDIAN - unsigned qr: 1; - unsigned opcode: 4; - unsigned aa: 1; - unsigned tc: 1; - unsigned rd: 1; - unsigned ra: 1; - unsigned unused :1; - unsigned ad: 1; - unsigned cd: 1; - unsigned rcode :4; + unsigned qr : 1; + unsigned opcode : 4; + unsigned aa : 1; + unsigned tc : 1; + unsigned rd : 1; + unsigned ra : 1; + unsigned unused : 1; + unsigned ad : 1; + unsigned cd : 1; + unsigned rcode : 4; #else - unsigned rd :1; - unsigned tc :1; - unsigned aa :1; - unsigned opcode :4; - unsigned qr :1; - unsigned rcode :4; - unsigned cd: 1; - unsigned ad: 1; - unsigned unused :1; - unsigned ra :1; + unsigned rd : 1; + unsigned tc : 1; + unsigned aa : 1; + unsigned opcode : 4; + unsigned qr : 1; + unsigned rcode : 4; + unsigned cd : 1; + unsigned ad : 1; + unsigned unused : 1; + unsigned ra : 1; #endif - unsigned qdcount :16; - unsigned ancount :16; - unsigned nscount :16; - unsigned arcount :16; + unsigned qdcount : 16; + unsigned ancount : 16; + unsigned nscount : 16; + unsigned arcount : 16; } HEADER; -#define PACKETSZ NS_PACKETSZ -#define MAXDNAME NS_MAXDNAME +#define PACKETSZ NS_PACKETSZ +#define MAXDNAME NS_MAXDNAME -#define NOERROR ns_r_noerror -#define FORMERR ns_r_formerr -#define SERVFAIL ns_r_servfail -#define NXDOMAIN ns_r_nxdomain -#define NOTIMP ns_r_notimpl -#define REFUSED ns_r_refused -#define YXDOMAIN ns_r_yxdomain -#define YXRRSET ns_r_yxrrset -#define NXRRSET ns_r_nxrrset -#define NOTAUTH ns_r_notauth -#define NOTZONE ns_r_notzone +#define NOERROR ns_r_noerror +#define FORMERR ns_r_formerr +#define SERVFAIL ns_r_servfail +#define NXDOMAIN ns_r_nxdomain +#define NOTIMP ns_r_notimpl +#define REFUSED ns_r_refused +#define YXDOMAIN ns_r_yxdomain +#define YXRRSET ns_r_yxrrset +#define NXRRSET ns_r_nxrrset +#define NOTAUTH ns_r_notauth +#define NOTZONE ns_r_notzone -#define T_A ns_t_a -#define T_NS ns_t_ns -#define T_MD ns_t_md -#define T_MF ns_t_mf -#define T_CNAME ns_t_cname -#define T_SOA ns_t_soa -#define T_MB ns_t_mb -#define T_MG ns_t_mg -#define T_MR ns_t_mr -#define T_NULL ns_t_null -#define T_WKS ns_t_wks -#define T_PTR ns_t_ptr -#define T_HINFO ns_t_hinfo -#define T_MINFO ns_t_minfo -#define T_MX ns_t_mx -#define T_TXT ns_t_txt -#define T_RP ns_t_rp -#define T_AFSDB ns_t_afsdb -#define T_X25 ns_t_x25 -#define T_ISDN ns_t_isdn -#define T_RT ns_t_rt -#define T_NSAP ns_t_nsap -#define T_NSAP_PTR ns_t_nsap_ptr -#define T_SIG ns_t_sig -#define T_KEY ns_t_key -#define T_PX ns_t_px -#define T_GPOS ns_t_gpos -#define T_AAAA ns_t_aaaa -#define T_LOC ns_t_loc -#define T_NXT ns_t_nxt -#define T_EID ns_t_eid -#define T_NIMLOC ns_t_nimloc -#define T_SRV ns_t_srv -#define T_ATMA ns_t_atma -#define T_NAPTR ns_t_naptr -#define T_A6 ns_t_a6 -#define T_DNAME ns_t_dname -#define T_TSIG ns_t_tsig -#define T_IXFR ns_t_ixfr -#define T_AXFR ns_t_axfr -#define T_MAILB ns_t_mailb -#define T_MAILA ns_t_maila -#define T_ANY ns_t_any +#define T_A ns_t_a +#define T_NS ns_t_ns +#define T_MD ns_t_md +#define T_MF ns_t_mf +#define T_CNAME ns_t_cname +#define T_SOA ns_t_soa +#define T_MB ns_t_mb +#define T_MG ns_t_mg +#define T_MR ns_t_mr +#define T_NULL ns_t_null +#define T_WKS ns_t_wks +#define T_PTR ns_t_ptr +#define T_HINFO ns_t_hinfo +#define T_MINFO ns_t_minfo +#define T_MX ns_t_mx +#define T_TXT ns_t_txt +#define T_RP ns_t_rp +#define T_AFSDB ns_t_afsdb +#define T_X25 ns_t_x25 +#define T_ISDN ns_t_isdn +#define T_RT ns_t_rt +#define T_NSAP ns_t_nsap +#define T_NSAP_PTR ns_t_nsap_ptr +#define T_SIG ns_t_sig +#define T_KEY ns_t_key +#define T_PX ns_t_px +#define T_GPOS ns_t_gpos +#define T_AAAA ns_t_aaaa +#define T_LOC ns_t_loc +#define T_NXT ns_t_nxt +#define T_EID ns_t_eid +#define T_NIMLOC ns_t_nimloc +#define T_SRV ns_t_srv +#define T_ATMA ns_t_atma +#define T_NAPTR ns_t_naptr +#define T_A6 ns_t_a6 +#define T_DNAME ns_t_dname +#define T_TSIG ns_t_tsig +#define T_IXFR ns_t_ixfr +#define T_AXFR ns_t_axfr +#define T_MAILB ns_t_mailb +#define T_MAILA ns_t_maila +#define T_ANY ns_t_any -#define C_IN ns_c_in -#define C_CHAOS ns_c_chaos -#define C_HS ns_c_hs -#define C_NONE ns_c_none -#define C_ANY ns_c_any +#define C_IN ns_c_in +#define C_CHAOS ns_c_chaos +#define C_HS ns_c_hs +#define C_NONE ns_c_none +#define C_ANY ns_c_any -#define GETSHORT NS_GET16 -#define GETLONG NS_GET32 -#define PUTSHORT NS_PUT16 -#define PUTLONG NS_PUT32 +#define GETSHORT NS_GET16 +#define GETLONG NS_GET32 +#define PUTSHORT NS_PUT16 +#define PUTLONG NS_PUT32 #ifdef __cplusplus } diff --git a/options/bsd/include/sys/queue.h b/options/bsd/include/sys/queue.h index 219066bdd0..b95f149b01 100644 --- a/options/bsd/include/sys/queue.h +++ b/options/bsd/include/sys/queue.h @@ -29,8 +29,8 @@ * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ -#ifndef _SYS_QUEUE_H_ -#define _SYS_QUEUE_H_ +#ifndef _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ /* * This file defines five types of data structures: singly-linked lists, @@ -81,494 +81,490 @@ /* * List definitions. */ -#define LIST_HEAD(name, type) \ -struct name { \ - struct type *lh_first; /* first element */ \ -} +#define LIST_HEAD(name, type) \ + struct name { \ + struct type *lh_first; /* first element */ \ + } -#define LIST_HEAD_INITIALIZER(head) \ - { NULL } +#define LIST_HEAD_INITIALIZER(head) {NULL} -#define LIST_ENTRY(type) \ -struct { \ - struct type *le_next; /* next element */ \ - struct type **le_prev; /* address of previous next element */ \ -} +#define LIST_ENTRY(type) \ + struct { \ + struct type *le_next; /* next element */ \ + struct type **le_prev; /* address of previous next element */ \ + } /* * List functions. */ -#define LIST_INIT(head) do { \ - (head)->lh_first = NULL; \ -} while (0) - -#define LIST_INSERT_AFTER(listelm, elm, field) do { \ - if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ - (listelm)->field.le_next->field.le_prev = \ - &(elm)->field.le_next; \ - (listelm)->field.le_next = (elm); \ - (elm)->field.le_prev = &(listelm)->field.le_next; \ -} while (0) - -#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ - (elm)->field.le_prev = (listelm)->field.le_prev; \ - (elm)->field.le_next = (listelm); \ - *(listelm)->field.le_prev = (elm); \ - (listelm)->field.le_prev = &(elm)->field.le_next; \ -} while (0) - -#define LIST_INSERT_HEAD(head, elm, field) do { \ - if (((elm)->field.le_next = (head)->lh_first) != NULL) \ - (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ - (head)->lh_first = (elm); \ - (elm)->field.le_prev = &(head)->lh_first; \ -} while (0) - -#define LIST_REMOVE(elm, field) do { \ - if ((elm)->field.le_next != NULL) \ - (elm)->field.le_next->field.le_prev = \ - (elm)->field.le_prev; \ - *(elm)->field.le_prev = (elm)->field.le_next; \ -} while (0) - -#define LIST_FOREACH(var, head, field) \ - for ((var) = ((head)->lh_first); \ - (var); \ - (var) = ((var)->field.le_next)) +#define LIST_INIT(head) \ + do { \ + (head)->lh_first = NULL; \ + } while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) \ + do { \ + if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ + (listelm)->field.le_next->field.le_prev = &(elm)->field.le_next; \ + (listelm)->field.le_next = (elm); \ + (elm)->field.le_prev = &(listelm)->field.le_next; \ + } while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) \ + do { \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + (elm)->field.le_next = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &(elm)->field.le_next; \ + } while (0) + +#define LIST_INSERT_HEAD(head, elm, field) \ + do { \ + if (((elm)->field.le_next = (head)->lh_first) != NULL) \ + (head)->lh_first->field.le_prev = &(elm)->field.le_next; \ + (head)->lh_first = (elm); \ + (elm)->field.le_prev = &(head)->lh_first; \ + } while (0) + +#define LIST_REMOVE(elm, field) \ + do { \ + if ((elm)->field.le_next != NULL) \ + (elm)->field.le_next->field.le_prev = (elm)->field.le_prev; \ + *(elm)->field.le_prev = (elm)->field.le_next; \ + } while (0) + +#define LIST_FOREACH(var, head, field) \ + for ((var) = ((head)->lh_first); (var); (var) = ((var)->field.le_next)) /* * List access methods. */ -#define LIST_EMPTY(head) ((head)->lh_first == NULL) -#define LIST_FIRST(head) ((head)->lh_first) -#define LIST_NEXT(elm, field) ((elm)->field.le_next) - +#define LIST_EMPTY(head) ((head)->lh_first == NULL) +#define LIST_FIRST(head) ((head)->lh_first) +#define LIST_NEXT(elm, field) ((elm)->field.le_next) /* * Singly-linked List definitions. */ -#define SLIST_HEAD(name, type) \ -struct name { \ - struct type *slh_first; /* first element */ \ -} +#define SLIST_HEAD(name, type) \ + struct name { \ + struct type *slh_first; /* first element */ \ + } -#define SLIST_HEAD_INITIALIZER(head) \ - { NULL } +#define SLIST_HEAD_INITIALIZER(head) {NULL} -#define SLIST_ENTRY(type) \ -struct { \ - struct type *sle_next; /* next element */ \ -} +#define SLIST_ENTRY(type) \ + struct { \ + struct type *sle_next; /* next element */ \ + } /* * Singly-linked List functions. */ -#define SLIST_INIT(head) do { \ - (head)->slh_first = NULL; \ -} while (0) - -#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ - (elm)->field.sle_next = (slistelm)->field.sle_next; \ - (slistelm)->field.sle_next = (elm); \ -} while (0) - -#define SLIST_INSERT_HEAD(head, elm, field) do { \ - (elm)->field.sle_next = (head)->slh_first; \ - (head)->slh_first = (elm); \ -} while (0) - -#define SLIST_REMOVE_HEAD(head, field) do { \ - (head)->slh_first = (head)->slh_first->field.sle_next; \ -} while (0) - -#define SLIST_REMOVE(head, elm, type, field) do { \ - if ((head)->slh_first == (elm)) { \ - SLIST_REMOVE_HEAD((head), field); \ - } \ - else { \ - struct type *curelm = (head)->slh_first; \ - while(curelm->field.sle_next != (elm)) \ - curelm = curelm->field.sle_next; \ - curelm->field.sle_next = \ - curelm->field.sle_next->field.sle_next; \ - } \ -} while (0) - -#define SLIST_FOREACH(var, head, field) \ - for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) +#define SLIST_INIT(head) \ + do { \ + (head)->slh_first = NULL; \ + } while (0) + +#define SLIST_INSERT_AFTER(slistelm, elm, field) \ + do { \ + (elm)->field.sle_next = (slistelm)->field.sle_next; \ + (slistelm)->field.sle_next = (elm); \ + } while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) \ + do { \ + (elm)->field.sle_next = (head)->slh_first; \ + (head)->slh_first = (elm); \ + } while (0) + +#define SLIST_REMOVE_HEAD(head, field) \ + do { \ + (head)->slh_first = (head)->slh_first->field.sle_next; \ + } while (0) + +#define SLIST_REMOVE(head, elm, type, field) \ + do { \ + if ((head)->slh_first == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->slh_first; \ + while (curelm->field.sle_next != (elm)) \ + curelm = curelm->field.sle_next; \ + curelm->field.sle_next = curelm->field.sle_next->field.sle_next; \ + } \ + } while (0) + +#define SLIST_FOREACH(var, head, field) \ + for ((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) /* * Singly-linked List access methods. */ -#define SLIST_EMPTY(head) ((head)->slh_first == NULL) -#define SLIST_FIRST(head) ((head)->slh_first) -#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) - +#define SLIST_EMPTY(head) ((head)->slh_first == NULL) +#define SLIST_FIRST(head) ((head)->slh_first) +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) /* * Singly-linked Tail queue declarations. */ -#define STAILQ_HEAD(name, type) \ -struct name { \ - struct type *stqh_first; /* first element */ \ - struct type **stqh_last; /* addr of last next element */ \ -} +#define STAILQ_HEAD(name, type) \ + struct name { \ + struct type *stqh_first; /* first element */ \ + struct type **stqh_last; /* addr of last next element */ \ + } -#define STAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).stqh_first } +#define STAILQ_HEAD_INITIALIZER(head) {NULL, &(head).stqh_first} -#define STAILQ_ENTRY(type) \ -struct { \ - struct type *stqe_next; /* next element */ \ -} +#define STAILQ_ENTRY(type) \ + struct { \ + struct type *stqe_next; /* next element */ \ + } /* * Singly-linked Tail queue functions. */ -#define STAILQ_INIT(head) do { \ - (head)->stqh_first = NULL; \ - (head)->stqh_last = &(head)->stqh_first; \ -} while (0) - -#define STAILQ_INSERT_HEAD(head, elm, field) do { \ - if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \ - (head)->stqh_last = &(elm)->field.stqe_next; \ - (head)->stqh_first = (elm); \ -} while (0) - -#define STAILQ_INSERT_TAIL(head, elm, field) do { \ - (elm)->field.stqe_next = NULL; \ - *(head)->stqh_last = (elm); \ - (head)->stqh_last = &(elm)->field.stqe_next; \ -} while (0) - -#define STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ - if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL)\ - (head)->stqh_last = &(elm)->field.stqe_next; \ - (listelm)->field.stqe_next = (elm); \ -} while (0) - -#define STAILQ_REMOVE_HEAD(head, field) do { \ - if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == NULL) \ - (head)->stqh_last = &(head)->stqh_first; \ -} while (0) - -#define STAILQ_REMOVE(head, elm, type, field) do { \ - if ((head)->stqh_first == (elm)) { \ - STAILQ_REMOVE_HEAD((head), field); \ - } else { \ - struct type *curelm = (head)->stqh_first; \ - while (curelm->field.stqe_next != (elm)) \ - curelm = curelm->field.stqe_next; \ - if ((curelm->field.stqe_next = \ - curelm->field.stqe_next->field.stqe_next) == NULL) \ - (head)->stqh_last = &(curelm)->field.stqe_next; \ - } \ -} while (0) - -#define STAILQ_FOREACH(var, head, field) \ - for ((var) = ((head)->stqh_first); \ - (var); \ - (var) = ((var)->field.stqe_next)) - -#define STAILQ_CONCAT(head1, head2) do { \ - if (!STAILQ_EMPTY((head2))) { \ - *(head1)->stqh_last = (head2)->stqh_first; \ - (head1)->stqh_last = (head2)->stqh_last; \ - STAILQ_INIT((head2)); \ - } \ -} while (0) +#define STAILQ_INIT(head) \ + do { \ + (head)->stqh_first = NULL; \ + (head)->stqh_last = &(head)->stqh_first; \ + } while (0) + +#define STAILQ_INSERT_HEAD(head, elm, field) \ + do { \ + if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \ + (head)->stqh_last = &(elm)->field.stqe_next; \ + (head)->stqh_first = (elm); \ + } while (0) + +#define STAILQ_INSERT_TAIL(head, elm, field) \ + do { \ + (elm)->field.stqe_next = NULL; \ + *(head)->stqh_last = (elm); \ + (head)->stqh_last = &(elm)->field.stqe_next; \ + } while (0) + +#define STAILQ_INSERT_AFTER(head, listelm, elm, field) \ + do { \ + if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL) \ + (head)->stqh_last = &(elm)->field.stqe_next; \ + (listelm)->field.stqe_next = (elm); \ + } while (0) + +#define STAILQ_REMOVE_HEAD(head, field) \ + do { \ + if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == NULL) \ + (head)->stqh_last = &(head)->stqh_first; \ + } while (0) + +#define STAILQ_REMOVE(head, elm, type, field) \ + do { \ + if ((head)->stqh_first == (elm)) { \ + STAILQ_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->stqh_first; \ + while (curelm->field.stqe_next != (elm)) \ + curelm = curelm->field.stqe_next; \ + if ((curelm->field.stqe_next = curelm->field.stqe_next->field.stqe_next) == NULL) \ + (head)->stqh_last = &(curelm)->field.stqe_next; \ + } \ + } while (0) + +#define STAILQ_FOREACH(var, head, field) \ + for ((var) = ((head)->stqh_first); (var); (var) = ((var)->field.stqe_next)) + +#define STAILQ_CONCAT(head1, head2) \ + do { \ + if (!STAILQ_EMPTY((head2))) { \ + *(head1)->stqh_last = (head2)->stqh_first; \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_INIT((head2)); \ + } \ + } while (0) /* * Singly-linked Tail queue access methods. */ -#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) -#define STAILQ_FIRST(head) ((head)->stqh_first) -#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) - +#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) +#define STAILQ_FIRST(head) ((head)->stqh_first) +#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) /* * Simple queue definitions. */ -#define SIMPLEQ_HEAD(name, type) \ -struct name { \ - struct type *sqh_first; /* first element */ \ - struct type **sqh_last; /* addr of last next element */ \ -} +#define SIMPLEQ_HEAD(name, type) \ + struct name { \ + struct type *sqh_first; /* first element */ \ + struct type **sqh_last; /* addr of last next element */ \ + } -#define SIMPLEQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).sqh_first } +#define SIMPLEQ_HEAD_INITIALIZER(head) {NULL, &(head).sqh_first} -#define SIMPLEQ_ENTRY(type) \ -struct { \ - struct type *sqe_next; /* next element */ \ -} +#define SIMPLEQ_ENTRY(type) \ + struct { \ + struct type *sqe_next; /* next element */ \ + } /* * Simple queue functions. */ -#define SIMPLEQ_INIT(head) do { \ - (head)->sqh_first = NULL; \ - (head)->sqh_last = &(head)->sqh_first; \ -} while (0) - -#define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ - if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ - (head)->sqh_last = &(elm)->field.sqe_next; \ - (head)->sqh_first = (elm); \ -} while (0) - -#define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ - (elm)->field.sqe_next = NULL; \ - *(head)->sqh_last = (elm); \ - (head)->sqh_last = &(elm)->field.sqe_next; \ -} while (0) - -#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ - if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ - (head)->sqh_last = &(elm)->field.sqe_next; \ - (listelm)->field.sqe_next = (elm); \ -} while (0) - -#define SIMPLEQ_REMOVE_HEAD(head, field) do { \ - if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ - (head)->sqh_last = &(head)->sqh_first; \ -} while (0) - -#define SIMPLEQ_REMOVE(head, elm, type, field) do { \ - if ((head)->sqh_first == (elm)) { \ - SIMPLEQ_REMOVE_HEAD((head), field); \ - } else { \ - struct type *curelm = (head)->sqh_first; \ - while (curelm->field.sqe_next != (elm)) \ - curelm = curelm->field.sqe_next; \ - if ((curelm->field.sqe_next = \ - curelm->field.sqe_next->field.sqe_next) == NULL) \ - (head)->sqh_last = &(curelm)->field.sqe_next; \ - } \ -} while (0) - -#define SIMPLEQ_FOREACH(var, head, field) \ - for ((var) = ((head)->sqh_first); \ - (var); \ - (var) = ((var)->field.sqe_next)) +#define SIMPLEQ_INIT(head) \ + do { \ + (head)->sqh_first = NULL; \ + (head)->sqh_last = &(head)->sqh_first; \ + } while (0) + +#define SIMPLEQ_INSERT_HEAD(head, elm, field) \ + do { \ + if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ + (head)->sqh_last = &(elm)->field.sqe_next; \ + (head)->sqh_first = (elm); \ + } while (0) + +#define SIMPLEQ_INSERT_TAIL(head, elm, field) \ + do { \ + (elm)->field.sqe_next = NULL; \ + *(head)->sqh_last = (elm); \ + (head)->sqh_last = &(elm)->field.sqe_next; \ + } while (0) + +#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) \ + do { \ + if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL) \ + (head)->sqh_last = &(elm)->field.sqe_next; \ + (listelm)->field.sqe_next = (elm); \ + } while (0) + +#define SIMPLEQ_REMOVE_HEAD(head, field) \ + do { \ + if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ + (head)->sqh_last = &(head)->sqh_first; \ + } while (0) + +#define SIMPLEQ_REMOVE(head, elm, type, field) \ + do { \ + if ((head)->sqh_first == (elm)) { \ + SIMPLEQ_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->sqh_first; \ + while (curelm->field.sqe_next != (elm)) \ + curelm = curelm->field.sqe_next; \ + if ((curelm->field.sqe_next = curelm->field.sqe_next->field.sqe_next) == NULL) \ + (head)->sqh_last = &(curelm)->field.sqe_next; \ + } \ + } while (0) + +#define SIMPLEQ_FOREACH(var, head, field) \ + for ((var) = ((head)->sqh_first); (var); (var) = ((var)->field.sqe_next)) /* * Simple queue access methods. */ -#define SIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL) -#define SIMPLEQ_FIRST(head) ((head)->sqh_first) -#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) - +#define SIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL) +#define SIMPLEQ_FIRST(head) ((head)->sqh_first) +#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) /* * Tail queue definitions. */ -#define _TAILQ_HEAD(name, type, qual) \ -struct name { \ - qual type *tqh_first; /* first element */ \ - qual type *qual *tqh_last; /* addr of last next element */ \ -} -#define TAILQ_HEAD(name, type) _TAILQ_HEAD(name, struct type,) - -#define TAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).tqh_first } - -#define _TAILQ_ENTRY(type, qual) \ -struct { \ - qual type *tqe_next; /* next element */ \ - qual type *qual *tqe_prev; /* address of previous next element */\ -} -#define TAILQ_ENTRY(type) _TAILQ_ENTRY(struct type,) +#define _TAILQ_HEAD(name, type, qual) \ + struct name { \ + qual type *tqh_first; /* first element */ \ + qual type *qual *tqh_last; /* addr of last next element */ \ + } +#define TAILQ_HEAD(name, type) _TAILQ_HEAD(name, struct type, ) + +#define TAILQ_HEAD_INITIALIZER(head) {NULL, &(head).tqh_first} + +#define _TAILQ_ENTRY(type, qual) \ + struct { \ + qual type *tqe_next; /* next element */ \ + qual type *qual *tqe_prev; /* address of previous next element */ \ + } +#define TAILQ_ENTRY(type) _TAILQ_ENTRY(struct type, ) /* * Tail queue functions. */ -#define TAILQ_INIT(head) do { \ - (head)->tqh_first = NULL; \ - (head)->tqh_last = &(head)->tqh_first; \ -} while (0) - -#define TAILQ_INSERT_HEAD(head, elm, field) do { \ - if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ - (head)->tqh_first->field.tqe_prev = \ - &(elm)->field.tqe_next; \ - else \ - (head)->tqh_last = &(elm)->field.tqe_next; \ - (head)->tqh_first = (elm); \ - (elm)->field.tqe_prev = &(head)->tqh_first; \ -} while (0) - -#define TAILQ_INSERT_TAIL(head, elm, field) do { \ - (elm)->field.tqe_next = NULL; \ - (elm)->field.tqe_prev = (head)->tqh_last; \ - *(head)->tqh_last = (elm); \ - (head)->tqh_last = &(elm)->field.tqe_next; \ -} while (0) - -#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ - if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ - (elm)->field.tqe_next->field.tqe_prev = \ - &(elm)->field.tqe_next; \ - else \ - (head)->tqh_last = &(elm)->field.tqe_next; \ - (listelm)->field.tqe_next = (elm); \ - (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ -} while (0) - -#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ - (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ - (elm)->field.tqe_next = (listelm); \ - *(listelm)->field.tqe_prev = (elm); \ - (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ -} while (0) - -#define TAILQ_REMOVE(head, elm, field) do { \ - if (((elm)->field.tqe_next) != NULL) \ - (elm)->field.tqe_next->field.tqe_prev = \ - (elm)->field.tqe_prev; \ - else \ - (head)->tqh_last = (elm)->field.tqe_prev; \ - *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ -} while (0) - -#define TAILQ_FOREACH(var, head, field) \ - for ((var) = ((head)->tqh_first); \ - (var); \ - (var) = ((var)->field.tqe_next)) - -#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ - for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); \ - (var); \ - (var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last))) - -#define TAILQ_CONCAT(head1, head2, field) do { \ - if (!TAILQ_EMPTY(head2)) { \ - *(head1)->tqh_last = (head2)->tqh_first; \ - (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ - (head1)->tqh_last = (head2)->tqh_last; \ - TAILQ_INIT((head2)); \ - } \ -} while (0) +#define TAILQ_INIT(head) \ + do { \ + (head)->tqh_first = NULL; \ + (head)->tqh_last = &(head)->tqh_first; \ + } while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) \ + do { \ + if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ + (head)->tqh_first->field.tqe_prev = &(elm)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + (head)->tqh_first = (elm); \ + (elm)->field.tqe_prev = &(head)->tqh_first; \ + } while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) \ + do { \ + (elm)->field.tqe_next = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + } while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) \ + do { \ + if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL) \ + (elm)->field.tqe_next->field.tqe_prev = &(elm)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + (listelm)->field.tqe_next = (elm); \ + (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ + } while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) \ + do { \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + (elm)->field.tqe_next = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ + } while (0) + +#define TAILQ_REMOVE(head, elm, field) \ + do { \ + if (((elm)->field.tqe_next) != NULL) \ + (elm)->field.tqe_next->field.tqe_prev = (elm)->field.tqe_prev; \ + else \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ + } while (0) + +#define TAILQ_FOREACH(var, head, field) \ + for ((var) = ((head)->tqh_first); (var); (var) = ((var)->field.tqe_next)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); (var); \ + (var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last))) + +#define TAILQ_CONCAT(head1, head2, field) \ + do { \ + if (!TAILQ_EMPTY(head2)) { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + } \ + } while (0) /* * Tail queue access methods. */ -#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) -#define TAILQ_FIRST(head) ((head)->tqh_first) -#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) - -#define TAILQ_LAST(head, headname) \ - (*(((struct headname *)((head)->tqh_last))->tqh_last)) -#define TAILQ_PREV(elm, headname, field) \ - (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) +#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) +#define TAILQ_FIRST(head) ((head)->tqh_first) +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) +#define TAILQ_LAST(head, headname) (*(((struct headname *)((head)->tqh_last))->tqh_last)) +#define TAILQ_PREV(elm, headname, field) (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) /* * Circular queue definitions. */ -#define CIRCLEQ_HEAD(name, type) \ -struct name { \ - struct type *cqh_first; /* first element */ \ - struct type *cqh_last; /* last element */ \ -} +#define CIRCLEQ_HEAD(name, type) \ + struct name { \ + struct type *cqh_first; /* first element */ \ + struct type *cqh_last; /* last element */ \ + } -#define CIRCLEQ_HEAD_INITIALIZER(head) \ - { (void *)&head, (void *)&head } +#define CIRCLEQ_HEAD_INITIALIZER(head) {(void *)&head, (void *)&head} -#define CIRCLEQ_ENTRY(type) \ -struct { \ - struct type *cqe_next; /* next element */ \ - struct type *cqe_prev; /* previous element */ \ -} +#define CIRCLEQ_ENTRY(type) \ + struct { \ + struct type *cqe_next; /* next element */ \ + struct type *cqe_prev; /* previous element */ \ + } /* * Circular queue functions. */ -#define CIRCLEQ_INIT(head) do { \ - (head)->cqh_first = (void *)(head); \ - (head)->cqh_last = (void *)(head); \ -} while (0) - -#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ - (elm)->field.cqe_next = (listelm)->field.cqe_next; \ - (elm)->field.cqe_prev = (listelm); \ - if ((listelm)->field.cqe_next == (void *)(head)) \ - (head)->cqh_last = (elm); \ - else \ - (listelm)->field.cqe_next->field.cqe_prev = (elm); \ - (listelm)->field.cqe_next = (elm); \ -} while (0) - -#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \ - (elm)->field.cqe_next = (listelm); \ - (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \ - if ((listelm)->field.cqe_prev == (void *)(head)) \ - (head)->cqh_first = (elm); \ - else \ - (listelm)->field.cqe_prev->field.cqe_next = (elm); \ - (listelm)->field.cqe_prev = (elm); \ -} while (0) - -#define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \ - (elm)->field.cqe_next = (head)->cqh_first; \ - (elm)->field.cqe_prev = (void *)(head); \ - if ((head)->cqh_last == (void *)(head)) \ - (head)->cqh_last = (elm); \ - else \ - (head)->cqh_first->field.cqe_prev = (elm); \ - (head)->cqh_first = (elm); \ -} while (0) - -#define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \ - (elm)->field.cqe_next = (void *)(head); \ - (elm)->field.cqe_prev = (head)->cqh_last; \ - if ((head)->cqh_first == (void *)(head)) \ - (head)->cqh_first = (elm); \ - else \ - (head)->cqh_last->field.cqe_next = (elm); \ - (head)->cqh_last = (elm); \ -} while (0) - -#define CIRCLEQ_REMOVE(head, elm, field) do { \ - if ((elm)->field.cqe_next == (void *)(head)) \ - (head)->cqh_last = (elm)->field.cqe_prev; \ - else \ - (elm)->field.cqe_next->field.cqe_prev = \ - (elm)->field.cqe_prev; \ - if ((elm)->field.cqe_prev == (void *)(head)) \ - (head)->cqh_first = (elm)->field.cqe_next; \ - else \ - (elm)->field.cqe_prev->field.cqe_next = \ - (elm)->field.cqe_next; \ -} while (0) - -#define CIRCLEQ_FOREACH(var, head, field) \ - for ((var) = ((head)->cqh_first); \ - (var) != (const void *)(head); \ - (var) = ((var)->field.cqe_next)) - -#define CIRCLEQ_FOREACH_REVERSE(var, head, field) \ - for ((var) = ((head)->cqh_last); \ - (var) != (const void *)(head); \ - (var) = ((var)->field.cqe_prev)) +#define CIRCLEQ_INIT(head) \ + do { \ + (head)->cqh_first = (void *)(head); \ + (head)->cqh_last = (void *)(head); \ + } while (0) + +#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) \ + do { \ + (elm)->field.cqe_next = (listelm)->field.cqe_next; \ + (elm)->field.cqe_prev = (listelm); \ + if ((listelm)->field.cqe_next == (void *)(head)) \ + (head)->cqh_last = (elm); \ + else \ + (listelm)->field.cqe_next->field.cqe_prev = (elm); \ + (listelm)->field.cqe_next = (elm); \ + } while (0) + +#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) \ + do { \ + (elm)->field.cqe_next = (listelm); \ + (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \ + if ((listelm)->field.cqe_prev == (void *)(head)) \ + (head)->cqh_first = (elm); \ + else \ + (listelm)->field.cqe_prev->field.cqe_next = (elm); \ + (listelm)->field.cqe_prev = (elm); \ + } while (0) + +#define CIRCLEQ_INSERT_HEAD(head, elm, field) \ + do { \ + (elm)->field.cqe_next = (head)->cqh_first; \ + (elm)->field.cqe_prev = (void *)(head); \ + if ((head)->cqh_last == (void *)(head)) \ + (head)->cqh_last = (elm); \ + else \ + (head)->cqh_first->field.cqe_prev = (elm); \ + (head)->cqh_first = (elm); \ + } while (0) + +#define CIRCLEQ_INSERT_TAIL(head, elm, field) \ + do { \ + (elm)->field.cqe_next = (void *)(head); \ + (elm)->field.cqe_prev = (head)->cqh_last; \ + if ((head)->cqh_first == (void *)(head)) \ + (head)->cqh_first = (elm); \ + else \ + (head)->cqh_last->field.cqe_next = (elm); \ + (head)->cqh_last = (elm); \ + } while (0) + +#define CIRCLEQ_REMOVE(head, elm, field) \ + do { \ + if ((elm)->field.cqe_next == (void *)(head)) \ + (head)->cqh_last = (elm)->field.cqe_prev; \ + else \ + (elm)->field.cqe_next->field.cqe_prev = (elm)->field.cqe_prev; \ + if ((elm)->field.cqe_prev == (void *)(head)) \ + (head)->cqh_first = (elm)->field.cqe_next; \ + else \ + (elm)->field.cqe_prev->field.cqe_next = (elm)->field.cqe_next; \ + } while (0) + +#define CIRCLEQ_FOREACH(var, head, field) \ + for ((var) = ((head)->cqh_first); (var) != (const void *)(head); \ + (var) = ((var)->field.cqe_next)) + +#define CIRCLEQ_FOREACH_REVERSE(var, head, field) \ + for ((var) = ((head)->cqh_last); (var) != (const void *)(head); (var) = ((var)->field.cqe_prev)) /* * Circular queue access methods. */ -#define CIRCLEQ_EMPTY(head) ((head)->cqh_first == (void *)(head)) -#define CIRCLEQ_FIRST(head) ((head)->cqh_first) -#define CIRCLEQ_LAST(head) ((head)->cqh_last) -#define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next) -#define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev) - -#define CIRCLEQ_LOOP_NEXT(head, elm, field) \ - (((elm)->field.cqe_next == (void *)(head)) \ - ? ((head)->cqh_first) \ - : (elm->field.cqe_next)) -#define CIRCLEQ_LOOP_PREV(head, elm, field) \ - (((elm)->field.cqe_prev == (void *)(head)) \ - ? ((head)->cqh_last) \ - : (elm->field.cqe_prev)) +#define CIRCLEQ_EMPTY(head) ((head)->cqh_first == (void *)(head)) +#define CIRCLEQ_FIRST(head) ((head)->cqh_first) +#define CIRCLEQ_LAST(head) ((head)->cqh_last) +#define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next) +#define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev) + +#define CIRCLEQ_LOOP_NEXT(head, elm, field) \ + (((elm)->field.cqe_next == (void *)(head)) ? ((head)->cqh_first) : (elm->field.cqe_next)) +#define CIRCLEQ_LOOP_PREV(head, elm, field) \ + (((elm)->field.cqe_prev == (void *)(head)) ? ((head)->cqh_last) : (elm->field.cqe_prev)) #endif /* _SYS_QUEUE_H_ */ diff --git a/options/elf/generic/phdr.cpp b/options/elf/generic/phdr.cpp index 334d52c71a..408e909390 100644 --- a/options/elf/generic/phdr.cpp +++ b/options/elf/generic/phdr.cpp @@ -3,8 +3,8 @@ #include #include -extern "C" int __dlapi_iterate_phdr(int (*)(struct dl_phdr_info*, size_t, void*), void *); +extern "C" int __dlapi_iterate_phdr(int (*)(struct dl_phdr_info *, size_t, void *), void *); -int dl_iterate_phdr(int (*callback)(struct dl_phdr_info*, size_t, void*), void *data) { +int dl_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *data) { return __dlapi_iterate_phdr(callback, data); } diff --git a/options/elf/generic/startup.cpp b/options/elf/generic/startup.cpp index d53881ba11..c9ca1e7ebe 100644 --- a/options/elf/generic/startup.cpp +++ b/options/elf/generic/startup.cpp @@ -1,11 +1,11 @@ -#include -#include -#include -#include #include +#include #include #include +#include +#include +#include extern "C" size_t __init_array_start[]; extern "C" size_t __init_array_end[]; @@ -15,24 +15,22 @@ extern "C" size_t __preinit_array_end[]; static int constructors_ran_already = 0; struct global_constructor_guard { - global_constructor_guard() { - constructors_ran_already = 1; - } + global_constructor_guard() { constructors_ran_already = 1; } }; static global_constructor_guard g; void __mlibc_run_constructors() { -/* - if (!constructors_ran_already) { - size_t constructor_count = (size_t)__init_array_end - (size_t)__init_array_start; - constructor_count /= sizeof(void*); - for (size_t i = 0; i < constructor_count; i++) { - void (*ptr)(void) = (void(*)(void))(__init_array_start[i]); - ptr(); - } - } -*/ + /* + if (!constructors_ran_already) { + size_t constructor_count = (size_t)__init_array_end - (size_t)__init_array_start; + constructor_count /= sizeof(void*); + for (size_t i = 0; i < constructor_count; i++) { + void (*ptr)(void) = (void(*)(void))(__init_array_start[i]); + ptr(); + } + } + */ } namespace mlibc { @@ -42,19 +40,19 @@ void parse_exec_stack(void *opaque_sp, exec_stack_data *data) { data->argc = *sp++; data->argv = reinterpret_cast(sp); sp += data->argc; // Skip all arguments. - __ensure(!*sp); // Skip the terminating null element. + __ensure(!*sp); // Skip the terminating null element. sp++; data->envp = reinterpret_cast(sp); } // TODO: This does not have to be here; we could also move it to options/internal. void set_startup_data(int argc, char **argv, char **envp) { - if(argc) { + if (argc) { program_invocation_name = argv[0]; - if(auto slash = strrchr(argv[0], '/'); slash) { + if (auto slash = strrchr(argv[0], '/'); slash) { program_invocation_short_name = slash + 1; - }else{ + } else { program_invocation_short_name = argv[0]; } } @@ -62,7 +60,7 @@ void set_startup_data(int argc, char **argv, char **envp) { // Initialize environ. // TODO: Copy the arguments instead of pointing to them? auto ev = envp; - while(*ev) { + while (*ev) { auto fail = mlibc::putenv(*ev); __ensure(!fail); ev++; @@ -70,4 +68,3 @@ void set_startup_data(int argc, char **argv, char **envp) { } } // namespace mlibc - diff --git a/options/elf/include/elf.h b/options/elf/include/elf.h index 0c89dacb68..964cbad004 100644 --- a/options/elf/include/elf.h +++ b/options/elf/include/elf.h @@ -1,9 +1,9 @@ #ifndef _ELF_H #define _ELF_H -#include -#include #include +#include +#include #ifdef __cplusplus extern "C" { @@ -49,56 +49,56 @@ typedef Elf32_Half Elf32_Versym; typedef struct { unsigned char e_ident[EI_NIDENT]; /* ELF identification */ - Elf32_Half e_type; /* Object file type */ - Elf32_Half e_machine; /* Machine type */ - Elf32_Word e_version; /* Object file version */ - Elf32_Addr e_entry; /* Entry point address */ - Elf32_Off e_phoff; /* Program header offset */ - Elf32_Off e_shoff; /* Section header offset */ - Elf32_Word e_flags; /* Processor-specific flags */ - Elf32_Half e_ehsize; /* ELF header size */ - Elf32_Half e_phentsize; /* Size of program header entry */ - Elf32_Half e_phnum; /* Number of program header entries */ - Elf32_Half e_shentsize; /* Size of section header entry */ - Elf32_Half e_shnum; /* Number of section header entries */ - Elf32_Half e_shstrndx; /* Section name string table index */ + Elf32_Half e_type; /* Object file type */ + Elf32_Half e_machine; /* Machine type */ + Elf32_Word e_version; /* Object file version */ + Elf32_Addr e_entry; /* Entry point address */ + Elf32_Off e_phoff; /* Program header offset */ + Elf32_Off e_shoff; /* Section header offset */ + Elf32_Word e_flags; /* Processor-specific flags */ + Elf32_Half e_ehsize; /* ELF header size */ + Elf32_Half e_phentsize; /* Size of program header entry */ + Elf32_Half e_phnum; /* Number of program header entries */ + Elf32_Half e_shentsize; /* Size of section header entry */ + Elf32_Half e_shnum; /* Number of section header entries */ + Elf32_Half e_shstrndx; /* Section name string table index */ } Elf32_Ehdr; typedef struct { unsigned char e_ident[EI_NIDENT]; /* ELF identification */ - Elf64_Half e_type; /* Object file type */ - Elf64_Half e_machine; /* Machine type */ - Elf64_Word e_version; /* Object file version */ - Elf64_Addr e_entry; /* Entry point address */ - Elf64_Off e_phoff; /* Program header offset */ - Elf64_Off e_shoff; /* Section header offset */ - Elf64_Word e_flags; /* Processor-specific flags */ - Elf64_Half e_ehsize; /* ELF header size */ - Elf64_Half e_phentsize; /* Size of program header entry */ - Elf64_Half e_phnum; /* Number of program header entries */ - Elf64_Half e_shentsize; /* Size of section header entry */ - Elf64_Half e_shnum; /* Number of section header entries */ - Elf64_Half e_shstrndx; /* Section name string table index */ + Elf64_Half e_type; /* Object file type */ + Elf64_Half e_machine; /* Machine type */ + Elf64_Word e_version; /* Object file version */ + Elf64_Addr e_entry; /* Entry point address */ + Elf64_Off e_phoff; /* Program header offset */ + Elf64_Off e_shoff; /* Section header offset */ + Elf64_Word e_flags; /* Processor-specific flags */ + Elf64_Half e_ehsize; /* ELF header size */ + Elf64_Half e_phentsize; /* Size of program header entry */ + Elf64_Half e_phnum; /* Number of program header entries */ + Elf64_Half e_shentsize; /* Size of section header entry */ + Elf64_Half e_shnum; /* Number of section header entries */ + Elf64_Half e_shstrndx; /* Section name string table index */ } Elf64_Ehdr; typedef struct { Elf32_Half vd_version; /* Version revision */ - Elf32_Half vd_flags; /* Version information */ - Elf32_Half vd_ndx; /* Version Index */ - Elf32_Half vd_cnt; /* Number of associated aux entries */ - Elf32_Word vd_hash; /* Version name hash value */ - Elf32_Word vd_aux; /* Offset in bytes to verdaux array */ - Elf32_Word vd_next; /* Offset in bytes to next verdef entry */ + Elf32_Half vd_flags; /* Version information */ + Elf32_Half vd_ndx; /* Version Index */ + Elf32_Half vd_cnt; /* Number of associated aux entries */ + Elf32_Word vd_hash; /* Version name hash value */ + Elf32_Word vd_aux; /* Offset in bytes to verdaux array */ + Elf32_Word vd_next; /* Offset in bytes to next verdef entry */ } Elf32_Verdef; typedef struct { Elf64_Half vd_version; /* Version revision */ - Elf64_Half vd_flags; /* Version information */ - Elf64_Half vd_ndx; /* Version Index */ - Elf64_Half vd_cnt; /* Number of associated aux entries */ - Elf64_Word vd_hash; /* Version name hash value */ - Elf64_Word vd_aux; /* Offset in bytes to verdaux array */ - Elf64_Word vd_next; /* Offset in bytes to next verdef entry */ + Elf64_Half vd_flags; /* Version information */ + Elf64_Half vd_ndx; /* Version Index */ + Elf64_Half vd_cnt; /* Number of associated aux entries */ + Elf64_Word vd_hash; /* Version name hash value */ + Elf64_Word vd_aux; /* Offset in bytes to verdaux array */ + Elf64_Word vd_next; /* Offset in bytes to next verdef entry */ } Elf64_Verdef; typedef struct { @@ -143,22 +143,11 @@ typedef struct { Elf64_Word l_flags; } Elf64_Lib; -enum { - ET_NONE = 0, - ET_REL = 1, - ET_EXEC = 2, - ET_DYN = 3, - ET_CORE = 4 -}; +enum { ET_NONE = 0, ET_REL = 1, ET_EXEC = 2, ET_DYN = 3, ET_CORE = 4 }; -enum { - SHN_UNDEF = 0, - SHN_ABS = 0xFFF1 -}; +enum { SHN_UNDEF = 0, SHN_ABS = 0xFFF1 }; -enum { - STN_UNDEF = 0 -}; +enum { STN_UNDEF = 0 }; typedef struct { Elf32_Word st_name; @@ -178,12 +167,8 @@ typedef struct { Elf64_Xword st_size; } Elf64_Sym; -__MLIBC_INLINE_DEFINITION unsigned char ELF64_ST_BIND(unsigned char info) { - return info >> 4; -} -__MLIBC_INLINE_DEFINITION unsigned char ELF64_ST_TYPE(unsigned char info) { - return info & 0x0F; -} +__MLIBC_INLINE_DEFINITION unsigned char ELF64_ST_BIND(unsigned char info) { return info >> 4; } +__MLIBC_INLINE_DEFINITION unsigned char ELF64_ST_TYPE(unsigned char info) { return info & 0x0F; } __MLIBC_INLINE_DEFINITION unsigned char ELF64_ST_INFO(unsigned char bind, unsigned char type) { return (bind << 4) | type; } @@ -193,31 +178,15 @@ typedef struct { Elf64_Half si_flags; } Elf64_Syminfo; -__MLIBC_INLINE_DEFINITION unsigned char ELF32_ST_BIND(unsigned char info) { - return info >> 4; -} -__MLIBC_INLINE_DEFINITION unsigned char ELF32_ST_TYPE(unsigned char info) { - return info & 0xF; -} +__MLIBC_INLINE_DEFINITION unsigned char ELF32_ST_BIND(unsigned char info) { return info >> 4; } +__MLIBC_INLINE_DEFINITION unsigned char ELF32_ST_TYPE(unsigned char info) { return info & 0xF; } __MLIBC_INLINE_DEFINITION unsigned char ELF32_ST_INFO(unsigned char bind, unsigned char type) { return (bind << 4) | (type & 0xF); } -enum { - STB_GLOBAL = 1, - STB_WEAK = 2, - STB_GNU_UNIQUE = 10, - STB_LOPROC = 13, - STB_HIPROC = 15 -}; +enum { STB_GLOBAL = 1, STB_WEAK = 2, STB_GNU_UNIQUE = 10, STB_LOPROC = 13, STB_HIPROC = 15 }; -enum { - STT_OBJECT = 1, - STT_FUNC = 2, - STT_TLS = 6, - STT_LOPROC = 13, - STT_HIPROC = 15 -}; +enum { STT_OBJECT = 1, STT_FUNC = 2, STT_TLS = 6, STT_LOPROC = 13, STT_HIPROC = 15 }; enum { R_X86_64_NONE = 0, @@ -302,8 +271,8 @@ enum { R_68K_RELATIVE = 22, R_68K_TLS_DTPMOD32 = 40, - R_68K_TLS_DTPREL32= 41, - R_68K_TLS_TPREL32= 42 + R_68K_TLS_DTPREL32 = 41, + R_68K_TLS_TPREL32 = 42 }; typedef struct { @@ -313,7 +282,7 @@ typedef struct { typedef struct { Elf64_Addr r_offset; - uint64_t r_info; + uint64_t r_info; } Elf64_Rel; typedef struct { @@ -331,22 +300,14 @@ typedef struct { typedef Elf32_Word Elf32_Relr; typedef Elf64_Xword Elf64_Relr; -__MLIBC_INLINE_DEFINITION Elf64_Xword ELF64_R_SYM(Elf64_Xword info) { - return info >> 32; -} -__MLIBC_INLINE_DEFINITION Elf64_Xword ELF64_R_TYPE(Elf64_Xword info) { - return info & 0xFFFFFFFF; -} +__MLIBC_INLINE_DEFINITION Elf64_Xword ELF64_R_SYM(Elf64_Xword info) { return info >> 32; } +__MLIBC_INLINE_DEFINITION Elf64_Xword ELF64_R_TYPE(Elf64_Xword info) { return info & 0xFFFFFFFF; } __MLIBC_INLINE_DEFINITION Elf64_Xword ELF64_R_INFO(Elf64_Xword sym, Elf64_Xword type) { return ((((Elf64_Xword)(sym)) << 32) + (type)); } -__MLIBC_INLINE_DEFINITION Elf32_Word ELF32_R_SYM(Elf32_Word info) { - return info >> 8; -} -__MLIBC_INLINE_DEFINITION Elf32_Word ELF32_R_TYPE(Elf32_Word info) { - return info & 0xFF; -} +__MLIBC_INLINE_DEFINITION Elf32_Word ELF32_R_SYM(Elf32_Word info) { return info >> 8; } +__MLIBC_INLINE_DEFINITION Elf32_Word ELF32_R_TYPE(Elf32_Word info) { return info & 0xFF; } enum { PT_NULL = 0, @@ -373,32 +334,28 @@ enum { PT_HIPROC = 0x7fffffff }; -enum { - PF_X = 1, - PF_W = 2, - PF_R = 4 -}; +enum { PF_X = 1, PF_W = 2, PF_R = 4 }; typedef struct { - Elf32_Word p_type; /* Type of segment */ - Elf32_Off p_offset; /* Offset in file */ - Elf32_Addr p_vaddr; /* Virtual address in memory */ - Elf32_Addr p_paddr; /* Reserved */ + Elf32_Word p_type; /* Type of segment */ + Elf32_Off p_offset; /* Offset in file */ + Elf32_Addr p_vaddr; /* Virtual address in memory */ + Elf32_Addr p_paddr; /* Reserved */ Elf32_Word p_filesz; /* Size of segment in file */ - Elf32_Word p_memsz; /* Size of segment in memory */ - Elf32_Word p_flags; /* Segment attributes */ - Elf32_Word p_align; /* Alignment of segment */ + Elf32_Word p_memsz; /* Size of segment in memory */ + Elf32_Word p_flags; /* Segment attributes */ + Elf32_Word p_align; /* Alignment of segment */ } Elf32_Phdr; typedef struct { - Elf64_Word p_type; /* Type of segment */ - Elf64_Word p_flags; /* Segment attributes */ - Elf64_Off p_offset; /* Offset in file */ - Elf64_Addr p_vaddr; /* Virtual address in memory */ - Elf64_Addr p_paddr; /* Reserved */ + Elf64_Word p_type; /* Type of segment */ + Elf64_Word p_flags; /* Segment attributes */ + Elf64_Off p_offset; /* Offset in file */ + Elf64_Addr p_vaddr; /* Virtual address in memory */ + Elf64_Addr p_paddr; /* Reserved */ Elf64_Xword p_filesz; /* Size of segment in file */ - Elf64_Xword p_memsz; /* Size of segment in memory */ - Elf64_Xword p_align; /* Alignment of segment */ + Elf64_Xword p_memsz; /* Size of segment in memory */ + Elf64_Xword p_align; /* Alignment of segment */ } Elf64_Phdr; enum { @@ -467,8 +424,8 @@ enum { }; /* Valid values for note segment descriptor files for core files */ -#define NT_PRSTATUS 1 -#define NT_FPREGSET 2 +#define NT_PRSTATUS 1 +#define NT_FPREGSET 2 #define NT_PRPSINFO 3 /* Build ID bits as generated by ld --build-id */ @@ -517,10 +474,10 @@ typedef struct { } Elf64_Shdr; typedef struct { - uint64_t a_type; - union { - uint64_t a_val; - } a_un; + uint64_t a_type; + union { + uint64_t a_val; + } a_un; } Elf64_auxv_t; typedef struct { @@ -531,122 +488,123 @@ typedef struct { } Elf32_auxv_t; typedef struct { - Elf32_Word n_namesz; - Elf32_Word n_descsz; - Elf32_Word n_type; + Elf32_Word n_namesz; + Elf32_Word n_descsz; + Elf32_Word n_type; } Elf32_Nhdr; typedef struct { - Elf64_Word n_namesz; - Elf64_Word n_descsz; - Elf64_Word n_type; + Elf64_Word n_namesz; + Elf64_Word n_descsz; + Elf64_Word n_type; } Elf64_Nhdr; /* ST_TYPE (subfield of st_info) values (symbol type) */ -#define STT_NOTYPE 0 -#define STT_OBJECT 1 -#define STT_FUNC 2 -#define STT_SECTION 3 -#define STT_FILE 4 +#define STT_NOTYPE 0 +#define STT_OBJECT 1 +#define STT_FUNC 2 +#define STT_SECTION 3 +#define STT_FILE 4 /* ST_BIND (subfield of st_info) values (symbol binding) */ -#define STB_LOCAL 0 -#define STB_GLOBAL 1 -#define STB_WEAK 2 +#define STB_LOCAL 0 +#define STB_GLOBAL 1 +#define STB_WEAK 2 /* sh_type (section type) values */ -#define SHT_NULL 0 -#define SHT_PROGBITS 1 -#define SHT_SYMTAB 2 -#define SHT_STRTAB 3 -#define SHT_RELA 4 -#define SHT_HASH 5 +#define SHT_NULL 0 +#define SHT_PROGBITS 1 +#define SHT_SYMTAB 2 +#define SHT_STRTAB 3 +#define SHT_RELA 4 +#define SHT_HASH 5 #define SHT_DYNAMIC 6 -#define SHT_NOTE 7 -#define SHT_NOBITS 8 -#define SHT_REL 9 -#define SHT_DYNSYM 11 -#define SHT_INIT_ARRAY 14 -#define SHT_FINI_ARRAY 15 -#define SHT_SYMTAB_SHNDX 18 +#define SHT_NOTE 7 +#define SHT_NOBITS 8 +#define SHT_REL 9 +#define SHT_DYNSYM 11 +#define SHT_INIT_ARRAY 14 +#define SHT_FINI_ARRAY 15 +#define SHT_SYMTAB_SHNDX 18 /* special section indices */ -#define SHN_UNDEF 0 -#define SHN_LORESERVE 0xff00 -#define SHN_COMMON 0xfff2 -#define SHN_XINDEX 0xffff -#define SHN_HIRESERVE 0xff00 +#define SHN_UNDEF 0 +#define SHN_LORESERVE 0xff00 +#define SHN_COMMON 0xfff2 +#define SHN_XINDEX 0xffff +#define SHN_HIRESERVE 0xff00 /* values for e_machine */ -#define EM_NONE 0 -#define EM_M32 1 -#define EM_SPARC 2 -#define EM_386 3 -#define EM_68K 4 -#define EM_MIPS 8 -#define EM_PARISC 15 -#define EM_PPC 20 -#define EM_PPC64 21 -#define EM_S390 22 -#define EM_ARM 40 -#define EM_SH 42 -#define EM_SPARCV9 43 -#define EM_IA_64 50 -#define EM_X86_64 62 -#define EM_BLACKFIN 106 -#define EM_AARCH64 183 -#define EM_RISCV 243 - -/* Linux notes this value as being interim; however applications are using this (Qt6), so we define it here. */ -#define EM_ALPHA 0x9026 +#define EM_NONE 0 +#define EM_M32 1 +#define EM_SPARC 2 +#define EM_386 3 +#define EM_68K 4 +#define EM_MIPS 8 +#define EM_PARISC 15 +#define EM_PPC 20 +#define EM_PPC64 21 +#define EM_S390 22 +#define EM_ARM 40 +#define EM_SH 42 +#define EM_SPARCV9 43 +#define EM_IA_64 50 +#define EM_X86_64 62 +#define EM_BLACKFIN 106 +#define EM_AARCH64 183 +#define EM_RISCV 243 + +/* Linux notes this value as being interim; however applications are using this (Qt6), so we define + * it here. */ +#define EM_ALPHA 0x9026 /* values for e_version */ -#define EV_NONE 0 -#define EV_CURRENT 1 -#define EV_NUM 2 +#define EV_NONE 0 +#define EV_CURRENT 1 +#define EV_NUM 2 /* e_indent constants */ -#define EI_MAG0 0 -#define ELFMAG0 0x7f +#define EI_MAG0 0 +#define ELFMAG0 0x7f -#define EI_MAG1 1 -#define ELFMAG1 'E' +#define EI_MAG1 1 +#define ELFMAG1 'E' -#define EI_MAG2 2 -#define ELFMAG2 'L' +#define EI_MAG2 2 +#define ELFMAG2 'L' -#define EI_MAG3 3 -#define ELFMAG3 'F' +#define EI_MAG3 3 +#define ELFMAG3 'F' -#define ELFMAG "\177ELF" -#define SELFMAG 4 +#define ELFMAG "\177ELF" +#define SELFMAG 4 -#define EI_CLASS 4 -#define ELFCLASSNONE 0 -#define ELFCLASS32 1 -#define ELFCLASS64 2 -#define ELFCLASSNUM 3 +#define EI_CLASS 4 +#define ELFCLASSNONE 0 +#define ELFCLASS32 1 +#define ELFCLASS64 2 +#define ELFCLASSNUM 3 -#define EI_DATA 5 -#define ELFDATANONE 0 -#define ELFDATA2LSB 1 -#define ELFDATA2MSB 2 -#define ELFDATANUM 3 +#define EI_DATA 5 +#define ELFDATANONE 0 +#define ELFDATA2LSB 1 +#define ELFDATA2MSB 2 +#define ELFDATANUM 3 -#define EI_VERSION 6 +#define EI_VERSION 6 -#define EI_OSABI 7 -#define ELFOSABI_HPUX 1 -#define ELFOSABI_NETBSD 2 -#define ELFOSABI_GNU 3 +#define EI_OSABI 7 +#define ELFOSABI_HPUX 1 +#define ELFOSABI_NETBSD 2 +#define ELFOSABI_GNU 3 #define ELFOSABI_LINUX ELFOSABI_GNU -#define ELFOSABI_SOLARIS 6 -#define ELFOSABI_AIX 7 -#define ELFOSABI_IRIX 8 -#define ELFOSABI_FREEBSD 9 -#define ELFOSABI_OPENBSD 12 +#define ELFOSABI_SOLARIS 6 +#define ELFOSABI_AIX 7 +#define ELFOSABI_IRIX 8 +#define ELFOSABI_FREEBSD 9 +#define ELFOSABI_OPENBSD 12 -#define EI_ABIVERSION 8 +#define EI_ABIVERSION 8 #define ELF_NOTE_GNU "GNU" diff --git a/options/elf/include/link.h b/options/elf/include/link.h index 64d5fafc6d..e8c010fc79 100644 --- a/options/elf/include/link.h +++ b/options/elf/include/link.h @@ -7,20 +7,19 @@ extern "C" { #include #include - -#if defined(__x86_64__) || defined(__aarch64__) \ - || (defined(__riscv) && __riscv_xlen == 64) -# define ElfW(type) Elf64_ ## type + +#if defined(__x86_64__) || defined(__aarch64__) || (defined(__riscv) && __riscv_xlen == 64) +#define ElfW(type) Elf64_##type #elif defined(__i386__) || defined(__m68k__) -# define ElfW(type) Elf32_ ## type +#define ElfW(type) Elf32_##type #else -# error Unknown architecture +#error Unknown architecture #endif - + struct dl_phdr_info { ElfW(Addr) dlpi_addr; const char *dlpi_name; - const ElfW(Phdr) *dlpi_phdr; + const ElfW(Phdr) * dlpi_phdr; ElfW(Half) dlpi_phnum; unsigned long long int dlpi_adds; unsigned long long int dlpi_subs; @@ -31,7 +30,7 @@ struct dl_phdr_info { struct link_map { Elf64_Addr l_addr; char *l_name; - ElfW(Dyn) *l_ld; + ElfW(Dyn) * l_ld; struct link_map *l_next, *l_prev; }; @@ -45,7 +44,9 @@ struct r_debug { #ifndef __MLIBC_ABI_ONLY -int dl_iterate_phdr(int (*__callback)(struct dl_phdr_info* __info, size_t __size, void* __data), void* __data); +int dl_iterate_phdr( + int (*__callback)(struct dl_phdr_info *__info, size_t __size, void *__data), void *__data +); extern ElfW(Dyn) _DYNAMIC[]; diff --git a/options/glibc/generic/err.cpp b/options/glibc/generic/err.cpp index 042c1d8cb0..177c888570 100644 --- a/options/glibc/generic/err.cpp +++ b/options/glibc/generic/err.cpp @@ -10,7 +10,7 @@ void vwarn(const char *fmt, va_list params) { fprintf(stderr, "%s: ", program_invocation_short_name); if (fmt) { vfprintf(stderr, fmt, params); - fwrite(": ", 1, 2, stderr); + fwrite(": ", 1, 2, stderr); } perror(NULL); } diff --git a/options/glibc/generic/error.cpp b/options/glibc/generic/error.cpp index 45203b212b..7122bd8617 100644 --- a/options/glibc/generic/error.cpp +++ b/options/glibc/generic/error.cpp @@ -1,9 +1,9 @@ -#include -#include #include -#include -#include #include +#include +#include +#include +#include unsigned int error_message_count = 0; int error_one_per_line = 0; @@ -14,9 +14,9 @@ void error(int status, int errnum, const char *format, ...) { va_start(args, format); error_message_count++; - + fflush(stdout); - if(error_print_progname) { + if (error_print_progname) { error_print_progname(); } else { fprintf(stderr, "%s: ", program_invocation_name); @@ -24,28 +24,30 @@ void error(int status, int errnum, const char *format, ...) { vfprintf(stderr, format, args); va_end(args); - if(errnum) { + if (errnum) { fprintf(stderr, ": %s\n", strerror(errnum)); } - if(status) { + if (status) { exit(status); } } -void error_at_line(int status, int errnum, const char *filename, unsigned int linenum, const char *format, ...) { +void error_at_line( + int status, int errnum, const char *filename, unsigned int linenum, const char *format, ... +) { va_list args; va_start(args, format); static bool first_call = true; static unsigned int last_line = 0; - if(!(last_line == linenum && error_one_per_line && !first_call)) { + if (!(last_line == linenum && error_one_per_line && !first_call)) { first_call = false; last_line = linenum; error_message_count++; fflush(stdout); - if(error_print_progname) { + if (error_print_progname) { error_print_progname(); } else { fprintf(stderr, "%s:", program_invocation_name); @@ -53,13 +55,13 @@ void error_at_line(int status, int errnum, const char *filename, unsigned int li fprintf(stderr, "%s:%u: ", filename, linenum); vfprintf(stderr, format, args); - if(errnum) { + if (errnum) { fprintf(stderr, ": %s\n", strerror(errnum)); } } va_end(args); - if(status) { + if (status) { exit(status); } } diff --git a/options/glibc/generic/execinfo.cpp b/options/glibc/generic/execinfo.cpp index 3474615e96..077aad0a9c 100644 --- a/options/glibc/generic/execinfo.cpp +++ b/options/glibc/generic/execinfo.cpp @@ -1,5 +1,5 @@ -#include #include +#include int backtrace(void **, int) { __ensure(!"Not implemented"); diff --git a/options/glibc/generic/getopt.cpp b/options/glibc/generic/getopt.cpp index d13d4eb3e2..f566fdd7c4 100644 --- a/options/glibc/generic/getopt.cpp +++ b/options/glibc/generic/getopt.cpp @@ -23,42 +23,49 @@ enum GetoptMode { LongOnly, }; -int getopt_common(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex, enum GetoptMode mode) { +int getopt_common( + int argc, + char *const argv[], + const char *optstring, + const struct option *longopts, + int *longindex, + enum GetoptMode mode +) { auto longopt_consume = [&](const char *arg, char *s, int k, bool colon) -> frg::optional { // Consume the option and its argument. - if(longopts[k].has_arg == required_argument) { - if(s) { + if (longopts[k].has_arg == required_argument) { + if (s) { // Consume the long option and its argument. optarg = s + 1; optind++; - }else if(argv[optind + 1]) { + } else if (argv[optind + 1]) { // Consume the long option. optind++; // Consume the option's argument. optarg = argv[optind]; optind++; - }else{ + } else { /* If an error was detected, and the first character of optstring is not a colon, - and the external variable opterr is nonzero (which is the default), - getopt() prints an error message. */ - if(!colon && opterr) + and the external variable opterr is nonzero (which is the default), + getopt() prints an error message. */ + if (!colon && opterr) fprintf(stderr, "--%s requires an argument.\n", arg); /* If the first character of optstring is a colon (':'), then getopt() - returns ':' instead of '?' to indicate a missing option argument. */ + returns ':' instead of '?' to indicate a missing option argument. */ return colon ? ':' : '?'; } - }else if(longopts[k].has_arg == optional_argument) { - if(s) { + } else if (longopts[k].has_arg == optional_argument) { + if (s) { // Consume the long option and its argument. optarg = s + 1; optind++; - }else{ + } else { // Consume the long option. optarg = nullptr; optind++; } - }else{ + } else { __ensure(longopts[k].has_arg == no_argument); // Consume the long option. @@ -73,11 +80,11 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st // glibc extension: Setting optind to zero causes a full reset. // TODO: Should we really reset opterr and the other flags? - if(!optind + if (!optind #if __MLIBC_BSD_OPTION - || optreset + || optreset #endif //__MLIBC_BSD_OPTION - ) { + ) { optarg = nullptr; optind = 1; opterr = 1; @@ -88,30 +95,30 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st #endif //__MLIBC_BSD_OPTION } - auto isOptionArg = [](char *arg){ + auto isOptionArg = [](char *arg) { // If the first character of arg '-', and the arg is not exactly // equal to "-" or "--", then the arg is an option argument. return arg[0] == '-' && strcmp(arg, "-") && strcmp(arg, "--"); }; - while(optind < argc) { + while (optind < argc) { char *arg = argv[optind]; - if(!isOptionArg(arg)) { - if(stop_at_first_nonarg) { + if (!isOptionArg(arg)) { + if (stop_at_first_nonarg) { return -1; } bool further_options = false; int skip = optind; - for(; skip < argc; ++skip) { - if(isOptionArg(argv[skip])) { + for (; skip < argc; ++skip) { + if (isOptionArg(argv[skip])) { further_options = true; break; } } - if(further_options) { + if (further_options) { optind += skip - optind; continue; } else { @@ -120,7 +127,7 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st } } - if(arg[1] == '-') { + if (arg[1] == '-') { arg += 2; // Determine the end of the option name (vs. the start of the argument). @@ -128,52 +135,52 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st size_t n = s ? (s - arg) : strlen(arg); int k = -1; - for(int i = 0; longopts[i].name; i++) { - if(strncmp(arg, longopts[i].name, n) || longopts[i].name[n]) + for (int i = 0; longopts[i].name; i++) { + if (strncmp(arg, longopts[i].name, n) || longopts[i].name[n]) continue; - if(k >= 0) { - if(opterr) + if (k >= 0) { + if (opterr) fprintf(stderr, "Multiple option declaration detected: %s\n", arg); return '?'; } k = i; } - if(k == -1) { - if(opterr) + if (k == -1) { + if (opterr) fprintf(stderr, "--%s is not a valid option.\n", arg); return '?'; } - if(longindex) + if (longindex) *longindex = k; - if(auto r = longopt_consume(arg, s, k, colon); r) + if (auto r = longopt_consume(arg, s, k, colon); r) return r.value(); - if(!longopts[k].flag) { + if (!longopts[k].flag) { return longopts[k].val; - }else{ + } else { *longopts[k].flag = longopts[k].val; return 0; } - }else{ + } else { /* handle short options, i.e. options with only one dash prefixed; e.g. `program -s` */ unsigned int i = __optpos; - while(true) { - if(mode == GetoptMode::LongOnly) { + while (true) { + if (mode == GetoptMode::LongOnly) { const char *lo_arg = &arg[1]; auto s = strchr(lo_arg, '='); size_t n = s ? (s - lo_arg) : strlen(lo_arg); int k = -1; - for(int longopt = 0; longopts[longopt].name; longopt++) { - if(strncmp(lo_arg, longopts[longopt].name, n) || longopts[longopt].name[n]) + for (int longopt = 0; longopts[longopt].name; longopt++) { + if (strncmp(lo_arg, longopts[longopt].name, n) || longopts[longopt].name[n]) continue; - if(k >= 0) { - if(opterr) + if (k >= 0) { + if (opterr) fprintf(stderr, "Multiple option declaration detected: %s\n", arg); return '?'; } @@ -181,13 +188,13 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st k = longopt; } - if(k != -1) { - if(auto r = longopt_consume(lo_arg, s, k, colon); r) + if (k != -1) { + if (auto r = longopt_consume(lo_arg, s, k, colon); r) return r.value(); - if(!longopts[k].flag) { + if (!longopts[k].flag) { return longopts[k].val; - }else{ + } else { *longopts[k].flag = longopts[k].val; return 0; } @@ -195,18 +202,19 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st } auto opt = strchr(optstring, arg[i]); - if(opt) { - if(opt[1] == ':') { + if (opt) { + if (opt[1] == ':') { bool required = (opt[2] != ':'); - if(arg[i+1]) { + if (arg[i + 1]) { optarg = arg + i + 1; - } else if(optind + 1 < argc && argv[optind + 1] && (required || argv[optind + 1][0] != '-')) { + } else if (optind + 1 < argc && argv[optind + 1] && + (required || argv[optind + 1][0] != '-')) { /* there is an argument to this short option, separated by a space */ optarg = argv[optind + 1]; optind++; __optpos = 1; - } else if(!required) { + } else if (!required) { optarg = nullptr; } else { __optpos = 1; @@ -215,9 +223,9 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st } optind++; } else { - if(arg[i+1]) { + if (arg[i + 1]) { __optpos++; - } else if(arg[i]) { + } else if (arg[i]) { optind++; } else { return -1; @@ -226,11 +234,11 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st return arg[i]; } else { - /* If getopt() does not recognize an option character, it prints an error message to stderr, - stores the character in optopt, and returns '?'. The calling program may prevent - the error message by setting opterr to 0. */ + /* If getopt() does not recognize an option character, it prints an error + message to stderr, stores the character in optopt, and returns '?'. The + calling program may prevent the error message by setting opterr to 0. */ optopt = arg[1]; - if(opterr) + if (opterr) fprintf(stderr, "%s is not a valid option.\n", arg); return '?'; } @@ -240,14 +248,24 @@ int getopt_common(int argc, char * const argv[], const char *optstring, const st return -1; } -} +} // namespace -int getopt_long(int argc, char * const argv[], const char *optstring, - const struct option *longopts, int *longindex) { +int getopt_long( + int argc, + char *const argv[], + const char *optstring, + const struct option *longopts, + int *longindex +) { return getopt_common(argc, argv, optstring, longopts, longindex, GetoptMode::Long); } -int getopt_long_only(int argc, char * const argv[], const char *optstring, - const struct option *longopts, int *longindex) { +int getopt_long_only( + int argc, + char *const argv[], + const char *optstring, + const struct option *longopts, + int *longindex +) { return getopt_common(argc, argv, optstring, longopts, longindex, GetoptMode::LongOnly); } diff --git a/options/glibc/generic/glibc-assert.cpp b/options/glibc/generic/glibc-assert.cpp index 77cd4988ad..e65b5839f6 100644 --- a/options/glibc/generic/glibc-assert.cpp +++ b/options/glibc/generic/glibc-assert.cpp @@ -5,10 +5,11 @@ #include -[[gnu::noreturn]] void __assert_fail_perror(int errno, const char *file, unsigned int line, - const char *function) { +[[gnu::noreturn]] void +__assert_fail_perror(int errno, const char *file, unsigned int line, const char *function) { char *errormsg = strerror(errno); - fprintf(stderr, "In function %s, file %s:%d: Errno '%s' failed!\n", - function, file, line, errormsg); + fprintf( + stderr, "In function %s, file %s:%d: Errno '%s' failed!\n", function, file, line, errormsg + ); abort(); } diff --git a/options/glibc/generic/glibc-signal.cpp b/options/glibc/generic/glibc-signal.cpp index 41bc455d87..ee8d59b1c2 100644 --- a/options/glibc/generic/glibc-signal.cpp +++ b/options/glibc/generic/glibc-signal.cpp @@ -1,12 +1,12 @@ -#include -#include #include +#include #include #include +#include int tgkill(int tgid, int tid, int sig) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_tgkill, -1); - if(int e = mlibc::sys_tgkill(tgid, tid, sig); e) { + if (int e = mlibc::sys_tgkill(tgid, tid, sig); e) { errno = e; return -1; } diff --git a/options/glibc/generic/gshadow.cpp b/options/glibc/generic/gshadow.cpp index f93a47ddfa..7304e14b08 100644 --- a/options/glibc/generic/gshadow.cpp +++ b/options/glibc/generic/gshadow.cpp @@ -1,5 +1,5 @@ -#include #include +#include int getsgnam_r(const char *, struct sgrp *, char *, size_t, struct sgrp **) { __ensure(!"Not implemented"); diff --git a/options/glibc/generic/malloc.cpp b/options/glibc/generic/malloc.cpp index b5a4dafbe5..5c012fdda5 100644 --- a/options/glibc/generic/malloc.cpp +++ b/options/glibc/generic/malloc.cpp @@ -1,6 +1,4 @@ #include #include -size_t malloc_usable_size(void *p) { - return getAllocator().get_size(p); -} +size_t malloc_usable_size(void *p) { return getAllocator().get_size(p); } diff --git a/options/glibc/generic/personality.cpp b/options/glibc/generic/personality.cpp index 3bfd9aaf10..f88023d4f5 100644 --- a/options/glibc/generic/personality.cpp +++ b/options/glibc/generic/personality.cpp @@ -7,7 +7,7 @@ int personality(unsigned long persona) { int out = 0; auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_personality, -1); - if(int e = sysdep(persona, &out); e) { + if (int e = sysdep(persona, &out); e) { errno = e; return -1; } diff --git a/options/glibc/generic/printf.cpp b/options/glibc/generic/printf.cpp index 4abb00d75b..2b97c4b512 100644 --- a/options/glibc/generic/printf.cpp +++ b/options/glibc/generic/printf.cpp @@ -1,7 +1,7 @@ #include #include -size_t parse_printf_format(const char * __restrict, size_t, int * __restrict) { +size_t parse_printf_format(const char *__restrict, size_t, int *__restrict) { __ensure(!"Not implemented"); __builtin_unreachable(); } diff --git a/options/glibc/generic/resolv.cpp b/options/glibc/generic/resolv.cpp index 7c0723ed68..cee8e8e668 100644 --- a/options/glibc/generic/resolv.cpp +++ b/options/glibc/generic/resolv.cpp @@ -1,16 +1,15 @@ -#include #include #include +#include -int dn_expand(const unsigned char *, const unsigned char *, - const unsigned char *, char *, int) { +int dn_expand(const unsigned char *, const unsigned char *, const unsigned char *, char *, int) { __ensure(!"Not implemented"); __builtin_unreachable(); } int res_query(const char *, int, int, unsigned char *, int) { __ensure(!"Not implemented"); - __builtin_unreachable(); + __builtin_unreachable(); } int res_init() { diff --git a/options/glibc/generic/search.cpp b/options/glibc/generic/search.cpp index 52a578f78e..0378114dcc 100644 --- a/options/glibc/generic/search.cpp +++ b/options/glibc/generic/search.cpp @@ -5,9 +5,7 @@ int hcreate_r(size_t num_entries, hsearch_data *htab) { return mlibc::hcreate_r(num_entries, htab); } -void hdestroy_r(hsearch_data *htab) { - mlibc::hdestroy_r(htab); -} +void hdestroy_r(hsearch_data *htab) { mlibc::hdestroy_r(htab); } int hsearch_r(ENTRY item, ACTION action, ENTRY **ret, hsearch_data *htab) { return mlibc::hsearch_r(item, action, ret, htab); diff --git a/options/glibc/generic/shadow.cpp b/options/glibc/generic/shadow.cpp index 9ce6584664..f4da82e171 100644 --- a/options/glibc/generic/shadow.cpp +++ b/options/glibc/generic/shadow.cpp @@ -1,11 +1,11 @@ -#include #include +#include #include #include +#include #include -#include -#include #include +#include #include #include @@ -22,22 +22,31 @@ #define NUM(n) ((n) == -1 ? 0 : -1), ((n) == -1 ? 0 : (n)) int putspent(const struct spwd *sp, FILE *f) { - auto str = [] (char *s) { - return ((s) ? (s) : ""); - }; - return fprintf(f, "%s:%s:%.*d:%.*d:%.*d:%.*d:%.*d:%.*d:%.*u\n", - str(sp->sp_namp), str(sp->sp_pwdp), NUM(sp->sp_lstchg), - NUM(sp->sp_min), NUM(sp->sp_max), NUM(sp->sp_warn), - NUM(sp->sp_inact), NUM(sp->sp_expire), NUM((int)sp->sp_flag)) < 0 ? -1 : 0; + auto str = [](char *s) { return ((s) ? (s) : ""); }; + return fprintf( + f, + "%s:%s:%.*d:%.*d:%.*d:%.*d:%.*d:%.*d:%.*u\n", + str(sp->sp_namp), + str(sp->sp_pwdp), + NUM(sp->sp_lstchg), + NUM(sp->sp_min), + NUM(sp->sp_max), + NUM(sp->sp_warn), + NUM(sp->sp_inact), + NUM(sp->sp_expire), + NUM((int)sp->sp_flag) + ) < 0 + ? -1 + : 0; } #undef NUM static long xatol(char **s) { long x; - if(**s == ':' || **s == '\n') { + if (**s == ':' || **s == '\n') { return -1; } - for(x = 0; (unsigned int)**s - '0' < 10U; ++*s) { + for (x = 0; (unsigned int)**s - '0' < 10U; ++*s) { x = 10 * x + (**s - '0'); } return x; @@ -45,64 +54,62 @@ static long xatol(char **s) { static int __parsespent(char *s, struct spwd *sp) { sp->sp_namp = s; - if(!(s = strchr(s, ':'))) { + if (!(s = strchr(s, ':'))) { return -1; } *s = 0; sp->sp_pwdp = ++s; - if(!(s = strchr(s, ':'))) { + if (!(s = strchr(s, ':'))) { return -1; } *s = 0; s++; sp->sp_lstchg = xatol(&s); - if(*s != ':') { + if (*s != ':') { return -1; } s++; sp->sp_min = xatol(&s); - if(*s != ':') { + if (*s != ':') { return -1; } s++; sp->sp_max = xatol(&s); - if(*s != ':') { + if (*s != ':') { return -1; } s++; sp->sp_warn = xatol(&s); - if(*s != ':') { + if (*s != ':') { return -1; } s++; sp->sp_inact = xatol(&s); - if(*s != ':') { + if (*s != ':') { return -1; } s++; sp->sp_expire = xatol(&s); - if(*s != ':') { + if (*s != ':') { return -1; } s++; sp->sp_flag = xatol(&s); - if(*s != '\n') { + if (*s != '\n') { return -1; } return 0; } -static void cleanup(void *p) { - fclose((FILE *)p); -} +static void cleanup(void *p) { fclose((FILE *)p); } int getspnam_r(const char *name, struct spwd *sp, char *buf, size_t size, struct spwd **res) { char path[20 + NAME_MAX]; @@ -117,37 +124,37 @@ int getspnam_r(const char *name, struct spwd *sp, char *buf, size_t size, struct *res = 0; /* Disallow potentially-malicious user names */ - if(*name=='.' || strchr(name, '/') || !l) { + if (*name == '.' || strchr(name, '/') || !l) { return errno = EINVAL; } /* Buffer size must at least be able to hold name, plus some.. */ - if(size < l + 100) { + if (size < l + 100) { return errno = ERANGE; } /* Protect against truncation */ - if(snprintf(path, sizeof path, "/etc/tcb/%s/shadow", name) >= (int)sizeof path) { + if (snprintf(path, sizeof path, "/etc/tcb/%s/shadow", name) >= (int)sizeof path) { return errno = EINVAL; } - fd = open(path, O_RDONLY|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC); - if(fd >= 0) { + fd = open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC); + if (fd >= 0) { struct stat st = {}; errno = EINVAL; - if(fstat(fd, &st) || !S_ISREG(st.st_mode) || !(f = fdopen(fd, "rb"))) { + if (fstat(fd, &st) || !S_ISREG(st.st_mode) || !(f = fdopen(fd, "rb"))) { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); close(fd); pthread_setcancelstate(cs, 0); return errno; } } else { - if(errno != ENOENT && errno != ENOTDIR) { + if (errno != ENOENT && errno != ENOTDIR) { return errno; } f = fopen("/etc/shadow", "rbe"); - if(!f) { - if(errno != ENOENT && errno != ENOTDIR) { + if (!f) { + if (errno != ENOENT && errno != ENOTDIR) { return errno; } return 0; @@ -155,17 +162,17 @@ int getspnam_r(const char *name, struct spwd *sp, char *buf, size_t size, struct } pthread_cleanup_push(cleanup, f); - while(fgets(buf, size, f) && (k = strlen(buf)) > 0) { - if(skip || strncmp(name, buf, l) || buf[l] != ':') { + while (fgets(buf, size, f) && (k = strlen(buf)) > 0) { + if (skip || strncmp(name, buf, l) || buf[l] != ':') { skip = buf[k - 1] != '\n'; continue; } - if(buf[k - 1] != '\n') { + if (buf[k - 1] != '\n') { rv = ERANGE; break; } - if(__parsespent(buf, sp) < 0) { + if (__parsespent(buf, sp) < 0) { continue; } *res = sp; @@ -196,10 +203,10 @@ struct spwd *getspnam(const char *name) { int e; int orig_errno = errno; - if(!line) { + if (!line) { line = (char *)malloc(LINE_LIM); } - if(!line) { + if (!line) { return 0; } e = getspnam_r(name, &sp, line, LINE_LIM, &res); @@ -212,6 +219,4 @@ struct spwd *fgetspent(FILE *) { __builtin_unreachable(); } -void endspent(void) { - mlibc::infoLogger() << "mlibc: endspent is a stub" << frg::endlog; -} +void endspent(void) { mlibc::infoLogger() << "mlibc: endspent is a stub" << frg::endlog; } diff --git a/options/glibc/generic/stdio_ext.cpp b/options/glibc/generic/stdio_ext.cpp index b9b61fc225..fbb4f75df7 100644 --- a/options/glibc/generic/stdio_ext.cpp +++ b/options/glibc/generic/stdio_ext.cpp @@ -1,7 +1,7 @@ -#include #include #include +#include size_t __fbufsize(FILE *) { __ensure(!"Not implemented"); @@ -26,13 +26,9 @@ int __fwritable(FILE *) { __builtin_unreachable(); } -int __freading(FILE *file_base) { - return file_base->__io_mode == 0; -} +int __freading(FILE *file_base) { return file_base->__io_mode == 0; } -int __fwriting(FILE *file_base) { - return file_base->__io_mode == 1; -} +int __fwriting(FILE *file_base) { return file_base->__io_mode == 1; } int __fsetlocking(FILE *, int) { mlibc::infoLogger() << "mlibc: __fsetlocking() is a no-op" << frg::endlog; @@ -47,8 +43,9 @@ void _flushlbf(void) { // The following functions are defined by musl. size_t __freadahead(FILE *file_base) { - if(file_base->__io_mode != 0) { - mlibc::infoLogger() << "mlibc: __freadahead() called but file is not open for reading" << frg::endlog; + if (file_base->__io_mode != 0) { + mlibc::infoLogger() << "mlibc: __freadahead() called but file is not open for reading" + << frg::endlog; return 0; } return file_base->__valid_limit - file_base->__offset; @@ -61,4 +58,3 @@ void __fseterr(FILE *) { __ensure(!"Not implemented"); __builtin_unreachable(); } - diff --git a/options/glibc/generic/string.cpp b/options/glibc/generic/string.cpp index 19f77c7232..d0857a5ed0 100644 --- a/options/glibc/generic/string.cpp +++ b/options/glibc/generic/string.cpp @@ -1,8 +1,8 @@ #ifndef _GNU_SOURCE -# define _GNU_SOURCE +#define _GNU_SOURCE #endif -#include #include +#include /* This is a bit of a weird detail of the GNU implementation and C's lack of * overloading and strictness: GNU takes const char * and returns a char * so @@ -17,16 +17,11 @@ char *__mlibc_gnu_basename_c(const char *path) { return basename_component + 1; } - /* GNU exposes these overloads, and as a result, we should probably have them * checked, to make sure we actually match expectations. */ static_assert( - std::is_same_v, - "C++ overloads broken" + std::is_same_v, "C++ overloads broken" ); -static_assert( - std::is_same_v, - "C++ overloads broken" -); +static_assert(std::is_same_v, "C++ overloads broken"); diff --git a/options/glibc/generic/sys-io.cpp b/options/glibc/generic/sys-io.cpp index fbd907067f..2384303d51 100644 --- a/options/glibc/generic/sys-io.cpp +++ b/options/glibc/generic/sys-io.cpp @@ -7,7 +7,7 @@ int ioperm(unsigned long int from, unsigned long int num, int turn_on) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ioperm, -1); - if(int e = sysdep(from, num, turn_on); e) { + if (int e = sysdep(from, num, turn_on); e) { errno = e; return -1; } @@ -17,7 +17,7 @@ int ioperm(unsigned long int from, unsigned long int num, int turn_on) { int iopl(int level) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_iopl, -1); - if(int e = sysdep(level); e) { + if (int e = sysdep(level); e) { errno = e; return -1; } diff --git a/options/glibc/generic/sys-ioctl.cpp b/options/glibc/generic/sys-ioctl.cpp index 021d2a3d32..f9ca9237df 100644 --- a/options/glibc/generic/sys-ioctl.cpp +++ b/options/glibc/generic/sys-ioctl.cpp @@ -12,10 +12,9 @@ int ioctl(int fd, unsigned long request, ...) { int result; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ioctl, -1); void *arg = va_arg(args, void *); - if(int e = mlibc::sys_ioctl(fd, request, arg, &result); e) { + if (int e = mlibc::sys_ioctl(fd, request, arg, &result); e) { errno = e; return -1; } return result; } - diff --git a/options/glibc/include/ar.h b/options/glibc/include/ar.h index c7a9f38dcf..cf8cc91832 100644 --- a/options/glibc/include/ar.h +++ b/options/glibc/include/ar.h @@ -1,8 +1,8 @@ -#ifndef _AR_H -#define _AR_H +#ifndef _AR_H +#define _AR_H -#define ARMAG "!\n" +#define ARMAG "!\n" #define SARMAG 8 #define ARFMAG "`\n" diff --git a/options/glibc/include/bits/glibc/glibc_assert.h b/options/glibc/include/bits/glibc/glibc_assert.h index 9165d29e4d..9269d0d5bb 100644 --- a/options/glibc/include/bits/glibc/glibc_assert.h +++ b/options/glibc/include/bits/glibc/glibc_assert.h @@ -7,8 +7,8 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -__attribute__ ((__noreturn__)) void __assert_fail_perror(int __errno, const char *__file, unsigned int __line, - const char *__function); +__attribute__((__noreturn__)) void +__assert_fail_perror(int __errno, const char *__file, unsigned int __line, const char *__function); #endif /* !__MLIBC_ABI_ONLY */ @@ -26,7 +26,7 @@ __attribute__ ((__noreturn__)) void __assert_fail_perror(int __errno, const char #else /* NDEBUG */ #undef assert_perror -#define assert_perror(errno) (!(errno) \ - || (__assert_fail_perror((errno), __FILE__, __LINE__, __func__), 0)) +#define assert_perror(errno) \ + (!(errno) || (__assert_fail_perror((errno), __FILE__, __LINE__, __func__), 0)) #endif /* NDEBUG */ diff --git a/options/glibc/include/bits/glibc/glibc_icmp6.h b/options/glibc/include/bits/glibc/glibc_icmp6.h index eafde16625..3c2fe164e7 100644 --- a/options/glibc/include/bits/glibc/glibc_icmp6.h +++ b/options/glibc/include/bits/glibc/glibc_icmp6.h @@ -18,4 +18,3 @@ extern "C" { #endif #endif /* _GLIBC_NETINET_ICMP6_H */ - diff --git a/options/glibc/include/bits/glibc/glibc_malloc.h b/options/glibc/include/bits/glibc/glibc_malloc.h index 62cf00961e..5b4b41fa76 100644 --- a/options/glibc/include/bits/glibc/glibc_malloc.h +++ b/options/glibc/include/bits/glibc/glibc_malloc.h @@ -14,4 +14,3 @@ size_t malloc_usable_size(void *__ptr); #endif #endif /* _GLIBC_MALLOC_H */ - diff --git a/options/glibc/include/endian.h b/options/glibc/include/endian.h index 129af989df..c7af77d494 100644 --- a/options/glibc/include/endian.h +++ b/options/glibc/include/endian.h @@ -4,51 +4,51 @@ #include #ifdef __GNUC__ -# define BYTE_ORDER __BYTE_ORDER__ -# define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ -# define BIG_ENDIAN __ORDER_BIG_ENDIAN__ -# define PDP_ENDIAN __ORDER_PDP_ENDIAN__ +#define BYTE_ORDER __BYTE_ORDER__ +#define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ +#define BIG_ENDIAN __ORDER_BIG_ENDIAN__ +#define PDP_ENDIAN __ORDER_PDP_ENDIAN__ -# define __BYTE_ORDER __BYTE_ORDER__ +#define __BYTE_ORDER __BYTE_ORDER__ #ifndef __LITTLE_ENDIAN /* Linux kernel headers define this already */ -# define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ +#define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ #endif -# define __BIG_ENDIAN __ORDER_BIG_ENDIAN__ -# define __PDP_ENDIAN __ORDER_PDP_ENDIAN__ +#define __BIG_ENDIAN __ORDER_BIG_ENDIAN__ +#define __PDP_ENDIAN __ORDER_PDP_ENDIAN__ #else -# error "Unsupported compiler" +#error "Unsupported compiler" #endif #if BYTE_ORDER == LITTLE_ENDIAN -# define htobe16(x) __bswap_16(x) -# define htole16(x) (uint16_t)(x) -# define be16toh(x) __bswap_16(x) -# define le16toh(x) (uint16_t)(x) - -# define htobe32(x) __bswap_32(x) -# define htole32(x) (uint32_t)(x) -# define be32toh(x) __bswap_32(x) -# define le32toh(x) (uint32_t)(x) - -# define htobe64(x) __bswap_64(x) -# define htole64(x) (uint64_t)(x) -# define be64toh(x) __bswap_64(x) -# define le64toh(x) (uint64_t)(x) +#define htobe16(x) __bswap_16(x) +#define htole16(x) (uint16_t)(x) +#define be16toh(x) __bswap_16(x) +#define le16toh(x) (uint16_t)(x) + +#define htobe32(x) __bswap_32(x) +#define htole32(x) (uint32_t)(x) +#define be32toh(x) __bswap_32(x) +#define le32toh(x) (uint32_t)(x) + +#define htobe64(x) __bswap_64(x) +#define htole64(x) (uint64_t)(x) +#define be64toh(x) __bswap_64(x) +#define le64toh(x) (uint64_t)(x) #else -# define htobe16(x) (uint16_t)(x) -# define htole16(x) __bswap_16(x) -# define be16toh(x) (uint16_t)(x) -# define le16toh(x) __bswap_16(x) - -# define htobe32(x) (uint32_t)(x) -# define htole32(x) __bswap_32(x) -# define be32toh(x) (uint32_t)(x) -# define le32toh(x) __bswap_32(x) - -# define htobe64(x) (uint64_t)(x) -# define htole64(x) __bswap_64(x) -# define be64toh(x) (uint64_t)(x) -# define le64toh(x) __bswap_64(x) +#define htobe16(x) (uint16_t)(x) +#define htole16(x) __bswap_16(x) +#define be16toh(x) (uint16_t)(x) +#define le16toh(x) __bswap_16(x) + +#define htobe32(x) (uint32_t)(x) +#define htole32(x) __bswap_32(x) +#define be32toh(x) (uint32_t)(x) +#define le32toh(x) __bswap_32(x) + +#define htobe64(x) (uint64_t)(x) +#define htole64(x) __bswap_64(x) +#define be64toh(x) (uint64_t)(x) +#define le64toh(x) __bswap_64(x) #endif #endif /* _ENDIAN_H */ diff --git a/options/glibc/include/err.h b/options/glibc/include/err.h index 88341e9f5b..6d2102164e 100644 --- a/options/glibc/include/err.h +++ b/options/glibc/include/err.h @@ -1,5 +1,5 @@ -#ifndef _ERR_H -#define _ERR_H +#ifndef _ERR_H +#define _ERR_H #include @@ -14,14 +14,14 @@ __attribute__((__format__(__printf__, 1, 0))) void vwarn(const char *__format, v __attribute__((__format__(__printf__, 1, 2))) void warnx(const char *__format, ...); __attribute__((__format__(__printf__, 1, 0))) void vwarnx(const char *__format, va_list __args); -__attribute__((__noreturn__, __format__(__printf__, 2, 3))) -void err(int __errnum, const char *__format, ...); -__attribute__((__noreturn__, __format__(__printf__, 2, 0))) -void verr(int __errnum, const char *__format, va_list __args); -__attribute__((__noreturn__, , __format__(__printf__, 2, 3))) -void errx(int __errnum, const char *__format, ...); -__attribute__((__noreturn__, __format__(__printf__, 2, 0))) -void verrx(int __errnum, const char *__format, va_list __args); +__attribute__((__noreturn__, __format__(__printf__, 2, 3))) void +err(int __errnum, const char *__format, ...); +__attribute__((__noreturn__, __format__(__printf__, 2, 0))) void +verr(int __errnum, const char *__format, va_list __args); +__attribute__((__noreturn__, , __format__(__printf__, 2, 3))) void +errx(int __errnum, const char *__format, ...); +__attribute__((__noreturn__, __format__(__printf__, 2, 0))) void +verrx(int __errnum, const char *__format, va_list __args); #endif /* !__MLIBC_ABI_ONLY */ @@ -30,4 +30,3 @@ void verrx(int __errnum, const char *__format, va_list __args); #endif #endif /* _ERR_H */ - diff --git a/options/glibc/include/error.h b/options/glibc/include/error.h index b41352a0cd..38050bb083 100644 --- a/options/glibc/include/error.h +++ b/options/glibc/include/error.h @@ -4,24 +4,30 @@ #include #ifdef __cplusplus -extern "C"{ +extern "C" { #endif #ifndef __MLIBC_ABI_ONLY -__attribute__((__format__(__printf__, 3, 4))) -void error(int __status, int __errnum, const char *__format, ...); -__attribute__((__format__(__printf__, 5, 6))) -void error_at_line(int __status, int __errnum, const char *__filename, unsigned int __linenum, const char *__format, ...); +__attribute__((__format__(__printf__, 3, 4))) void +error(int __status, int __errnum, const char *__format, ...); +__attribute__((__format__(__printf__, 5, 6))) void error_at_line( + int __status, + int __errnum, + const char *__filename, + unsigned int __linenum, + const char *__format, + ... +); extern unsigned int error_message_count; extern int error_one_per_line; extern void (*error_print_progname)(void); - + #endif /* !__MLIBC_ABI_ONLY */ #ifdef __cplusplus } #endif - + #endif /* _ERROR_H */ diff --git a/options/glibc/include/getopt.h b/options/glibc/include/getopt.h index 10ca7be96d..1bfe452527 100644 --- a/options/glibc/include/getopt.h +++ b/options/glibc/include/getopt.h @@ -1,6 +1,6 @@ -#ifndef _GETOPT_H -#define _GETOPT_H +#ifndef _GETOPT_H +#define _GETOPT_H #include @@ -27,10 +27,20 @@ extern int optreset; #endif /*__MLIBC_BSD_OPTION */ int getopt(int __argc, char *const __argv[], const char *__optstring); -int getopt_long(int __argc, char *const __argv[], const char *__optstring, - const struct option *__longopts, int *__longindex); -int getopt_long_only(int __argc, char *const __argv[], const char *__optstring, - const struct option *__longopts, int *__longindex); +int getopt_long( + int __argc, + char *const __argv[], + const char *__optstring, + const struct option *__longopts, + int *__longindex +); +int getopt_long_only( + int __argc, + char *const __argv[], + const char *__optstring, + const struct option *__longopts, + int *__longindex +); #endif /* !__MLIBC_ABI_ONLY */ @@ -43,4 +53,3 @@ int getopt_long_only(int __argc, char *const __argv[], const char *__optstring, #endif #endif /* _GETOPT_H */ - diff --git a/options/glibc/include/gshadow.h b/options/glibc/include/gshadow.h index 4517700f1e..0e1ea24238 100644 --- a/options/glibc/include/gshadow.h +++ b/options/glibc/include/gshadow.h @@ -1,16 +1,16 @@ #ifndef _GSHADOW_H #define _GSHADOW_H -#include #include +#include #define GSHADOW _PATH_GSHADOW struct sgrp { - char *sg_namp; - char *sg_passwd; - char **sg_adm; - char **sg_mem; + char *sg_namp; + char *sg_passwd; + char **sg_adm; + char **sg_mem; }; #ifndef __MLIBC_ABI_ONLY @@ -19,7 +19,13 @@ struct sgrp { extern "C" { #endif -int getsgnam_r(const char *__name, struct sgrp *__result_buf, char *__buffer, size_t __len, struct sgrp **__result); +int getsgnam_r( + const char *__name, + struct sgrp *__result_buf, + char *__buffer, + size_t __len, + struct sgrp **__result +); #ifdef __cplusplus } diff --git a/options/glibc/include/mlibc/glibc-sysdeps.hpp b/options/glibc/include/mlibc/glibc-sysdeps.hpp index a3888ce248..2c3cd0d323 100644 --- a/options/glibc/include/mlibc/glibc-sysdeps.hpp +++ b/options/glibc/include/mlibc/glibc-sysdeps.hpp @@ -1,7 +1,7 @@ #ifndef MLIBC_GLIBC_SYSDEPS #define MLIBC_GLIBC_SYSDEPS -namespace [[gnu::visibility("hidden")]] mlibc { +namespace [[gnu::visibility("hidden")]] mlibc { [[gnu::weak]] int sys_ioctl(int fd, unsigned long request, void *arg, int *result); [[gnu::weak]] int sys_tgkill(int tgid, int tid, int sig); diff --git a/options/glibc/include/net/ethernet.h b/options/glibc/include/net/ethernet.h index 8dac98ae0d..5e674375b8 100644 --- a/options/glibc/include/net/ethernet.h +++ b/options/glibc/include/net/ethernet.h @@ -2,15 +2,15 @@ #define _NET_ETHERNET_H #include -#include #include +#include #ifdef __cplusplus extern "C" { #endif #if __MLIBC_LINUX_OPTION -# include +#include #endif /* __MLIBC_LINUX_OPTION */ #define ETHERTYPE_PUP 0x0200 diff --git a/options/glibc/include/netax25/ax25.h b/options/glibc/include/netax25/ax25.h index 3fb82da9d3..3137d3aff8 100644 --- a/options/glibc/include/netax25/ax25.h +++ b/options/glibc/include/netax25/ax25.h @@ -4,23 +4,23 @@ #include #include -#define AX25_VALUES_IPDEFMODE 0 -#define AX25_VALUES_AXDEFMODE 1 -#define AX25_VALUES_NETROM 2 -#define AX25_VALUES_TEXT 3 -#define AX25_VALUES_BACKOFF 4 -#define AX25_VALUES_CONMODE 5 -#define AX25_VALUES_WINDOW 6 -#define AX25_VALUES_EWINDOW 7 -#define AX25_VALUES_T1 8 -#define AX25_VALUES_T2 9 -#define AX25_VALUES_T3 10 -#define AX25_VALUES_N2 11 -#define AX25_VALUES_DIGI 12 -#define AX25_VALUES_IDLE 13 -#define AX25_VALUES_PACLEN 14 -#define AX25_VALUES_IPMAXQUEUE 15 -#define AX25_MAX_VALUES 20 +#define AX25_VALUES_IPDEFMODE 0 +#define AX25_VALUES_AXDEFMODE 1 +#define AX25_VALUES_NETROM 2 +#define AX25_VALUES_TEXT 3 +#define AX25_VALUES_BACKOFF 4 +#define AX25_VALUES_CONMODE 5 +#define AX25_VALUES_WINDOW 6 +#define AX25_VALUES_EWINDOW 7 +#define AX25_VALUES_T1 8 +#define AX25_VALUES_T2 9 +#define AX25_VALUES_T3 10 +#define AX25_VALUES_N2 11 +#define AX25_VALUES_DIGI 12 +#define AX25_VALUES_IDLE 13 +#define AX25_VALUES_PACLEN 14 +#define AX25_VALUES_IPMAXQUEUE 15 +#define AX25_MAX_VALUES 20 typedef struct { char ax25_call[7]; diff --git a/options/glibc/include/netinet/in_systm.h b/options/glibc/include/netinet/in_systm.h index 131de898fb..474adbaa02 100644 --- a/options/glibc/include/netinet/in_systm.h +++ b/options/glibc/include/netinet/in_systm.h @@ -2,6 +2,4 @@ #ifndef _NETINET_IN_SYSTM_H #define _NETINET_IN_SYSTM_H - - #endif /* _NETINET_IN_SYSTM_H */ diff --git a/options/glibc/include/netipx/ipx.h b/options/glibc/include/netipx/ipx.h index 7b5c774207..0a765f2bbc 100644 --- a/options/glibc/include/netipx/ipx.h +++ b/options/glibc/include/netipx/ipx.h @@ -2,8 +2,8 @@ #define _NETIPX_IPX_H #include -#include #include +#include typedef struct ipx_config_data { unsigned char ipxcfg_auto_select_primary; diff --git a/options/glibc/include/paths.h b/options/glibc/include/paths.h index b5f3faea65..ae40714ec9 100644 --- a/options/glibc/include/paths.h +++ b/options/glibc/include/paths.h @@ -4,34 +4,34 @@ #ifndef _PATHS_H #define _PATHS_H -#define _PATH_DEFPATH "/usr/local/bin:/bin:/usr/bin" -#define _PATH_STDPATH "/bin:/usr/bin:/sbin:/usr/sbin" +#define _PATH_DEFPATH "/usr/local/bin:/bin:/usr/bin" +#define _PATH_STDPATH "/bin:/usr/bin:/sbin:/usr/sbin" -#define _PATH_BSHELL "/bin/sh" -#define _PATH_CONSOLE "/dev/console" -#define _PATH_DEVNULL "/dev/null" -#define _PATH_GSHADOW "/etc/gshadow" -#define _PATH_KLOG "/proc/kmsg" -#define _PATH_LASTLOG "/var/log/lastlog" -#define _PATH_MAILDIR "/var/mail" -#define _PATH_MAN "/usr/share/man" -#define _PATH_MNTTAB "/etc/fstab" -#define _PATH_MOUNTED "/etc/mtab" -#define _PATH_NOLOGIN "/etc/nologin" -#define _PATH_PRESERVE "/var/lib" -#define _PATH_SENDMAIL "/usr/sbin/sendmail" -#define _PATH_SHADOW "/etc/shadow" -#define _PATH_SHELLS "/etc/shells" -#define _PATH_TTY "/dev/tty" -#define _PATH_UTMP "/dev/null/utmp" -#define _PATH_VI "/usr/bin/vi" -#define _PATH_WTMP "/dev/null/wtmp" +#define _PATH_BSHELL "/bin/sh" +#define _PATH_CONSOLE "/dev/console" +#define _PATH_DEVNULL "/dev/null" +#define _PATH_GSHADOW "/etc/gshadow" +#define _PATH_KLOG "/proc/kmsg" +#define _PATH_LASTLOG "/var/log/lastlog" +#define _PATH_MAILDIR "/var/mail" +#define _PATH_MAN "/usr/share/man" +#define _PATH_MNTTAB "/etc/fstab" +#define _PATH_MOUNTED "/etc/mtab" +#define _PATH_NOLOGIN "/etc/nologin" +#define _PATH_PRESERVE "/var/lib" +#define _PATH_SENDMAIL "/usr/sbin/sendmail" +#define _PATH_SHADOW "/etc/shadow" +#define _PATH_SHELLS "/etc/shells" +#define _PATH_TTY "/dev/tty" +#define _PATH_UTMP "/dev/null/utmp" +#define _PATH_VI "/usr/bin/vi" +#define _PATH_WTMP "/dev/null/wtmp" -#define _PATH_DEV "/dev/" -#define _PATH_TMP "/tmp/" -#define _PATH_VARDB "/var/lib/misc/" -#define _PATH_VARRUN "/var/run/" -#define _PATH_VARTMP "/var/tmp/" +#define _PATH_DEV "/dev/" +#define _PATH_TMP "/tmp/" +#define _PATH_VARDB "/var/lib/misc/" +#define _PATH_VARRUN "/var/run/" +#define _PATH_VARTMP "/var/tmp/" #ifdef _GNU_SOURCE #define _PATH_UTMPX _PATH_UTMP diff --git a/options/glibc/include/printf.h b/options/glibc/include/printf.h index b6b86b9c99..307aabfdcf 100644 --- a/options/glibc/include/printf.h +++ b/options/glibc/include/printf.h @@ -1,38 +1,29 @@ -#ifndef _PRINTF_H -#define _PRINTF_H +#ifndef _PRINTF_H +#define _PRINTF_H #ifdef __cplusplus extern "C" { #endif -#include #include +#include #ifndef __MLIBC_ABI_ONLY /* This seems to be a glibc thing, so constants are from glibc */ -size_t parse_printf_format(const char * __restrict __format, size_t __size, int * __restrict __argtypes); +size_t +parse_printf_format(const char *__restrict __format, size_t __size, int *__restrict __argtypes); #endif /* !__MLIBC_ABI_ONLY */ -enum { - PA_INT, - PA_CHAR, - PA_WCHAR, - PA_STRING, - PA_WSTRING, - PA_POINTER, - PA_FLOAT, - PA_DOUBLE, - PA_LAST -}; - -#define PA_FLAG_MASK 0xff00 -#define PA_FLAG_LONG_LONG (1 << 8) -#define PA_FLAG_LONG_DOUBLE PA_FLAG_LONG_LONG -#define PA_FLAG_LONG (1 << 9) -#define PA_FLAG_SHORT (1 << 10) -#define PA_FLAG_PTR (1 << 11) +enum { PA_INT, PA_CHAR, PA_WCHAR, PA_STRING, PA_WSTRING, PA_POINTER, PA_FLOAT, PA_DOUBLE, PA_LAST }; + +#define PA_FLAG_MASK 0xff00 +#define PA_FLAG_LONG_LONG (1 << 8) +#define PA_FLAG_LONG_DOUBLE PA_FLAG_LONG_LONG +#define PA_FLAG_LONG (1 << 9) +#define PA_FLAG_SHORT (1 << 10) +#define PA_FLAG_PTR (1 << 11) #ifdef __cplusplus } diff --git a/options/glibc/include/resolv.h b/options/glibc/include/resolv.h index cb97c9b816..dc57233d3a 100644 --- a/options/glibc/include/resolv.h +++ b/options/glibc/include/resolv.h @@ -3,16 +3,16 @@ #include -#define RES_INIT 0x00000001 -#define RES_DEBUG 0x00000002 -#define RES_USEVC 0x00000008 -#define RES_IGNTC 0x00000020 -#define RES_RECURSE 0x00000040 +#define RES_INIT 0x00000001 +#define RES_DEBUG 0x00000002 +#define RES_USEVC 0x00000008 +#define RES_IGNTC 0x00000020 +#define RES_RECURSE 0x00000040 #define RES_DEFNAMES 0x00000080 #define RES_STAYOPEN 0x00000100 -#define RES_DNSRCH 0x00000200 +#define RES_DNSRCH 0x00000200 -#define MAXNS 3 +#define MAXNS 3 #define MAXDNSRCH 6 #define _PATH_RESCONF "/etc/resolv.conf" @@ -23,11 +23,15 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -int dn_expand(const unsigned char *__msg, const unsigned char *__eomorig, - const unsigned char *__comp_dn, char *__exp_dn, int __size); +int dn_expand( + const unsigned char *__msg, + const unsigned char *__eomorig, + const unsigned char *__comp_dn, + char *__exp_dn, + int __size +); -int res_query(const char *__dname, int __class, int __type, - unsigned char *__answer, int __anslen); +int res_query(const char *__dname, int __class, int __type, unsigned char *__answer, int __anslen); int res_init(void); @@ -43,8 +47,8 @@ typedef struct __res_state { struct sockaddr_in nsaddr_list[MAXNS]; char *dnsrch[MAXDNSRCH + 1]; char defdname[256]; - unsigned ndots:4; - unsigned nsort:4; + unsigned ndots : 4; + unsigned nsort : 4; union { char pad[52]; struct { @@ -53,7 +57,7 @@ typedef struct __res_state { int nssocks[MAXNS]; uint16_t nscount6; uint16_t nsinit; - struct sockaddr_in6 *nsaddrs[MAXNS]; + struct sockaddr_in6 *nsaddrs[MAXNS]; unsigned int _initstamp[2]; } _ext; } _u; diff --git a/options/glibc/include/shadow.h b/options/glibc/include/shadow.h index 58844589ef..286281c79b 100644 --- a/options/glibc/include/shadow.h +++ b/options/glibc/include/shadow.h @@ -1,9 +1,9 @@ #ifndef _SHADOW_H #define _SHADOW_H +#include #include #include -#include #ifdef __cplusplus extern "C" { @@ -29,7 +29,8 @@ int putspent(const struct spwd *__sp, FILE *__f); int lckpwdf(void); int ulckpwdf(void); struct spwd *getspnam(const char *__name); -int getspnam_r(const char *__name, struct spwd *__sp, char *__buf, size_t __size, struct spwd **__res); +int +getspnam_r(const char *__name, struct spwd *__sp, char *__buf, size_t __size, struct spwd **__res); struct spwd *fgetspent(FILE *__f); void endspent(void); diff --git a/options/glibc/include/sys/dir.h b/options/glibc/include/sys/dir.h index eff112cb9a..7bbd490b0e 100644 --- a/options/glibc/include/sys/dir.h +++ b/options/glibc/include/sys/dir.h @@ -3,6 +3,6 @@ #include -#define direct dirent +#define direct dirent #endif diff --git a/options/glibc/include/sys/io.h b/options/glibc/include/sys/io.h index 1ee22f2bea..a96471f9a5 100644 --- a/options/glibc/include/sys/io.h +++ b/options/glibc/include/sys/io.h @@ -18,86 +18,104 @@ __attribute__((deprecated)) int iopl(int __level); #ifdef __x86_64__ __MLIBC_INLINE_DEFINITION unsigned char inb(unsigned short int __port) { unsigned char __value; - __asm__ __volatile__ ("inb %w1,%0":"=a" (__value):"Nd" (__port)); + __asm__ __volatile__("inb %w1,%0" : "=a"(__value) : "Nd"(__port)); return __value; } __MLIBC_INLINE_DEFINITION unsigned char inb_p(unsigned short int __port) { unsigned char __value; - __asm__ __volatile__ ("inb %w1,%0\noutb %%al,$0x80":"=a" (__value):"Nd" (__port)); + __asm__ __volatile__("inb %w1,%0\noutb %%al,$0x80" : "=a"(__value) : "Nd"(__port)); return __value; } __MLIBC_INLINE_DEFINITION unsigned short int inw(unsigned short int __port) { unsigned short __value; - __asm__ __volatile__ ("inw %w1,%0":"=a" (__value):"Nd" (__port)); + __asm__ __volatile__("inw %w1,%0" : "=a"(__value) : "Nd"(__port)); return __value; } __MLIBC_INLINE_DEFINITION unsigned short int inw_p(unsigned short int __port) { unsigned short int __value; - __asm__ __volatile__ ("inw %w1,%0\noutb %%al,$0x80":"=a" (__value):"Nd" (__port)); + __asm__ __volatile__("inw %w1,%0\noutb %%al,$0x80" : "=a"(__value) : "Nd"(__port)); return __value; } __MLIBC_INLINE_DEFINITION unsigned int inl(unsigned short int __port) { unsigned int __value; - __asm__ __volatile__ ("inl %w1,%0":"=a" (__value):"Nd" (__port)); + __asm__ __volatile__("inl %w1,%0" : "=a"(__value) : "Nd"(__port)); return __value; } __MLIBC_INLINE_DEFINITION unsigned int inl_p(unsigned short int __port) { unsigned int __value; - __asm__ __volatile__ ("inl %w1,%0\noutb %%al,$0x80":"=a" (__value):"Nd" (__port)); + __asm__ __volatile__("inl %w1,%0\noutb %%al,$0x80" : "=a"(__value) : "Nd"(__port)); return __value; } __MLIBC_INLINE_DEFINITION void outb(unsigned char value, unsigned short int __port) { - __asm__ __volatile__ ("outb %b0,%w1": :"a" (value), "Nd" (__port)); + __asm__ __volatile__("outb %b0,%w1" : : "a"(value), "Nd"(__port)); } __MLIBC_INLINE_DEFINITION void outb_p(unsigned char __value, unsigned short int __port) { - __asm__ __volatile__ ("outb %b0,%w1\noutb %%al,$0x80": :"a" (__value), "Nd" (__port)); + __asm__ __volatile__("outb %b0,%w1\noutb %%al,$0x80" : : "a"(__value), "Nd"(__port)); } __MLIBC_INLINE_DEFINITION void outw(unsigned short int __value, unsigned short int __port) { - __asm__ __volatile__ ("outw %w0,%w1": :"a" (__value), "Nd" (__port)); + __asm__ __volatile__("outw %w0,%w1" : : "a"(__value), "Nd"(__port)); } __MLIBC_INLINE_DEFINITION void outw_p(unsigned short int __value, unsigned short int __port) { - __asm__ __volatile__ ("outw %w0,%w1\noutb %%al,$0x80": :"a" (__value), "Nd" (__port)); + __asm__ __volatile__("outw %w0,%w1\noutb %%al,$0x80" : : "a"(__value), "Nd"(__port)); } __MLIBC_INLINE_DEFINITION void outl(unsigned int __value, unsigned short int __port) { - __asm__ __volatile__ ("outl %0,%w1": :"a" (__value), "Nd" (__port)); + __asm__ __volatile__("outl %0,%w1" : : "a"(__value), "Nd"(__port)); } __MLIBC_INLINE_DEFINITION void outl_p(unsigned int __value, unsigned short int __port) { - __asm__ __volatile__ ("outl %0,%w1\noutb %%al,$0x80": :"a" (__value), "Nd" (__port)); + __asm__ __volatile__("outl %0,%w1\noutb %%al,$0x80" : : "a"(__value), "Nd"(__port)); } -__MLIBC_INLINE_DEFINITION void insb(unsigned short int __port, void *__addr, unsigned long int __count) { - __asm__ __volatile__ ("cld ; rep ; insb":"=D" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); +__MLIBC_INLINE_DEFINITION void +insb(unsigned short int __port, void *__addr, unsigned long int __count) { + __asm__ __volatile__("cld ; rep ; insb" + : "=D"(__addr), "=c"(__count) + : "d"(__port), "0"(__addr), "1"(__count)); } -__MLIBC_INLINE_DEFINITION void insw(unsigned short int __port, void *__addr, unsigned long int __count) { - __asm__ __volatile__ ("cld ; rep ; insw":"=D" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); +__MLIBC_INLINE_DEFINITION void +insw(unsigned short int __port, void *__addr, unsigned long int __count) { + __asm__ __volatile__("cld ; rep ; insw" + : "=D"(__addr), "=c"(__count) + : "d"(__port), "0"(__addr), "1"(__count)); } -__MLIBC_INLINE_DEFINITION void insl(unsigned short int __port, void *__addr, unsigned long int __count) { - __asm__ __volatile__ ("cld ; rep ; insl":"=D" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); +__MLIBC_INLINE_DEFINITION void +insl(unsigned short int __port, void *__addr, unsigned long int __count) { + __asm__ __volatile__("cld ; rep ; insl" + : "=D"(__addr), "=c"(__count) + : "d"(__port), "0"(__addr), "1"(__count)); } -__MLIBC_INLINE_DEFINITION void outsb(unsigned short int __port, const void *__addr, unsigned long int __count) { - __asm__ __volatile__ ("cld ; rep ; outsb":"=S" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); +__MLIBC_INLINE_DEFINITION void +outsb(unsigned short int __port, const void *__addr, unsigned long int __count) { + __asm__ __volatile__("cld ; rep ; outsb" + : "=S"(__addr), "=c"(__count) + : "d"(__port), "0"(__addr), "1"(__count)); } -__MLIBC_INLINE_DEFINITION void outsw(unsigned short int __port, const void *__addr, unsigned long int __count) { - __asm__ __volatile__ ("cld ; rep ; outsw":"=S" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); +__MLIBC_INLINE_DEFINITION void +outsw(unsigned short int __port, const void *__addr, unsigned long int __count) { + __asm__ __volatile__("cld ; rep ; outsw" + : "=S"(__addr), "=c"(__count) + : "d"(__port), "0"(__addr), "1"(__count)); } -__MLIBC_INLINE_DEFINITION void outsl(unsigned short int __port, const void *__addr, unsigned long int __count) { - __asm__ __volatile__ ("cld ; rep ; outsl":"=S" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); +__MLIBC_INLINE_DEFINITION void +outsl(unsigned short int __port, const void *__addr, unsigned long int __count) { + __asm__ __volatile__("cld ; rep ; outsl" + : "=S"(__addr), "=c"(__count) + : "d"(__port), "0"(__addr), "1"(__count)); } #endif diff --git a/options/glibc/include/sys/ioctl.h b/options/glibc/include/sys/ioctl.h index 3f5e0a473c..d5df8bf0b5 100644 --- a/options/glibc/include/sys/ioctl.h +++ b/options/glibc/include/sys/ioctl.h @@ -1,14 +1,14 @@ #ifndef _SYS_IOCTL_H #define _SYS_IOCTL_H -#include #include +#include /* On Linux, sys/ioctl.h includes the termios ioctls. */ #if __MLIBC_LINUX_OPTION -# include -# include -# include +#include +#include +#include #endif #ifdef __cplusplus diff --git a/options/glibc/include/sys/kd.h b/options/glibc/include/sys/kd.h index 285c694bd0..f06e99499f 100644 --- a/options/glibc/include/sys/kd.h +++ b/options/glibc/include/sys/kd.h @@ -3,15 +3,15 @@ /* Make sure the header is not loaded. */ #ifndef _LINUX_TYPES_H -# define _LINUX_TYPES_H 1 -# define __undef_LINUX_TYPES_H +#define _LINUX_TYPES_H 1 +#define __undef_LINUX_TYPES_H #endif #include #ifdef __undef_LINUX_TYPES_H -# undef _LINUX_TYPES_H -# undef __undef_LINUX_TYPES_H +#undef _LINUX_TYPES_H +#undef __undef_LINUX_TYPES_H #endif #endif /* _SYS_KD_H */ diff --git a/options/glibc/include/sys/mtio.h b/options/glibc/include/sys/mtio.h index c2f9d98aeb..4f1b33c528 100644 --- a/options/glibc/include/sys/mtio.h +++ b/options/glibc/include/sys/mtio.h @@ -35,19 +35,19 @@ struct mtconfiginfo { unsigned long int debug; - unsigned have_dens:1; - unsigned have_bsf:1; - unsigned have_fsr:1; - unsigned have_bsr:1; - unsigned have_eod:1; - unsigned have_seek:1; - unsigned have_tell:1; - unsigned have_ras1:1; - unsigned have_ras2:1; - unsigned have_ras3:1; - unsigned have_qfa:1; + unsigned have_dens : 1; + unsigned have_bsf : 1; + unsigned have_fsr : 1; + unsigned have_bsr : 1; + unsigned have_eod : 1; + unsigned have_seek : 1; + unsigned have_tell : 1; + unsigned have_ras1 : 1; + unsigned have_ras2 : 1; + unsigned have_ras3 : 1; + unsigned have_qfa : 1; - unsigned pad1:5; + unsigned pad1 : 5; char reserved[10]; }; diff --git a/options/glibc/include/sys/personality.h b/options/glibc/include/sys/personality.h index f4173eee75..ce40cb5cc1 100644 --- a/options/glibc/include/sys/personality.h +++ b/options/glibc/include/sys/personality.h @@ -6,7 +6,7 @@ extern "C" { #endif enum { - UNAME26 = 0x0020000, + UNAME26 = 0x0020000, ADDR_NO_RANDOMIZE = 0x0040000, FDPIC_FUNCPTRS = 0x0080000, MMAP_PAGE_ZERO = 0x0100000, @@ -15,7 +15,7 @@ enum { ADDR_LIMIT_32BIT = 0x0800000, SHORT_INODE = 0x1000000, WHOLE_SECONDS = 0x2000000, - STICKY_TIMEOUTS = 0x4000000, + STICKY_TIMEOUTS = 0x4000000, ADDR_LIMIT_3GB = 0x8000000 }; diff --git a/options/glibc/include/sys/procfs.h b/options/glibc/include/sys/procfs.h index 82fee9a666..05c3350a34 100644 --- a/options/glibc/include/sys/procfs.h +++ b/options/glibc/include/sys/procfs.h @@ -1,9 +1,9 @@ #ifndef _SYS_PROCFS_H #define _SYS_PROCFS_H -#include -#include #include +#include +#include #ifdef __cplusplus extern "C" { @@ -11,7 +11,7 @@ extern "C" { typedef unsigned long elf_greg_t; -#define ELF_NGREG (sizeof (struct user_regs_struct) / sizeof (elf_greg_t)) +#define ELF_NGREG (sizeof(struct user_regs_struct) / sizeof(elf_greg_t)) typedef elf_greg_t elf_gregset_t[ELF_NGREG]; typedef struct user_fpregs_struct elf_fpregset_t; diff --git a/options/glibc/include/sys/timeb.h b/options/glibc/include/sys/timeb.h index bf6d718953..06edc35ddf 100644 --- a/options/glibc/include/sys/timeb.h +++ b/options/glibc/include/sys/timeb.h @@ -5,8 +5,6 @@ extern "C" { #endif - - #ifdef __cplusplus } #endif diff --git a/options/glibc/include/sys/ucontext.h b/options/glibc/include/sys/ucontext.h index cae57f097a..1ca16ef1dc 100644 --- a/options/glibc/include/sys/ucontext.h +++ b/options/glibc/include/sys/ucontext.h @@ -5,8 +5,6 @@ extern "C" { #endif - - #ifdef __cplusplus } #endif diff --git a/options/glibc/include/sys/user.h b/options/glibc/include/sys/user.h index 7963e68341..76b9b4c769 100644 --- a/options/glibc/include/sys/user.h +++ b/options/glibc/include/sys/user.h @@ -33,7 +33,7 @@ struct user { unsigned long start_stack; long signal; int reserved; - struct user_regs_struct *u_ar0; + struct user_regs_struct *u_ar0; struct user_fpregs_struct *u_fpstate; unsigned long magic; char u_comm[32]; diff --git a/options/glibc/include/sysexits.h b/options/glibc/include/sysexits.h index b2969daa89..b0921f3b3e 100644 --- a/options/glibc/include/sysexits.h +++ b/options/glibc/include/sysexits.h @@ -1,24 +1,24 @@ #ifndef _SYSEXITS_H #define _SYSEXITS_H -#define EX_OK 0 -#define EX_USAGE 64 -#define EX_DATAERR 65 -#define EX_NOINPUT 66 -#define EX_NOUSER 67 -#define EX_NOHOST 68 -#define EX_UNAVAILABLE 69 -#define EX_SOFTWARE 70 -#define EX_OSERR 71 -#define EX_OSFILE 72 -#define EX_CANTCREAT 73 -#define EX_IOERR 74 -#define EX_TEMPFAIL 75 -#define EX_PROTOCOL 76 -#define EX_NOPERM 77 -#define EX_CONFIG 78 +#define EX_OK 0 +#define EX_USAGE 64 +#define EX_DATAERR 65 +#define EX_NOINPUT 66 +#define EX_NOUSER 67 +#define EX_NOHOST 68 +#define EX_UNAVAILABLE 69 +#define EX_SOFTWARE 70 +#define EX_OSERR 71 +#define EX_OSFILE 72 +#define EX_CANTCREAT 73 +#define EX_IOERR 74 +#define EX_TEMPFAIL 75 +#define EX_PROTOCOL 76 +#define EX_NOPERM 77 +#define EX_CONFIG 78 -#define EX__BASE 64 -#define EX__MAX 78 +#define EX__BASE 64 +#define EX__MAX 78 #endif /* _SYSEXITS_H */ diff --git a/options/internal/aarch64-include/mlibc/thread.hpp b/options/internal/aarch64-include/mlibc/thread.hpp index b62d832322..791d11b66e 100644 --- a/options/internal/aarch64-include/mlibc/thread.hpp +++ b/options/internal/aarch64-include/mlibc/thread.hpp @@ -1,20 +1,20 @@ #pragma once -#include #include +#include namespace mlibc { inline Tcb *get_current_tcb() { // On AArch64, TPIDR_EL0 points to 0x10 bytes before the first TLS block. uintptr_t ptr; - asm ("mrs %0, tpidr_el0" : "=r"(ptr)); + asm("mrs %0, tpidr_el0" : "=r"(ptr)); return reinterpret_cast(ptr + 0x10 - sizeof(Tcb)); } inline uintptr_t get_sp() { uintptr_t sp; - asm ("mov %0, sp" : "=r"(sp)); + asm("mov %0, sp" : "=r"(sp)); return sp; } diff --git a/options/internal/gcc-extra/cxxabi.cpp b/options/internal/gcc-extra/cxxabi.cpp index dff7d94181..520e05081a 100644 --- a/options/internal/gcc-extra/cxxabi.cpp +++ b/options/internal/gcc-extra/cxxabi.cpp @@ -6,9 +6,9 @@ // Note that G++ complains if we make the operator hidden, // thus we use it's mangled name as a workaround. #if defined(__clang__) - extern "C" [[gnu::visibility("hidden")]] void _ZdlPv() { // operator delete (void *, size_t) - __ensure(!"operator delete called! delete expressions cannot be used in mlibc."); - } +extern "C" [[gnu::visibility("hidden")]] void _ZdlPv() { // operator delete (void *, size_t) + __ensure(!"operator delete called! delete expressions cannot be used in mlibc."); +} #endif extern "C" [[gnu::visibility("hidden")]] void _ZdlPvj() { // operator delete (void *, unsigned int) diff --git a/options/internal/gcc/guard-abi.cpp b/options/internal/gcc/guard-abi.cpp index d68045e619..05e9fba85c 100644 --- a/options/internal/gcc/guard-abi.cpp +++ b/options/internal/gcc/guard-abi.cpp @@ -16,17 +16,16 @@ struct Guard { void lock() { uint32_t v = 0; - if(__atomic_compare_exchange_n(&mutex, &v, Guard::locked, false, - __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) + if (__atomic_compare_exchange_n( + &mutex, &v, Guard::locked, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED + )) return; mlibc::sys_libc_log("__cxa_guard_acquire contention"); __builtin_trap(); } - void unlock() { - __atomic_store_n(&mutex, 0, __ATOMIC_RELEASE); - } + void unlock() { __atomic_store_n(&mutex, 0, __ATOMIC_RELEASE); } // the first byte's meaning is fixed by the ABI. // it indicates whether initialization has already been completed. @@ -40,31 +39,30 @@ struct Guard { static_assert(sizeof(Guard) == sizeof(int64_t)); -} // namespace { } +} // namespace -extern "C" [[ gnu::visibility("hidden") ]] void __cxa_pure_virtual() { +extern "C" [[gnu::visibility("hidden")]] void __cxa_pure_virtual() { mlibc::panicLogger() << "mlibc: Pure virtual function called from IP " - << (void *)__builtin_return_address(0) << frg::endlog; + << (void *)__builtin_return_address(0) << frg::endlog; } -extern "C" [[ gnu::visibility("hidden") ]] int __cxa_guard_acquire(int64_t *ptr) { +extern "C" [[gnu::visibility("hidden")]] int __cxa_guard_acquire(int64_t *ptr) { auto guard = reinterpret_cast(ptr); guard->lock(); // relaxed ordering is sufficient because // Guard::complete is only modified while the mutex is held. - if(__atomic_load_n(&guard->complete, __ATOMIC_RELAXED)) { + if (__atomic_load_n(&guard->complete, __ATOMIC_RELAXED)) { guard->unlock(); return 0; - }else{ + } else { return 1; } } -extern "C" [[ gnu::visibility("hidden") ]] void __cxa_guard_release(int64_t *ptr) { +extern "C" [[gnu::visibility("hidden")]] void __cxa_guard_release(int64_t *ptr) { auto guard = reinterpret_cast(ptr); // do a store-release so that compiler generated code can skip calling // __cxa_guard_acquire by doing a load-acquire on Guard::complete. __atomic_store_n(&guard->complete, 1, __ATOMIC_RELEASE); guard->unlock(); } - diff --git a/options/internal/gcc/stack_protector.cpp b/options/internal/gcc/stack_protector.cpp index e5e50f0914..0d74970678 100644 --- a/options/internal/gcc/stack_protector.cpp +++ b/options/internal/gcc/stack_protector.cpp @@ -1,14 +1,14 @@ -#include -#include #include #include +#include +#include uintptr_t __stack_chk_guard = 0; namespace mlibc { void initStackGuard(void *entropy) { - if(entropy != nullptr) { + if (entropy != nullptr) { memcpy(&__stack_chk_guard, entropy, sizeof(__stack_chk_guard)); } else { // If no entropy is available, set it to the terminator canary @@ -28,4 +28,3 @@ extern "C" [[noreturn]] void __stack_chk_fail() { extern "C" [[noreturn, gnu::visibility("hidden")]] void __stack_chk_fail_local() { __stack_chk_fail(); }; - diff --git a/options/internal/generic/allocator.cpp b/options/internal/generic/allocator.cpp index 8b61fd57cd..313eae915d 100644 --- a/options/internal/generic/allocator.cpp +++ b/options/internal/generic/allocator.cpp @@ -3,9 +3,9 @@ #include #include +#include #include #include -#include #if !MLIBC_DEBUG_ALLOCATOR @@ -39,17 +39,16 @@ void VirtualAllocator::unmap(uintptr_t address, size_t length) { #else namespace { - struct AllocatorMeta { - size_t allocatedSize; - size_t pagesSize; - frg::array magic; - }; - - constexpr frg::array allocatorMagic { - 0x6d4bbb9f3446e83f, 0x25e213a7a7f9f954, - 0x1a3c667586538bef, 0x994f34ff71c090bc - }; -} // namespace anonymous +struct AllocatorMeta { + size_t allocatedSize; + size_t pagesSize; + frg::array magic; +}; + +constexpr frg::array allocatorMagic{ + 0x6d4bbb9f3446e83f, 0x25e213a7a7f9f954, 0x1a3c667586538bef, 0x994f34ff71c090bc +}; +} // namespace // Turn vm_unmap calls in free into vm_map(..., PROT_NONE, ...) calls to prevent // those addresses from being reused. This is useful for detecting situations like this: @@ -78,8 +77,9 @@ constexpr size_t pointerAlignment = 16; // TODO(qookie): Support this. Perhaps by overallocating by 2x and then picking // an offset that guarantees the desired alignment. static_assert(pointerAlignment <= 4096, "Pointer aligment of more than 4096 bytes is unsupported"); -static_assert(!(pointerAlignment & (pointerAlignment - 1)), - "Pointer aligment must be a power of 2"); +static_assert( + !(pointerAlignment & (pointerAlignment - 1)), "Pointer aligment must be a power of 2" +); constexpr size_t pageSize = 0x1000; @@ -91,12 +91,24 @@ void *MemoryAllocator::allocate(size_t size) { // Two extra pages for metadata in front and guard page at the end // Reserve the whole region as PROT_NONE... - if (int e = mlibc::sys_vm_map(nullptr, pg_size + pageSize * 2, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0, &ptr)) - mlibc::panicLogger() << "sys_vm_map failed in MemoryAllocator::allocate (errno " << e << ")" << frg::endlog; + if (int e = mlibc::sys_vm_map( + nullptr, pg_size + pageSize * 2, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0, &ptr + )) + mlibc::panicLogger() << "sys_vm_map failed in MemoryAllocator::allocate (errno " << e << ")" + << frg::endlog; // ...Then replace pages to make them accessible, excluding the guard page - if (int e = mlibc::sys_vm_map(ptr, pg_size + pageSize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0, &ptr)) - mlibc::panicLogger() << "sys_vm_map failed in MemoryAllocator::allocate (errno " << e << ")" << frg::endlog; + if (int e = mlibc::sys_vm_map( + ptr, + pg_size + pageSize, + PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, + -1, + 0, + &ptr + )) + mlibc::panicLogger() << "sys_vm_map failed in MemoryAllocator::allocate (errno " << e << ")" + << frg::endlog; void *meta = ptr; void *out_page = reinterpret_cast(reinterpret_cast(ptr) + pageSize); @@ -129,7 +141,8 @@ void MemoryAllocator::free(void *ptr) { AllocatorMeta *meta = reinterpret_cast(page_addr - pageSize); if (meta->magic != allocatorMagic) - mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::free" << frg::endlog; + mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::free" + << frg::endlog; deallocate(ptr, meta->allocatedSize); } @@ -139,24 +152,38 @@ void MemoryAllocator::deallocate(void *ptr, size_t size) { return; if constexpr (logAllocations) - mlibc::infoLogger() << "MemoryAllocator::deallocate(" << ptr << ", " << size << ")" << frg::endlog; + mlibc::infoLogger() << "MemoryAllocator::deallocate(" << ptr << ", " << size << ")" + << frg::endlog; uintptr_t page_addr = reinterpret_cast(ptr) & ~size_t{pageSize - 1}; AllocatorMeta *meta = reinterpret_cast(page_addr - pageSize); if (meta->magic != allocatorMagic) - mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::deallocate" << frg::endlog; + mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::deallocate" + << frg::endlog; if (size != meta->allocatedSize) - mlibc::panicLogger() << "Invalid allocated size in metadata in MemoryAllocator::deallocate (given " << size << ", stored " << meta->allocatedSize << ")" << frg::endlog; + mlibc::panicLogger( + ) << "Invalid allocated size in metadata in MemoryAllocator::deallocate (given " + << size << ", stored " << meta->allocatedSize << ")" << frg::endlog; if constexpr (neverReleaseVa) { void *unused; - if (int e = mlibc::sys_vm_map(meta, meta->pagesSize + pageSize * 2, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0, &unused)) - mlibc::panicLogger() << "sys_vm_map failed in MemoryAllocator::deallocate (errno " << e << ")" << frg::endlog; + if (int e = mlibc::sys_vm_map( + meta, + meta->pagesSize + pageSize * 2, + PROT_NONE, + MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, + -1, + 0, + &unused + )) + mlibc::panicLogger() << "sys_vm_map failed in MemoryAllocator::deallocate (errno " << e + << ")" << frg::endlog; } else { if (int e = mlibc::sys_vm_unmap(meta, meta->pagesSize + pageSize * 2)) - mlibc::panicLogger() << "sys_vm_unmap failed in MemoryAllocator::deallocate (errno " << e << ")" << frg::endlog; + mlibc::panicLogger() << "sys_vm_unmap failed in MemoryAllocator::deallocate (errno " + << e << ")" << frg::endlog; } } @@ -173,7 +200,9 @@ void *MemoryAllocator::reallocate(void *ptr, size_t size) { AllocatorMeta *meta = reinterpret_cast(page_addr - pageSize); if (meta->magic != allocatorMagic) - mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::reallocate" << frg::endlog; + mlibc::panicLogger( + ) << "Invalid allocator metadata magic in MemoryAllocator::reallocate" + << frg::endlog; memcpy(newArea, ptr, frg::min(meta->allocatedSize, size)); @@ -181,7 +210,8 @@ void *MemoryAllocator::reallocate(void *ptr, size_t size) { } if constexpr (logAllocations) - mlibc::infoLogger() << "MemoryAllocator::reallocate(" << ptr << ", " << size << ") = " << newArea << frg::endlog; + mlibc::infoLogger() << "MemoryAllocator::reallocate(" << ptr << ", " << size + << ") = " << newArea << frg::endlog; return newArea; } @@ -194,7 +224,8 @@ size_t MemoryAllocator::get_size(void *ptr) { AllocatorMeta *meta = reinterpret_cast(page_addr - pageSize); if (meta->magic != allocatorMagic) - mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::get_size" << frg::endlog; + mlibc::panicLogger() << "Invalid allocator metadata magic in MemoryAllocator::get_size" + << frg::endlog; return meta->allocatedSize; } diff --git a/options/internal/generic/charcode.cpp b/options/internal/generic/charcode.cpp index e09d5cd222..0a0a605eeb 100644 --- a/options/internal/generic/charcode.cpp +++ b/options/internal/generic/charcode.cpp @@ -11,35 +11,35 @@ struct utf8_charcode { static constexpr bool has_shift_states = false; struct decode_state { - decode_state() - : _progress{0}, _cpoint{0} { } + decode_state() : _progress{0}, _cpoint{0} {} auto progress() { return _progress; } auto cpoint() { return _cpoint; } - charcode_error operator() (code_seq &seq) { + charcode_error operator()(code_seq &seq) { auto uc = static_cast(*seq.it); - if(!_progress) { - if(!(uc & 0b1000'0000)) { + if (!_progress) { + if (!(uc & 0b1000'0000)) { // ASCII-compatible. _cpoint = uc; - }else if((uc & 0b1110'0000) == 0b1100'0000) { + } else if ((uc & 0b1110'0000) == 0b1100'0000) { _cpoint = uc & 0b1'1111; _progress = 1; - }else if((uc & 0b1111'0000) == 0b1110'0000) { + } else if ((uc & 0b1111'0000) == 0b1110'0000) { _cpoint = uc & 0b1111; _progress = 2; - }else if((uc & 0b1111'1000) == 0b1111'0000) { + } else if ((uc & 0b1111'1000) == 0b1111'0000) { _cpoint = uc & 0b111; _progress = 3; - }else{ + } else { // If the highest two bits are 0b10, this is the second (or later) unit. // Units with highest five bits = 0b11111 do not occur in valid UTF-8. - __ensure((uc & 0b1100'0000) == 0b1000'0000 - || (uc & 0b1111'1000) == 0b1111'1000); + __ensure( + (uc & 0b1100'0000) == 0b1000'0000 || (uc & 0b1111'1000) == 0b1111'1000 + ); return charcode_error::illegal_input; } - }else{ + } else { // TODO: Return an error. __ensure((uc & 0b1100'0000) == 0b1000'0000); _cpoint = (_cpoint << 6) | (uc & 0x3F); @@ -49,7 +49,7 @@ struct utf8_charcode { return charcode_error::null; } - private: + private: int _progress; codepoint _cpoint; }; @@ -57,7 +57,7 @@ struct utf8_charcode { struct encode_state { // Encodes a single character from wseq + the current state and stores it in nseq. // TODO: Convert decode_state to the same strategy. - charcode_error operator() (code_seq &nseq, code_seq &wseq) { + charcode_error operator()(code_seq &nseq, code_seq &wseq) { auto wc = *wseq.it; __ensure(wc <= 0x7F && "utf8_charcode cannot encode multibyte chars yet"); *nseq.it = wc; @@ -77,110 +77,111 @@ polymorphic_charcode::~polymorphic_charcode() = default; // TODO: There, we can use negative __mlibc_mbstate::progress to represent encoding to UTF-16. // - If G::decode_state::progress() == 0, the code point (given by cpoint()) // was decoded successfully. -template -struct polymorphic_charcode_adapter : polymorphic_charcode { +template struct polymorphic_charcode_adapter : polymorphic_charcode { polymorphic_charcode_adapter() - : polymorphic_charcode{G::preserves_7bit_units, G::has_shift_states} { } + : polymorphic_charcode{G::preserves_7bit_units, G::has_shift_states} {} - charcode_error decode(code_seq &nseq, code_seq &wseq, - __mlibc_mbstate &st) override { + charcode_error + decode(code_seq &nseq, code_seq &wseq, __mlibc_mbstate &st) override { __ensure(!st.__progress); // TODO: Update st with ds.progress() and ds.cpoint(). code_seq decode_nseq = nseq; typename G::decode_state ds; - while(decode_nseq && wseq) { + while (decode_nseq && wseq) { // Consume the next code unit. - if(auto e = ds(decode_nseq); e != charcode_error::null) + if (auto e = ds(decode_nseq); e != charcode_error::null) return e; // Produce a new code point. - if(!ds.progress()) { + if (!ds.progress()) { // "Commit" consumed code units (as there was no decode error). nseq.it = decode_nseq.it; - if(!ds.cpoint()) // Stop on null characters. + if (!ds.cpoint()) // Stop on null characters. return charcode_error::null; *wseq.it = ds.cpoint(); ++wseq.it; } } - if(ds.progress()) + if (ds.progress()) return charcode_error::input_underflow; return charcode_error::null; } - charcode_error decode_wtranscode(code_seq &nseq, code_seq &wseq, - __mlibc_mbstate &st) override { + charcode_error decode_wtranscode( + code_seq &nseq, code_seq &wseq, __mlibc_mbstate &st + ) override { __ensure(!st.__progress); // TODO: Update st with ds.progress() and ds.cpoint(). code_seq decode_nseq = nseq; typename G::decode_state ds; - while(decode_nseq && wseq) { + while (decode_nseq && wseq) { // Consume the next code unit. - if(auto e = ds(decode_nseq); e != charcode_error::null) + if (auto e = ds(decode_nseq); e != charcode_error::null) return e; // Produce a new code point. - if(!ds.progress()) { + if (!ds.progress()) { nseq.it = decode_nseq.it; // "Commit" consumed code units (as there was no decode error). - if(!ds.cpoint()) // Stop on null characters. + if (!ds.cpoint()) // Stop on null characters. return charcode_error::null; *wseq.it = ds.cpoint(); ++wseq.it; } } - if(ds.progress()) + if (ds.progress()) return charcode_error::input_underflow; return charcode_error::null; } - charcode_error decode_wtranscode_length(code_seq &nseq, size_t *n, - __mlibc_mbstate &st) override { + charcode_error + decode_wtranscode_length(code_seq &nseq, size_t *n, __mlibc_mbstate &st) override { __ensure(!st.__progress); // TODO: Update st with ds.progress() and ds.cpoint(). code_seq decode_nseq = nseq; typename G::decode_state ds; *n = 0; - while(decode_nseq) { + while (decode_nseq) { // Consume the next code unit. - if(auto e = ds(decode_nseq); e != charcode_error::null) + if (auto e = ds(decode_nseq); e != charcode_error::null) return e; - if(!ds.progress()) { + if (!ds.progress()) { nseq.it = decode_nseq.it; // "Commit" consumed code units (as there was no decode error). - if(!ds.cpoint()) // Stop on null code points. + if (!ds.cpoint()) // Stop on null code points. return charcode_error::null; ++(*n); } } - if(ds.progress()) + if (ds.progress()) return charcode_error::input_underflow; return charcode_error::null; } - charcode_error encode_wtranscode(code_seq &nseq, code_seq &wseq, - __mlibc_mbstate &st) override { + charcode_error encode_wtranscode( + code_seq &nseq, code_seq &wseq, __mlibc_mbstate &st + ) override { __ensure(!st.__progress); // TODO: Update st with es.progress() and es.cpoint(). code_seq encode_nseq = nseq; typename G::encode_state es; - while(encode_nseq && wseq) { + while (encode_nseq && wseq) { codepoint cp = *wseq.it; - if(!cp) + if (!cp) return charcode_error::null; code_seq cps{&cp, &cp + 1}; - if(auto e = es(encode_nseq, cps); e == charcode_error::dirty) { + if (auto e = es(encode_nseq, cps); e == charcode_error::dirty) { continue; - }else if(e != charcode_error::null) { + } else if (e != charcode_error::null) { return e; } __ensure(cps.it == cps.end); @@ -190,29 +191,30 @@ struct polymorphic_charcode_adapter : polymorphic_charcode { nseq.it = encode_nseq.it; } - if(encode_nseq.it != nseq.it) + if (encode_nseq.it != nseq.it) return charcode_error::output_overflow; return charcode_error::null; } - charcode_error encode_wtranscode_length(code_seq &wseq, size_t *n, - __mlibc_mbstate &st) override { + charcode_error encode_wtranscode_length( + code_seq &wseq, size_t *n, __mlibc_mbstate &st + ) override { __ensure(!st.__progress); // TODO: Update st with es.progress() and es.cpoint(). typename G::encode_state es; *n = 0; - while(wseq) { + while (wseq) { char temp[4]; code_seq encode_nseq{temp, temp + 4}; codepoint cp = *wseq.it; - if(!cp) + if (!cp) return charcode_error::null; // Consume the next code unit. code_seq cps{&cp, &cp + 1}; - if(auto e = es(encode_nseq, cps); e == charcode_error::dirty) { + if (auto e = es(encode_nseq, cps); e == charcode_error::dirty) { continue; - }else if(e != charcode_error::null) { + } else if (e != charcode_error::null) { return e; } @@ -241,4 +243,3 @@ wide_charcode *platform_wide_charcode() { } } // namespace mlibc - diff --git a/options/internal/generic/charset.cpp b/options/internal/generic/charset.cpp index c42b4f457e..3963d583bf 100644 --- a/options/internal/generic/charset.cpp +++ b/options/internal/generic/charset.cpp @@ -11,127 +11,138 @@ bool charset::is_ascii_superset() { } bool charset::is_alpha(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_alpha() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_digit(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return c >= '0' && c <= '9'; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_digit() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_xdigit(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_xdigit() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_alnum(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_alnum() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_punct(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) - return c == '!' || c == '"' || c == '#' || c == '$' || c == '%' || c == '&' - || c == '\'' || c == '(' || c == ')' || c == '*' || c == '+' || c == ',' - || c == '-' || c == '.' || c == '/' - || c == ':' || c == ';' || c == '<' || c == '=' || c == '>' || c == '?' - || c == '@' - || c == '[' || c == '\\' || c == ']' || c == '^' || c == '_' || c == '`' - || c == '{' || c == '|' || c == '}' || c == '~'; - if(c > 0x7F) + if (c <= 0x7F && is_ascii_superset()) + return c == '!' || c == '"' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || + c == '(' || c == ')' || c == '*' || c == '+' || c == ',' || c == '-' || c == '.' || + c == '/' || c == ':' || c == ';' || c == '<' || c == '=' || c == '>' || c == '?' || + c == '@' || c == '[' || c == '\\' || c == ']' || c == '^' || c == '_' || c == '`' || + c == '{' || c == '|' || c == '}' || c == '~'; + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_punct() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_graph(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return c >= 0x21 && c <= 0x7E; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_graph() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_blank(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return c == ' ' || c == '\t'; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_blank() is not implemented" - " for the full Unicode charset " << c << frg::endlog; + " for the full Unicode charset " + << c << frg::endlog; return false; } bool charset::is_space(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_space() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_print(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return c >= 0x20 && c <= 0x7E; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_print() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_lower(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return (c >= 'a' && c <= 'z'); - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_print() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } bool charset::is_upper(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) + if (c <= 0x7F && is_ascii_superset()) return (c >= 'A' && c <= 'Z'); - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::is_print() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return false; } codepoint charset::to_lower(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) - if(c >= 'A' && c <= 'Z') + if (c <= 0x7F && is_ascii_superset()) + if (c >= 'A' && c <= 'Z') return c - 'A' + 'a'; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::to_lower() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return c; } codepoint charset::to_upper(codepoint c) { - if(c <= 0x7F && is_ascii_superset()) - if(c >= 'a' && c <= 'z') + if (c <= 0x7F && is_ascii_superset()) + if (c >= 'a' && c <= 'z') return c - 'a' + 'A'; - if(c > 0x7F) + if (c > 0x7F) mlibc::infoLogger() << "mlibc: charset::to_upper() is not implemented" - " for the full Unicode charset" << frg::endlog; + " for the full Unicode charset" + << frg::endlog; return c; } @@ -141,4 +152,3 @@ charset *current_charset() { } } // namespace mlibc - diff --git a/options/internal/generic/debug.cpp b/options/internal/generic/debug.cpp index 19427c8ac2..0836ed2f2a 100644 --- a/options/internal/generic/debug.cpp +++ b/options/internal/generic/debug.cpp @@ -8,15 +8,12 @@ namespace mlibc { frg::stack_buffer_logger infoLogger; frg::stack_buffer_logger panicLogger; -void InfoSink::operator() (const char *message) { - sys_libc_log(message); -} +void InfoSink::operator()(const char *message) { sys_libc_log(message); } -void PanicSink::operator() (const char *message) { -// sys_libc_log("mlibc: Write to PanicSink"); +void PanicSink::operator()(const char *message) { + // sys_libc_log("mlibc: Write to PanicSink"); sys_libc_log(message); sys_libc_panic(); } } // namespace mlibc - diff --git a/options/internal/generic/ensure.cpp b/options/internal/generic/ensure.cpp index 57c953a239..8e8fc27a64 100644 --- a/options/internal/generic/ensure.cpp +++ b/options/internal/generic/ensure.cpp @@ -2,17 +2,14 @@ #include #include -void __ensure_fail(const char *assertion, const char *file, unsigned int line, - const char *function) { - mlibc::panicLogger() << "In function " << function - << ", file " << file << ":" << line << "\n" - << "__ensure(" << assertion << ") failed" << frg::endlog; +void +__ensure_fail(const char *assertion, const char *file, unsigned int line, const char *function) { + mlibc::panicLogger() << "In function " << function << ", file " << file << ":" << line << "\n" + << "__ensure(" << assertion << ") failed" << frg::endlog; } -void __ensure_warn(const char *assertion, const char *file, unsigned int line, - const char *function) { - mlibc::infoLogger() << "In function " << function - << ", file " << file << ":" << line << "\n" - << "__ensure(" << assertion << ") failed" << frg::endlog; +void +__ensure_warn(const char *assertion, const char *file, unsigned int line, const char *function) { + mlibc::infoLogger() << "In function " << function << ", file " << file << ":" << line << "\n" + << "__ensure(" << assertion << ") failed" << frg::endlog; } - diff --git a/options/internal/generic/essential.cpp b/options/internal/generic/essential.cpp index bafd70eb8a..8d1049b10f 100644 --- a/options/internal/generic/essential.cpp +++ b/options/internal/generic/essential.cpp @@ -1,103 +1,101 @@ -#include #include +#include namespace { - template - [[gnu::always_inline]] - inline T alias_load(const unsigned char *&p) { - T value; - __builtin_memcpy(&value, p, sizeof(value)); - p += sizeof(T); - return value; - } +template +[[gnu::always_inline]] +inline T alias_load(const unsigned char *&p) { + T value; + __builtin_memcpy(&value, p, sizeof(value)); + p += sizeof(T); + return value; +} - template - [[gnu::always_inline]] - inline void alias_store(unsigned char *&p, T value) { - __builtin_memcpy(p, &value, sizeof(value)); - p += sizeof(T); - } +template +[[gnu::always_inline]] +inline void alias_store(unsigned char *&p, T value) { + __builtin_memcpy(p, &value, sizeof(value)); + p += sizeof(T); +} #if defined(__LP64__) && !defined(__riscv) - void *forward_copy(void *__restrict dest, const void *__restrict src, size_t n) { - auto curDest = reinterpret_cast(dest); - auto curSrc = reinterpret_cast(src); - - while(n >= 8 * 8) { - auto w1 = alias_load(curSrc); - auto w2 = alias_load(curSrc); - auto w3 = alias_load(curSrc); - auto w4 = alias_load(curSrc); - auto w5 = alias_load(curSrc); - auto w6 = alias_load(curSrc); - auto w7 = alias_load(curSrc); - auto w8 = alias_load(curSrc); - alias_store(curDest, w1); - alias_store(curDest, w2); - alias_store(curDest, w3); - alias_store(curDest, w4); - alias_store(curDest, w5); - alias_store(curDest, w6); - alias_store(curDest, w7); - alias_store(curDest, w8); - n -= 8 * 8; - } - if(n >= 4 * 8) { - auto w1 = alias_load(curSrc); - auto w2 = alias_load(curSrc); - auto w3 = alias_load(curSrc); - auto w4 = alias_load(curSrc); - alias_store(curDest, w1); - alias_store(curDest, w2); - alias_store(curDest, w3); - alias_store(curDest, w4); - n -= 4 * 8; - } - if(n >= 2 * 8) { - auto w1 = alias_load(curSrc); - auto w2 = alias_load(curSrc); - alias_store(curDest, w1); - alias_store(curDest, w2); - n -= 2 * 8; - } - if(n >= 8) { - auto w = alias_load(curSrc); - alias_store(curDest, w); - n -= 8; - } - if(n >= 4) { - auto w = alias_load(curSrc); - alias_store(curDest, w); - n -= 4; - } - if(n >= 2) { - auto w = alias_load(curSrc); - alias_store(curDest, w); - n -= 2; - } - if(n) - *curDest = *curSrc; - return dest; +void *forward_copy(void *__restrict dest, const void *__restrict src, size_t n) { + auto curDest = reinterpret_cast(dest); + auto curSrc = reinterpret_cast(src); + + while (n >= 8 * 8) { + auto w1 = alias_load(curSrc); + auto w2 = alias_load(curSrc); + auto w3 = alias_load(curSrc); + auto w4 = alias_load(curSrc); + auto w5 = alias_load(curSrc); + auto w6 = alias_load(curSrc); + auto w7 = alias_load(curSrc); + auto w8 = alias_load(curSrc); + alias_store(curDest, w1); + alias_store(curDest, w2); + alias_store(curDest, w3); + alias_store(curDest, w4); + alias_store(curDest, w5); + alias_store(curDest, w6); + alias_store(curDest, w7); + alias_store(curDest, w8); + n -= 8 * 8; } -#else // !__LP64__ - void *forward_copy(void *dest, const void *src, size_t n) { - for(size_t i = 0; i < n; i++) - ((char *)dest)[i] = ((const char *)src)[i]; - return dest; + if (n >= 4 * 8) { + auto w1 = alias_load(curSrc); + auto w2 = alias_load(curSrc); + auto w3 = alias_load(curSrc); + auto w4 = alias_load(curSrc); + alias_store(curDest, w1); + alias_store(curDest, w2); + alias_store(curDest, w3); + alias_store(curDest, w4); + n -= 4 * 8; } -#endif // __LP64__ / !__LP64__ + if (n >= 2 * 8) { + auto w1 = alias_load(curSrc); + auto w2 = alias_load(curSrc); + alias_store(curDest, w1); + alias_store(curDest, w2); + n -= 2 * 8; + } + if (n >= 8) { + auto w = alias_load(curSrc); + alias_store(curDest, w); + n -= 8; + } + if (n >= 4) { + auto w = alias_load(curSrc); + alias_store(curDest, w); + n -= 4; + } + if (n >= 2) { + auto w = alias_load(curSrc); + alias_store(curDest, w); + n -= 2; + } + if (n) + *curDest = *curSrc; + return dest; +} +#else // !__LP64__ +void *forward_copy(void *dest, const void *src, size_t n) { + for (size_t i = 0; i < n; i++) + ((char *)dest)[i] = ((const char *)src)[i]; + return dest; } +#endif // __LP64__ / !__LP64__ +} // namespace // -------------------------------------------------------------------------------------- // memcpy() implementation. // -------------------------------------------------------------------------------------- - void *memcpy(void *__restrict dest, const void *__restrict src, size_t n) { return forward_copy(dest, src, n); } - // -------------------------------------------------------------------------------------- // memset() implementation. // -------------------------------------------------------------------------------------- @@ -109,32 +107,27 @@ void *memset(void *dest, int val, size_t n) { unsigned char byte = val; // Get rid of misalignment. - while(n && (uintptr_t(curDest) & 7)) { + while (n && (uintptr_t(curDest) & 7)) { *curDest++ = byte; --n; } auto pattern64 = static_cast( - static_cast(byte) - | (static_cast(byte) << 8) - | (static_cast(byte) << 16) - | (static_cast(byte) << 24) - | (static_cast(byte) << 32) - | (static_cast(byte) << 40) - | (static_cast(byte) << 48) - | (static_cast(byte) << 56)); + static_cast(byte) | (static_cast(byte) << 8) | + (static_cast(byte) << 16) | (static_cast(byte) << 24) | + (static_cast(byte) << 32) | (static_cast(byte) << 40) | + (static_cast(byte) << 48) | (static_cast(byte) << 56) + ); auto pattern32 = static_cast( - static_cast(byte) - | (static_cast(byte) << 8) - | (static_cast(byte) << 16) - | (static_cast(byte) << 24)); + static_cast(byte) | (static_cast(byte) << 8) | + (static_cast(byte) << 16) | (static_cast(byte) << 24) + ); - auto pattern16 = static_cast( - static_cast(byte) - | (static_cast(byte) << 8)); + auto pattern16 = + static_cast(static_cast(byte) | (static_cast(byte) << 8)); - while(n >= 8 * 8) { + while (n >= 8 * 8) { alias_store(curDest, pattern64); alias_store(curDest, pattern64); alias_store(curDest, pattern64); @@ -145,31 +138,31 @@ void *memset(void *dest, int val, size_t n) { alias_store(curDest, pattern64); n -= 8 * 8; } - if(n >= 4 * 8) { + if (n >= 4 * 8) { alias_store(curDest, pattern64); alias_store(curDest, pattern64); alias_store(curDest, pattern64); alias_store(curDest, pattern64); n -= 4 * 8; } - if(n >= 2 * 8) { + if (n >= 2 * 8) { alias_store(curDest, pattern64); alias_store(curDest, pattern64); n -= 2 * 8; } - if(n >= 8) { + if (n >= 8) { alias_store(curDest, pattern64); n -= 8; } - if(n >= 4) { + if (n >= 4) { alias_store(curDest, pattern32); n -= 4; } - if(n >= 2) { + if (n >= 2) { alias_store(curDest, pattern16); n -= 2; } - if(n) + if (n) *curDest = byte; return dest; } @@ -177,7 +170,7 @@ void *memset(void *dest, int val, size_t n) { #else // !__LP64__ void *memset(void *dest, int byte, size_t count) { - for(size_t i = 0; i < count; i++) + for (size_t i = 0; i < count; i++) ((char *)dest)[i] = (char)byte; return dest; } @@ -194,13 +187,13 @@ void *memmove(void *dest, const void *src, size_t size) { uintptr_t udest = reinterpret_cast(dest); uintptr_t usrc = reinterpret_cast(src); - if(udest < usrc || usrc + size <= udest) { + if (udest < usrc || usrc + size <= udest) { return forward_copy(dest, src, size); - } else if(udest > usrc) { + } else if (udest > usrc) { char *dest_bytes = (char *)dest; char *src_bytes = (char *)src; - for(size_t i = 0; i < size; i++) + for (size_t i = 0; i < size; i++) dest_bytes[size - i - 1] = src_bytes[size - i - 1]; } @@ -209,7 +202,7 @@ void *memmove(void *dest, const void *src, size_t size) { size_t strlen(const char *s) { size_t len = 0; - for(size_t i = 0; s[i]; i++) + for (size_t i = 0; s[i]; i++) len++; return len; } diff --git a/options/internal/generic/frigg.cpp b/options/internal/generic/frigg.cpp index 7575c9c89f..e5e158f521 100644 --- a/options/internal/generic/frigg.cpp +++ b/options/internal/generic/frigg.cpp @@ -4,11 +4,9 @@ #include extern "C" void frg_panic(const char *mstr) { -// mlibc::sys_libc_log("mlibc: Call to frg_panic"); + // mlibc::sys_libc_log("mlibc: Call to frg_panic"); mlibc::sys_libc_log(mstr); mlibc::sys_libc_panic(); } -extern "C" void frg_log(const char *mstr) { - mlibc::sys_libc_log(mstr); -} +extern "C" void frg_log(const char *mstr) { mlibc::sys_libc_log(mstr); } diff --git a/options/internal/generic/global-config.cpp b/options/internal/generic/global-config.cpp index 264a984f5e..00b10f8fa5 100644 --- a/options/internal/generic/global-config.cpp +++ b/options/internal/generic/global-config.cpp @@ -1,6 +1,6 @@ +#include #include #include -#include namespace mlibc { @@ -20,8 +20,6 @@ static bool envEnabled(const char *env) { return value && *value && *value != '0'; } -GlobalConfig::GlobalConfig() { - debugMalloc = envEnabled("MLIBC_DEBUG_MALLOC"); -} +GlobalConfig::GlobalConfig() { debugMalloc = envEnabled("MLIBC_DEBUG_MALLOC"); } -} +} // namespace mlibc diff --git a/options/internal/generic/locale.cpp b/options/internal/generic/locale.cpp index afd676785b..cc02a4324a 100644 --- a/options/internal/generic/locale.cpp +++ b/options/internal/generic/locale.cpp @@ -5,91 +5,129 @@ namespace mlibc { char *nl_langinfo(nl_item item) { - if(item == CODESET) { + if (item == CODESET) { return const_cast("UTF-8"); - } else if(item >= ABMON_1 && item <= ABMON_12) { - switch(item) { - case ABMON_1: return const_cast("Jan"); - case ABMON_2: return const_cast("Feb"); - case ABMON_3: return const_cast("Mar"); - case ABMON_4: return const_cast("Apr"); - case ABMON_5: return const_cast("May"); - case ABMON_6: return const_cast("Jun"); - case ABMON_7: return const_cast("Jul"); - case ABMON_8: return const_cast("Aug"); - case ABMON_9: return const_cast("Sep"); - case ABMON_10: return const_cast("Oct"); - case ABMON_11: return const_cast("Nov"); - case ABMON_12: return const_cast("Dec"); - default: - __ensure(!"ABMON_* constants don't seem to be contiguous!"); - __builtin_unreachable(); + } else if (item >= ABMON_1 && item <= ABMON_12) { + switch (item) { + case ABMON_1: + return const_cast("Jan"); + case ABMON_2: + return const_cast("Feb"); + case ABMON_3: + return const_cast("Mar"); + case ABMON_4: + return const_cast("Apr"); + case ABMON_5: + return const_cast("May"); + case ABMON_6: + return const_cast("Jun"); + case ABMON_7: + return const_cast("Jul"); + case ABMON_8: + return const_cast("Aug"); + case ABMON_9: + return const_cast("Sep"); + case ABMON_10: + return const_cast("Oct"); + case ABMON_11: + return const_cast("Nov"); + case ABMON_12: + return const_cast("Dec"); + default: + __ensure(!"ABMON_* constants don't seem to be contiguous!"); + __builtin_unreachable(); } - } else if(item >= MON_1 && item <= MON_12) { - switch(item) { - case MON_1: return const_cast("January"); - case MON_2: return const_cast("Feburary"); - case MON_3: return const_cast("March"); - case MON_4: return const_cast("April"); - case MON_5: return const_cast("May"); - case MON_6: return const_cast("June"); - case MON_7: return const_cast("July"); - case MON_8: return const_cast("August"); - case MON_9: return const_cast("September"); - case MON_10: return const_cast("October"); - case MON_11: return const_cast("November"); - case MON_12: return const_cast("December"); - default: - __ensure(!"MON_* constants don't seem to be contiguous!"); - __builtin_unreachable(); + } else if (item >= MON_1 && item <= MON_12) { + switch (item) { + case MON_1: + return const_cast("January"); + case MON_2: + return const_cast("Feburary"); + case MON_3: + return const_cast("March"); + case MON_4: + return const_cast("April"); + case MON_5: + return const_cast("May"); + case MON_6: + return const_cast("June"); + case MON_7: + return const_cast("July"); + case MON_8: + return const_cast("August"); + case MON_9: + return const_cast("September"); + case MON_10: + return const_cast("October"); + case MON_11: + return const_cast("November"); + case MON_12: + return const_cast("December"); + default: + __ensure(!"MON_* constants don't seem to be contiguous!"); + __builtin_unreachable(); } - } else if(item == AM_STR) { + } else if (item == AM_STR) { return const_cast("AM"); - } else if(item == PM_STR) { + } else if (item == PM_STR) { return const_cast("PM"); - } else if(item >= DAY_1 && item <= DAY_7) { - switch(item) { - case DAY_1: return const_cast("Sunday"); - case DAY_2: return const_cast("Monday"); - case DAY_3: return const_cast("Tuesday"); - case DAY_4: return const_cast("Wednesday"); - case DAY_5: return const_cast("Thursday"); - case DAY_6: return const_cast("Friday"); - case DAY_7: return const_cast("Saturday"); - default: - __ensure(!"DAY_* constants don't seem to be contiguous!"); - __builtin_unreachable(); + } else if (item >= DAY_1 && item <= DAY_7) { + switch (item) { + case DAY_1: + return const_cast("Sunday"); + case DAY_2: + return const_cast("Monday"); + case DAY_3: + return const_cast("Tuesday"); + case DAY_4: + return const_cast("Wednesday"); + case DAY_5: + return const_cast("Thursday"); + case DAY_6: + return const_cast("Friday"); + case DAY_7: + return const_cast("Saturday"); + default: + __ensure(!"DAY_* constants don't seem to be contiguous!"); + __builtin_unreachable(); } - } else if(item >= ABDAY_1 && item <= ABDAY_7) { - switch(item) { - case ABDAY_1: return const_cast("Sun"); - case ABDAY_2: return const_cast("Mon"); - case ABDAY_3: return const_cast("Tue"); - case ABDAY_4: return const_cast("Wed"); - case ABDAY_5: return const_cast("Thu"); - case ABDAY_6: return const_cast("Fri"); - case ABDAY_7: return const_cast("Sat"); - default: - __ensure(!"ABDAY_* constants don't seem to be contiguous!"); - __builtin_unreachable(); + } else if (item >= ABDAY_1 && item <= ABDAY_7) { + switch (item) { + case ABDAY_1: + return const_cast("Sun"); + case ABDAY_2: + return const_cast("Mon"); + case ABDAY_3: + return const_cast("Tue"); + case ABDAY_4: + return const_cast("Wed"); + case ABDAY_5: + return const_cast("Thu"); + case ABDAY_6: + return const_cast("Fri"); + case ABDAY_7: + return const_cast("Sat"); + default: + __ensure(!"ABDAY_* constants don't seem to be contiguous!"); + __builtin_unreachable(); } - }else if(item == D_FMT) { + } else if (item == D_FMT) { return const_cast("%m/%d/%y"); - }else if(item == T_FMT) { + } else if (item == T_FMT) { return const_cast("%H:%M:%S"); - }else if(item == T_FMT_AMPM) { + } else if (item == T_FMT_AMPM) { return const_cast("%I:%M:%S %p"); - }else if(item == D_T_FMT) { + } else if (item == D_T_FMT) { return const_cast("%a %b %e %T %Y"); - }else if(item == YESEXPR) { + } else if (item == YESEXPR) { return const_cast("^[yY]"); - }else if(item == NOEXPR) { + } else if (item == NOEXPR) { return const_cast("^[nN]"); - }else{ - mlibc::infoLogger() << "mlibc: nl_langinfo item " - << item << " is not implemented properly" << frg::endlog; + } else { + mlibc::infoLogger() << "mlibc: nl_langinfo item " << item << " is not implemented properly" + << frg::endlog; return const_cast(""); } } -} +} // namespace mlibc diff --git a/options/internal/generic/search.cpp b/options/internal/generic/search.cpp index 4a9747af04..71b303e4e0 100644 --- a/options/internal/generic/search.cpp +++ b/options/internal/generic/search.cpp @@ -1,8 +1,8 @@ -#include +#include #include -#include +#include #include -#include +#include struct _ENTRY { ENTRY entry; @@ -12,13 +12,13 @@ struct _ENTRY { namespace mlibc { int hcreate_r(size_t num_entries, struct hsearch_data *htab) { - if(!htab) { + if (!htab) { errno = EINVAL; return 0; } - htab->table = static_cast<_ENTRY*>(calloc(num_entries, sizeof(_ENTRY))); - if(!htab->table) { + htab->table = static_cast<_ENTRY *>(calloc(num_entries, sizeof(_ENTRY))); + if (!htab->table) { errno = ENOMEM; return 0; } @@ -28,7 +28,7 @@ int hcreate_r(size_t num_entries, struct hsearch_data *htab) { } void hdestroy_r(struct hsearch_data *htab) { - if(!htab) { + if (!htab) { errno = EINVAL; return; } @@ -38,22 +38,21 @@ void hdestroy_r(struct hsearch_data *htab) { htab->filled = 0; } - int hsearch_r(ENTRY item, ACTION action, ENTRY **ret, struct hsearch_data *htab) { auto key = frg::string_view{item.key}; auto hash = frg::hash{}(key); size_t bucket_index = hash % htab->size; size_t start = bucket_index; - while(true) { + while (true) { auto &bucket = htab->table[bucket_index]; - if(bucket.used) { - if(bucket.entry.key == key) { + if (bucket.used) { + if (bucket.entry.key == key) { *ret = &bucket.entry; return 1; } - } else if(action == FIND) { + } else if (action == FIND) { errno = ESRCH; *ret = nullptr; return 0; @@ -61,8 +60,8 @@ int hsearch_r(ENTRY item, ACTION action, ENTRY **ret, struct hsearch_data *htab) bucket_index = (bucket_index + 1) % htab->size; - if(bucket_index == start) { - if(action == FIND) { + if (bucket_index == start) { + if (action == FIND) { errno = ESRCH; *ret = nullptr; return 0; @@ -73,16 +72,16 @@ int hsearch_r(ENTRY item, ACTION action, ENTRY **ret, struct hsearch_data *htab) } // insert a new entry. - if(htab->size == htab->filled) { + if (htab->size == htab->filled) { errno = ENOMEM; return 0; } ++htab->filled; bucket_index = start; - while(true) { + while (true) { auto &bucket = htab->table[bucket_index]; - if(!bucket.used) { + if (!bucket.used) { bucket.used = true; bucket.entry = item; *ret = &bucket.entry; diff --git a/options/internal/generic/sigset.cpp b/options/internal/generic/sigset.cpp index f3434bc27c..ce998b46bc 100644 --- a/options/internal/generic/sigset.cpp +++ b/options/internal/generic/sigset.cpp @@ -1,45 +1,48 @@ -#include #include +#include #include #include -#include #include +#include namespace { -template struct remove_reference { typedef T type; }; -template struct remove_reference { typedef T type; }; +template struct remove_reference { + typedef T type; +}; +template struct remove_reference { + typedef T type; +}; // Assume that the struct has a member named 'sig'. -template -struct sigset_type_helper { +template struct sigset_type_helper { using type = typename remove_reference::type; static_assert(offsetof(T, sig) == 0); }; -template<> -struct sigset_type_helper { using type = unsigned long; }; +template <> struct sigset_type_helper { + using type = unsigned long; +}; -template<> -struct sigset_type_helper { using type = unsigned long long; }; +template <> struct sigset_type_helper { + using type = unsigned long long; +}; -template<> -struct sigset_type_helper { using type = long; }; +template <> struct sigset_type_helper { + using type = long; +}; -template<> -struct sigset_type_helper { using type = long long; }; +template <> struct sigset_type_helper { + using type = long long; +}; // Some ABIs define sigset_t as a simple integer (e.g unsigned long), // while others define it as a struct containing an array of integers. using sigset_underlying_type = sigset_type_helper::type; -size_t signo_to_field(int signo) { - return signo / (sizeof(sigset_underlying_type) * CHAR_BIT); -} +size_t signo_to_field(int signo) { return signo / (sizeof(sigset_underlying_type) * CHAR_BIT); } -size_t signo_to_bit(int signo) { - return signo % (sizeof(sigset_underlying_type) * CHAR_BIT); -} +size_t signo_to_bit(int signo) { return signo % (sizeof(sigset_underlying_type) * CHAR_BIT); } } // namespace @@ -55,7 +58,7 @@ int sigfillset(sigset_t *sigset) { int sigaddset(sigset_t *sigset, int sig) { int signo = sig - 1; - if(signo < 0 || static_cast(signo) >= (sizeof(sigset_t) * CHAR_BIT)) { + if (signo < 0 || static_cast(signo) >= (sizeof(sigset_t) * CHAR_BIT)) { errno = EINVAL; return -1; } @@ -68,7 +71,7 @@ int sigaddset(sigset_t *sigset, int sig) { int sigdelset(sigset_t *sigset, int sig) { int signo = sig - 1; - if(signo < 0 || static_cast(signo) >= (sizeof(sigset_t) * CHAR_BIT)) { + if (signo < 0 || static_cast(signo) >= (sizeof(sigset_t) * CHAR_BIT)) { errno = EINVAL; return -1; } @@ -81,7 +84,7 @@ int sigdelset(sigset_t *sigset, int sig) { int sigismember(const sigset_t *sigset, int sig) { int signo = sig - 1; - if(signo < 0 || static_cast(signo) >= (sizeof(sigset_t) * CHAR_BIT)) { + if (signo < 0 || static_cast(signo) >= (sizeof(sigset_t) * CHAR_BIT)) { errno = EINVAL; return -1; } diff --git a/options/internal/generic/strings.cpp b/options/internal/generic/strings.cpp index ce4f84bf28..547e4b3dfe 100644 --- a/options/internal/generic/strings.cpp +++ b/options/internal/generic/strings.cpp @@ -5,18 +5,18 @@ namespace mlibc { int strncasecmp(const char *a, const char *b, size_t size) { - for(size_t i = 0; i < size; i++) { + for (size_t i = 0; i < size; i++) { unsigned char a_byte = tolower(a[i]); unsigned char b_byte = tolower(b[i]); - if(!a_byte && !b_byte) + if (!a_byte && !b_byte) return 0; // If only one char is null, one of the following cases applies. - if(a_byte < b_byte) + if (a_byte < b_byte) return -1; - if(a_byte > b_byte) + if (a_byte > b_byte) return 1; } return 0; } -} +} // namespace mlibc diff --git a/options/internal/generic/threads.cpp b/options/internal/generic/threads.cpp index 1ef07a4d32..4354307118 100644 --- a/options/internal/generic/threads.cpp +++ b/options/internal/generic/threads.cpp @@ -1,17 +1,23 @@ #include -#include #include +#include #include #include #include -#include #include +#include extern "C" Tcb *__rtld_allocateTcb(); namespace mlibc { -int thread_create(struct __mlibc_thread_data **__restrict thread, const struct __mlibc_threadattr *__restrict attrp, void *entry, void *__restrict user_arg, bool returns_int) { +int thread_create( + struct __mlibc_thread_data **__restrict thread, + const struct __mlibc_threadattr *__restrict attrp, + void *entry, + void *__restrict user_arg, + bool returns_int +) { auto new_tcb = __rtld_allocateTcb(); pid_t tid; struct __mlibc_threadattr attr = {}; @@ -33,8 +39,15 @@ int thread_create(struct __mlibc_thread_data **__restrict thread, const struct _ MLIBC_MISSING_SYSDEP(); return ENOSYS; } - int ret = mlibc::sys_prepare_stack(&stack, entry, - user_arg, new_tcb, &attr.__mlibc_stacksize, &attr.__mlibc_guardsize, &new_tcb->stackAddr); + int ret = mlibc::sys_prepare_stack( + &stack, + entry, + user_arg, + new_tcb, + &attr.__mlibc_stacksize, + &attr.__mlibc_guardsize, + &new_tcb->stackAddr + ); if (ret) return ret; @@ -44,7 +57,8 @@ int thread_create(struct __mlibc_thread_data **__restrict thread, const struct _ } new_tcb->stackSize = attr.__mlibc_stacksize; new_tcb->guardSize = attr.__mlibc_guardsize; - new_tcb->returnValueType = (returns_int) ? TcbThreadReturnValue::Integer : TcbThreadReturnValue::Pointer; + new_tcb->returnValueType = + (returns_int) ? TcbThreadReturnValue::Integer : TcbThreadReturnValue::Pointer; mlibc::sys_clone(new_tcb, &tid, stack); *thread = reinterpret_cast(new_tcb); @@ -64,9 +78,9 @@ int thread_join(struct __mlibc_thread_data *thread, void *ret) { mlibc::sys_futex_wait(&tcb->didExit, 0, nullptr); } - if(ret && tcb->returnValueType == TcbThreadReturnValue::Pointer) + if (ret && tcb->returnValueType == TcbThreadReturnValue::Pointer) *reinterpret_cast(ret) = tcb->returnValue.voidPtr; - else if(ret && tcb->returnValueType == TcbThreadReturnValue::Integer) + else if (ret && tcb->returnValueType == TcbThreadReturnValue::Integer) *reinterpret_cast(ret) = tcb->returnValue.intVal; // FIXME: destroy tcb here, currently we leak it @@ -92,8 +106,9 @@ static constexpr unsigned int mutexErrorCheck = 2; static constexpr unsigned int mutex_owner_mask = (static_cast(1) << 30) - 1; static constexpr unsigned int mutex_waiters_bit = static_cast(1) << 31; -int thread_mutex_init(struct __mlibc_mutex *__restrict mutex, - const struct __mlibc_mutexattr *__restrict attr) { +int thread_mutex_init( + struct __mlibc_mutex *__restrict mutex, const struct __mlibc_mutexattr *__restrict attr +) { auto type = attr ? attr->__mlibc_type : __MLIBC_THREAD_MUTEX_DEFAULT; auto robust = attr ? attr->__mlibc_robust : __MLIBC_THREAD_MUTEX_STALLED; auto protocol = attr ? attr->__mlibc_protocol : __MLIBC_THREAD_PRIO_NONE; @@ -104,11 +119,11 @@ int thread_mutex_init(struct __mlibc_mutex *__restrict mutex, mutex->__mlibc_flags = 0; mutex->__mlibc_prioceiling = 0; // TODO: We don't implement this. - if(type == __MLIBC_THREAD_MUTEX_RECURSIVE) { + if (type == __MLIBC_THREAD_MUTEX_RECURSIVE) { mutex->__mlibc_flags |= mutexRecursive; - }else if(type == __MLIBC_THREAD_MUTEX_ERRORCHECK) { + } else if (type == __MLIBC_THREAD_MUTEX_ERRORCHECK) { mutex->__mlibc_flags |= mutexErrorCheck; - }else{ + } else { __ensure(type == __MLIBC_THREAD_MUTEX_NORMAL); } @@ -128,46 +143,59 @@ int thread_mutex_destroy(struct __mlibc_mutex *mutex) { int thread_mutex_lock(struct __mlibc_mutex *mutex) { unsigned int this_tid = mlibc::this_tid(); unsigned int expected = 0; - while(true) { - if(!expected) { + while (true) { + if (!expected) { // Try to take the mutex here. - if(__atomic_compare_exchange_n(&mutex->__mlibc_state, - &expected, this_tid, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) { + if (__atomic_compare_exchange_n( + &mutex->__mlibc_state, + &expected, + this_tid, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )) { __ensure(!mutex->__mlibc_recursion); mutex->__mlibc_recursion = 1; return 0; } - }else{ + } else { // If this (recursive) mutex is already owned by us, increment the recursion level. - if((expected & mutex_owner_mask) == this_tid) { - if(!(mutex->__mlibc_flags & mutexRecursive)) { + if ((expected & mutex_owner_mask) == this_tid) { + if (!(mutex->__mlibc_flags & mutexRecursive)) { if (mutex->__mlibc_flags & mutexErrorCheck) return EDEADLK; else - mlibc::panicLogger() << "mlibc: pthread_mutex deadlock detected!" - << frg::endlog; + mlibc::panicLogger() + << "mlibc: pthread_mutex deadlock detected!" << frg::endlog; } ++mutex->__mlibc_recursion; return 0; } // Wait on the futex if the waiters flag is set. - if(expected & mutex_waiters_bit) { + if (expected & mutex_waiters_bit) { int e = mlibc::sys_futex_wait((int *)&mutex->__mlibc_state, expected, nullptr); - // If the wait returns EAGAIN, that means that the mutex_waiters_bit was just unset by - // some other thread. In this case, we should loop back around. - // Also do so in case of a signal being caught. + // If the wait returns EAGAIN, that means that the mutex_waiters_bit was just unset + // by some other thread. In this case, we should loop back around. Also do so in + // case of a signal being caught. if (e && e != EAGAIN && e != EINTR) - mlibc::panicLogger() << "sys_futex_wait() failed with error code " << e << frg::endlog; + mlibc::panicLogger() + << "sys_futex_wait() failed with error code " << e << frg::endlog; // Opportunistically try to take the lock after we wake up. expected = 0; - }else{ + } else { // Otherwise we have to set the waiters flag first. unsigned int desired = expected | mutex_waiters_bit; - if(__atomic_compare_exchange_n((int *)&mutex->__mlibc_state, - reinterpret_cast(&expected), desired, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) + if (__atomic_compare_exchange_n( + (int *)&mutex->__mlibc_state, + reinterpret_cast(&expected), + desired, + false, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) expected = desired; } } @@ -177,7 +205,7 @@ int thread_mutex_lock(struct __mlibc_mutex *mutex) { int thread_mutex_unlock(struct __mlibc_mutex *mutex) { // Decrement the recursion level and unlock if we hit zero. __ensure(mutex->__mlibc_recursion); - if(--mutex->__mlibc_recursion) + if (--mutex->__mlibc_recursion) return 0; auto flags = mutex->__mlibc_flags; @@ -197,7 +225,7 @@ int thread_mutex_unlock(struct __mlibc_mutex *mutex) { __ensure((state & mutex_owner_mask) == this_tid); - if(state & mutex_waiters_bit) { + if (state & mutex_waiters_bit) { // Wake the futex if there were waiters. Since the mutex might not exist at this location // anymore, we must conservatively ignore EACCES and EINVAL which may occur as a result. int e = mlibc::sys_futex_wake((int *)&mutex->__mlibc_state); @@ -220,21 +248,24 @@ int thread_mutexattr_destroy(struct __mlibc_mutexattr *attr) { return 0; } -int thread_mutexattr_gettype(const struct __mlibc_mutexattr *__restrict attr, int *__restrict type) { +int +thread_mutexattr_gettype(const struct __mlibc_mutexattr *__restrict attr, int *__restrict type) { *type = attr->__mlibc_type; return 0; } int thread_mutexattr_settype(struct __mlibc_mutexattr *attr, int type) { - if (type != __MLIBC_THREAD_MUTEX_NORMAL && type != __MLIBC_THREAD_MUTEX_ERRORCHECK - && type != __MLIBC_THREAD_MUTEX_RECURSIVE) + if (type != __MLIBC_THREAD_MUTEX_NORMAL && type != __MLIBC_THREAD_MUTEX_ERRORCHECK && + type != __MLIBC_THREAD_MUTEX_RECURSIVE) return EINVAL; attr->__mlibc_type = type; return 0; } -int thread_cond_init(struct __mlibc_cond *__restrict cond, const struct __mlibc_condattr *__restrict attr) { +int thread_cond_init( + struct __mlibc_cond *__restrict cond, const struct __mlibc_condattr *__restrict attr +) { auto clock = attr ? attr->__mlibc_clock : CLOCK_REALTIME; auto pshared = attr ? attr->__mlibc_pshared : __MLIBC_THREAD_PROCESS_PRIVATE; @@ -246,20 +277,21 @@ int thread_cond_init(struct __mlibc_cond *__restrict cond, const struct __mlibc_ return 0; } -int thread_cond_destroy(struct __mlibc_cond *) { - return 0; -} +int thread_cond_destroy(struct __mlibc_cond *) { return 0; } int thread_cond_broadcast(struct __mlibc_cond *cond) { __atomic_fetch_add(&cond->__mlibc_seq, 1, __ATOMIC_RELEASE); - if(int e = mlibc::sys_futex_wake((int *)&cond->__mlibc_seq); e) + if (int e = mlibc::sys_futex_wake((int *)&cond->__mlibc_seq); e) __ensure(!"sys_futex_wake() failed"); return 0; } -int thread_cond_timedwait(struct __mlibc_cond *__restrict cond, __mlibc_mutex *__restrict mutex, - const struct timespec *__restrict abstime) { +int thread_cond_timedwait( + struct __mlibc_cond *__restrict cond, + __mlibc_mutex *__restrict mutex, + const struct timespec *__restrict abstime +) { // TODO: pshared isn't supported yet. __ensure(cond->__mlibc_flags == 0); diff --git a/options/internal/generic/ubsan.cpp b/options/internal/generic/ubsan.cpp index 581a762b06..a8e473379f 100644 --- a/options/internal/generic/ubsan.cpp +++ b/options/internal/generic/ubsan.cpp @@ -12,7 +12,7 @@ struct SourceLocation { uint32_t column; }; -template +template void format_object(const SourceLocation &loc, frg::format_options opts, F &formatter) { FMT(loc.filename); FMT(":"); @@ -24,18 +24,12 @@ void format_object(const SourceLocation &loc, frg::format_options opts, F &forma using ValueHandle = uintptr_t; struct TypeDescriptor { - enum class Kind : uint16_t { - Integer = 0x0000, - Float = 0x0001, - Unknown = 0xffff - } kind; + enum class Kind : uint16_t { Integer = 0x0000, Float = 0x0001, Unknown = 0xffff } kind; uint16_t info; char name[]; - unsigned bitWidthInt() const { - return 1 << (info >> 1); - } + unsigned bitWidthInt() const { return 1 << (info >> 1); } bool isInlineInt() const { if (kind != Kind::Integer) @@ -46,12 +40,10 @@ struct TypeDescriptor { return inlineBits <= valueBits; } - bool isSigned() const { - return info & 1; - } + bool isSigned() const { return info & 1; } }; -template +template void format_object(const TypeDescriptor &type, frg::format_options opts, F &formatter) { FMT(type.name); } @@ -63,8 +55,7 @@ struct Value { Value(const TypeDescriptor &type, ValueHandle val) : type(type), val(val) {} }; -template -void format_object(const Value &val, frg::format_options opts, F &formatter) { +template void format_object(const Value &val, frg::format_options opts, F &formatter) { if (val.type.isInlineInt() && val.type.isSigned()) { auto signedValue = static_cast(val.val); FMT(signedValue); @@ -78,7 +69,6 @@ void format_object(const Value &val, frg::format_options opts, F &formatter) { FMT(")"); } - // --- Hook implementations --- struct TypeMismatch { @@ -91,11 +81,9 @@ struct TypeMismatch { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_type_mismatch_v1(TypeMismatch *tm, ValueHandle pointer) { // TODO: Make this print more information. - mlibc::panicLogger() - << LOG_NAME_LOC("type mismatch", tm->loc) - << "accessed address " << (void *)pointer << " but type " - << tm->type << " requires alignment " << (1 << tm->logAlignment) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("type mismatch", tm->loc) << "accessed address " + << (void *)pointer << " but type " << tm->type << " requires alignment " + << (1 << tm->logAlignment) << frg::endlog; } struct PointerOverflowData { @@ -103,12 +91,11 @@ struct PointerOverflowData { }; extern "C" [[gnu::visibility("hidden")]] -void __ubsan_handle_pointer_overflow(PointerOverflowData *pod, ValueHandle base, ValueHandle result) { +void +__ubsan_handle_pointer_overflow(PointerOverflowData *pod, ValueHandle base, ValueHandle result) { (void)base; (void)result; - mlibc::panicLogger() - << LOG_NAME_LOC("pointer overflow", pod->loc) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("pointer overflow", pod->loc) << frg::endlog; } struct InvalidValueData { @@ -119,9 +106,7 @@ struct InvalidValueData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_load_invalid_value(InvalidValueData *ivd, ValueHandle value) { (void)value; - mlibc::panicLogger() - << LOG_NAME_LOC("load of invalid value", ivd->loc) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("load of invalid value", ivd->loc) << frg::endlog; } struct OverflowData { @@ -131,42 +116,32 @@ struct OverflowData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_add_overflow(OverflowData *od, ValueHandle lhs, ValueHandle rhs) { - mlibc::panicLogger() - << LOG_NAME_LOC("add overflowed ", od->loc) - << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("add overflowed ", od->loc) + << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) << frg::endlog; } extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_sub_overflow(OverflowData *od, ValueHandle lhs, ValueHandle rhs) { - mlibc::panicLogger() - << LOG_NAME_LOC("sub overflowed", od->loc) - << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("sub overflowed", od->loc) + << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) << frg::endlog; } extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_mul_overflow(OverflowData *od, ValueHandle lhs, ValueHandle rhs) { - mlibc::panicLogger() - << LOG_NAME_LOC("mul overflowed", od->loc) - << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("mul overflowed", od->loc) + << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) << frg::endlog; } extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_divrem_overflow(OverflowData *od, ValueHandle lhs, ValueHandle rhs) { - mlibc::panicLogger() - << LOG_NAME_LOC("divrem overflowed", od->loc) - << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("divrem overflowed", od->loc) + << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) << frg::endlog; } extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_negate_overflow(OverflowData *od, ValueHandle lhs, ValueHandle rhs) { - mlibc::panicLogger() - << LOG_NAME_LOC("negate overflowed", od->loc) - << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("negate overflowed", od->loc) + << LOG_LHS_RHS(Value(od->type, lhs), Value(od->type, rhs)) << frg::endlog; } struct ShiftOutOfBoundsData { @@ -176,11 +151,11 @@ struct ShiftOutOfBoundsData { }; extern "C" [[gnu::visibility("hidden")]] -void __ubsan_handle_shift_out_of_bounds(ShiftOutOfBoundsData *soob, ValueHandle lhs, ValueHandle rhs) { - mlibc::panicLogger() - << LOG_NAME_LOC("shift out of bounds", soob->loc) - << LOG_LHS_RHS(Value(soob->lhsType, lhs), Value(soob->rhsType, rhs)) - << frg::endlog; +void +__ubsan_handle_shift_out_of_bounds(ShiftOutOfBoundsData *soob, ValueHandle lhs, ValueHandle rhs) { + mlibc::panicLogger() << LOG_NAME_LOC("shift out of bounds", soob->loc) + << LOG_LHS_RHS(Value(soob->lhsType, lhs), Value(soob->rhsType, rhs)) + << frg::endlog; } struct OutOfBoundsData { @@ -192,9 +167,7 @@ struct OutOfBoundsData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_out_of_bounds(OutOfBoundsData *oobd, ValueHandle data) { (void)data; - mlibc::panicLogger() - << LOG_NAME_LOC("out of bounds access", oobd->loc) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("out of bounds access", oobd->loc) << frg::endlog; } struct UnreachableData { @@ -203,9 +176,8 @@ struct UnreachableData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_builtin_unreachable(UnreachableData *ubd) { - mlibc::panicLogger() - << LOG_NAME_LOC("reached __builtin_unreachable()", ubd->loc) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("reached __builtin_unreachable()", ubd->loc) + << frg::endlog; } struct InvalidBuiltinData { @@ -215,9 +187,7 @@ struct InvalidBuiltinData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_invalid_builtin(InvalidBuiltinData *ibd) { - mlibc::panicLogger() - << LOG_NAME_LOC("reached invalid builtin", ibd->loc) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("reached invalid builtin", ibd->loc) << frg::endlog; } struct VLABoundData { @@ -227,16 +197,16 @@ struct VLABoundData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_vla_bound_not_positive(VLABoundData *vlabd) { - mlibc::panicLogger() - << LOG_NAME_LOC("VLA bound not positive", vlabd->loc) - << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("VLA bound not positive", vlabd->loc) << frg::endlog; } extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_missing_return(UnreachableData *data) { mlibc::panicLogger() - << LOG_NAME_LOC("reached end of a value-returning function without returning a value", data->loc) - << frg::endlog; + << LOG_NAME_LOC( + "reached end of a value-returning function without returning a value", data->loc + ) + << frg::endlog; } struct NonNullArgData { @@ -247,10 +217,9 @@ struct NonNullArgData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_nonnull_arg(NonNullArgData *data) { - mlibc::panicLogger() - << LOG_NAME_LOC("null pointer passed to non-null argument", data->loc) - << "argument " << data->arg_index << " is required to be non-null in " - << data->attr_loc << frg::endlog; + mlibc::panicLogger() << LOG_NAME_LOC("null pointer passed to non-null argument", data->loc) + << "argument " << data->arg_index << " is required to be non-null in " + << data->attr_loc << frg::endlog; } struct FloatCastOverflowData { @@ -261,11 +230,9 @@ struct FloatCastOverflowData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_float_cast_overflow(FloatCastOverflowData *data, ValueHandle from) { - (void) from; - mlibc::panicLogger() - << LOG_NAME_LOC("float cast overflow", data->loc) - << "from " << data->from_type << " to " - << data->to_type << frg::endlog; + (void)from; + mlibc::panicLogger() << LOG_NAME_LOC("float cast overflow", data->loc) << "from " + << data->from_type << " to " << data->to_type << frg::endlog; } struct FunctionTypeMismatchData { @@ -275,8 +242,6 @@ struct FunctionTypeMismatchData { extern "C" [[gnu::visibility("hidden")]] void __ubsan_handle_function_type_mismatch(FunctionTypeMismatchData *data, ValueHandle from) { - (void) from; - mlibc::panicLogger() - << LOG_NAME_LOC("function type mismatch", data->loc) - << frg::endlog; + (void)from; + mlibc::panicLogger() << LOG_NAME_LOC("function type mismatch", data->loc) << frg::endlog; } diff --git a/options/internal/include/bits/ensure.h b/options/internal/include/bits/ensure.h index 17c96a8674..af075bba9b 100644 --- a/options/internal/include/bits/ensure.h +++ b/options/internal/include/bits/ensure.h @@ -8,38 +8,46 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -void __ensure_fail(const char *assertion, const char *file, unsigned int line, - const char *function); +void +__ensure_fail(const char *assertion, const char *file, unsigned int line, const char *function); -void __ensure_warn(const char *assertion, const char *file, unsigned int line, - const char *function); +void +__ensure_warn(const char *assertion, const char *file, unsigned int line, const char *function); #endif /* !__MLIBC_ABI_ONLY */ -#define __ensure(assertion) do { if(!(assertion)) \ - __ensure_fail(#assertion, __FILE__, __LINE__, __func__); } while(0) - -#define MLIBC_UNIMPLEMENTED() __ensure_fail("Functionality is not implemented", \ - __FILE__, __LINE__, __func__) - -#define MLIBC_MISSING_SYSDEP() __ensure_warn("Library function fails due to missing sysdep", \ - __FILE__, __LINE__, __func__) - -#define MLIBC_CHECK_OR_ENOSYS(sysdep, ret) ({ \ - if (!(sysdep)) { \ - __ensure_warn("Library function fails due to missing sysdep", \ - __FILE__, __LINE__, __func__); \ - errno = ENOSYS; \ - return (ret); \ - } \ - sysdep; \ - }) - -#define MLIBC_STUB_BODY { MLIBC_UNIMPLEMENTED(); __builtin_unreachable(); } +#define __ensure(assertion) \ + do { \ + if (!(assertion)) \ + __ensure_fail(#assertion, __FILE__, __LINE__, __func__); \ + } while (0) + +#define MLIBC_UNIMPLEMENTED() \ + __ensure_fail("Functionality is not implemented", __FILE__, __LINE__, __func__) + +#define MLIBC_MISSING_SYSDEP() \ + __ensure_warn("Library function fails due to missing sysdep", __FILE__, __LINE__, __func__) + +#define MLIBC_CHECK_OR_ENOSYS(sysdep, ret) \ + ({ \ + if (!(sysdep)) { \ + __ensure_warn( \ + "Library function fails due to missing sysdep", __FILE__, __LINE__, __func__ \ + ); \ + errno = ENOSYS; \ + return (ret); \ + } \ + sysdep; \ + }) + +#define MLIBC_STUB_BODY \ + { \ + MLIBC_UNIMPLEMENTED(); \ + __builtin_unreachable(); \ + } #ifdef __cplusplus } #endif #endif /* MLIBC_ENSURE_H */ - diff --git a/options/internal/include/bits/inline-definition.h b/options/internal/include/bits/inline-definition.h index 939059aac5..5abf0c9c5d 100644 --- a/options/internal/include/bits/inline-definition.h +++ b/options/internal/include/bits/inline-definition.h @@ -16,4 +16,3 @@ extern "C" { #endif #endif /* MLIBC_INLINE_DEFINITION_H */ - diff --git a/options/internal/include/bits/machine.h b/options/internal/include/bits/machine.h index d33029bfc6..a1db5e40f1 100644 --- a/options/internal/include/bits/machine.h +++ b/options/internal/include/bits/machine.h @@ -4,7 +4,7 @@ #include -#if defined (__i386__) +#if defined(__i386__) struct __mlibc_jmpbuf_register_state { uint32_t ebx; uint32_t ebp; @@ -13,7 +13,7 @@ struct __mlibc_jmpbuf_register_state { uint32_t esp; uint32_t eip; }; -#elif defined (__x86_64__) +#elif defined(__x86_64__) struct __mlibc_jmpbuf_register_state { uint64_t rbx; uint64_t rbp; @@ -24,7 +24,7 @@ struct __mlibc_jmpbuf_register_state { uint64_t rsp; uint64_t rip; }; -#elif defined (__aarch64__) +#elif defined(__aarch64__) struct __mlibc_jmpbuf_register_state { uint64_t x19; uint64_t x20; @@ -49,7 +49,7 @@ struct __mlibc_jmpbuf_register_state { uint64_t d14; uint64_t d15; }; -#elif defined (__riscv) && __riscv_xlen == 64 +#elif defined(__riscv) && __riscv_xlen == 64 struct __mlibc_jmpbuf_register_state { uint64_t ra; uint64_t s0; @@ -78,7 +78,7 @@ struct __mlibc_jmpbuf_register_state { double fs10; double fs11; }; -#elif defined (__m68k__) +#elif defined(__m68k__) struct __mlibc_jmpbuf_register_state { uint32_t d2; uint32_t d3; @@ -96,8 +96,7 @@ struct __mlibc_jmpbuf_register_state { uint32_t pc; }; #else -# error "Missing architecture specific code" +#error "Missing architecture specific code" #endif #endif /* MLIBC_MACHINE_H */ - diff --git a/options/internal/include/bits/nl_item.h b/options/internal/include/bits/nl_item.h index 762e61b0a3..87b4643c36 100644 --- a/options/internal/include/bits/nl_item.h +++ b/options/internal/include/bits/nl_item.h @@ -79,4 +79,3 @@ typedef int nl_item; #endif #endif /* _NL_ITEM_H */ - diff --git a/options/internal/include/bits/null.h b/options/internal/include/bits/null.h index 176008f455..16da84f714 100644 --- a/options/internal/include/bits/null.h +++ b/options/internal/include/bits/null.h @@ -7,10 +7,9 @@ #endif #ifndef __cplusplus -# define NULL ((void *)0) +#define NULL ((void *)0) #else -# define NULL 0 +#define NULL 0 #endif #endif /* MLIBC_NULL_H */ - diff --git a/options/internal/include/bits/search.h b/options/internal/include/bits/search.h index 8e650a066b..f74a1e9beb 100644 --- a/options/internal/include/bits/search.h +++ b/options/internal/include/bits/search.h @@ -3,10 +3,7 @@ #include -typedef enum { - FIND, - ENTER -} ACTION; +typedef enum { FIND, ENTER } ACTION; typedef struct entry { char *key; diff --git a/options/internal/include/bits/ssize_t.h b/options/internal/include/bits/ssize_t.h index a1a847179d..835f7445b5 100644 --- a/options/internal/include/bits/ssize_t.h +++ b/options/internal/include/bits/ssize_t.h @@ -12,4 +12,3 @@ typedef int ssize_t; #endif #endif /* MLIBC_SSIZE_T_H */ - diff --git a/options/internal/include/bits/threads.h b/options/internal/include/bits/threads.h index 6bd637934b..66607229ad 100644 --- a/options/internal/include/bits/threads.h +++ b/options/internal/include/bits/threads.h @@ -2,9 +2,9 @@ #define _INTERNAL_THREADS_H #include -#include #include #include +#include /* values for pthread_attr_{get,set}detachstate(). */ #define __MLIBC_THREAD_CREATE_JOINABLE 0 diff --git a/options/internal/include/bits/types.h b/options/internal/include/bits/types.h index e18d0c92a3..be8018e8b5 100644 --- a/options/internal/include/bits/types.h +++ b/options/internal/include/bits/types.h @@ -1,66 +1,66 @@ #ifndef _MLIBC_INTERNAL_TYPES_H #define _MLIBC_INTERNAL_TYPES_H -typedef __UINT8_TYPE__ __mlibc_uint8; +typedef __UINT8_TYPE__ __mlibc_uint8; typedef __UINT16_TYPE__ __mlibc_uint16; typedef __UINT32_TYPE__ __mlibc_uint32; typedef __UINT64_TYPE__ __mlibc_uint64; -typedef __INT8_TYPE__ __mlibc_int8; +typedef __INT8_TYPE__ __mlibc_int8; typedef __INT16_TYPE__ __mlibc_int16; typedef __INT32_TYPE__ __mlibc_int32; typedef __INT64_TYPE__ __mlibc_int64; /* Clang and GCC have different mechanisms for INT32_C and friends. */ #ifdef __clang__ -# define __MLIBC_C_EXPAND_JOIN(x, suffix) x ## suffix -# define __MLIBC_C_JOIN(x, suffix) __MLIBC_C_EXPAND_JOIN(x, suffix) +#define __MLIBC_C_EXPAND_JOIN(x, suffix) x##suffix +#define __MLIBC_C_JOIN(x, suffix) __MLIBC_C_EXPAND_JOIN(x, suffix) -# define __MLIBC_INT8_C(x) __MLIBC_C_JOIN(x, __INT8_C_SUFFIX__) -# define __MLIBC_INT16_C(x) __MLIBC_C_JOIN(x, __INT16_C_SUFFIX__) -# define __MLIBC_INT32_C(x) __MLIBC_C_JOIN(x, __INT32_C_SUFFIX__) -# define __MLIBC_INT64_C(x) __MLIBC_C_JOIN(x, __INT64_C_SUFFIX__) +#define __MLIBC_INT8_C(x) __MLIBC_C_JOIN(x, __INT8_C_SUFFIX__) +#define __MLIBC_INT16_C(x) __MLIBC_C_JOIN(x, __INT16_C_SUFFIX__) +#define __MLIBC_INT32_C(x) __MLIBC_C_JOIN(x, __INT32_C_SUFFIX__) +#define __MLIBC_INT64_C(x) __MLIBC_C_JOIN(x, __INT64_C_SUFFIX__) -# define __MLIBC_UINT8_C(x) __MLIBC_C_JOIN(x, __UINT8_C_SUFFIX__) -# define __MLIBC_UINT16_C(x) __MLIBC_C_JOIN(x, __UINT16_C_SUFFIX__) -# define __MLIBC_UINT32_C(x) __MLIBC_C_JOIN(x, __UINT32_C_SUFFIX__) -# define __MLIBC_UINT64_C(x) __MLIBC_C_JOIN(x, __UINT64_C_SUFFIX__) +#define __MLIBC_UINT8_C(x) __MLIBC_C_JOIN(x, __UINT8_C_SUFFIX__) +#define __MLIBC_UINT16_C(x) __MLIBC_C_JOIN(x, __UINT16_C_SUFFIX__) +#define __MLIBC_UINT32_C(x) __MLIBC_C_JOIN(x, __UINT32_C_SUFFIX__) +#define __MLIBC_UINT64_C(x) __MLIBC_C_JOIN(x, __UINT64_C_SUFFIX__) -# define __MLIBC_INTMAX_C(x) __MLIBC_C_JOIN(x, __INTMAX_C_SUFFIX__) -# define __MLIBC_UINTMAX_C(x) __MLIBC_C_JOIN(x, __UINTMAX_C_SUFFIX__) +#define __MLIBC_INTMAX_C(x) __MLIBC_C_JOIN(x, __INTMAX_C_SUFFIX__) +#define __MLIBC_UINTMAX_C(x) __MLIBC_C_JOIN(x, __UINTMAX_C_SUFFIX__) #else -# define __MLIBC_INT8_C(x) __INT8_C(x) -# define __MLIBC_INT16_C(x) __INT16_C(x) -# define __MLIBC_INT32_C(x) __INT32_C(x) -# define __MLIBC_INT64_C(x) __INT64_C(x) - -# define __MLIBC_UINT8_C(x) __UINT8_C(x) -# define __MLIBC_UINT16_C(x) __UINT16_C(x) -# define __MLIBC_UINT32_C(x) __UINT32_C(x) -# define __MLIBC_UINT64_C(x) __UINT64_C(x) - -# define __MLIBC_INTMAX_C(x) __INTMAX_C(x) -# define __MLIBC_UINTMAX_C(x) __UINTMAX_C(x) +#define __MLIBC_INT8_C(x) __INT8_C(x) +#define __MLIBC_INT16_C(x) __INT16_C(x) +#define __MLIBC_INT32_C(x) __INT32_C(x) +#define __MLIBC_INT64_C(x) __INT64_C(x) + +#define __MLIBC_UINT8_C(x) __UINT8_C(x) +#define __MLIBC_UINT16_C(x) __UINT16_C(x) +#define __MLIBC_UINT32_C(x) __UINT32_C(x) +#define __MLIBC_UINT64_C(x) __UINT64_C(x) + +#define __MLIBC_INTMAX_C(x) __INTMAX_C(x) +#define __MLIBC_UINTMAX_C(x) __UINTMAX_C(x) #endif -#define __MLIBC_INT8_MAX __INT8_MAX__ +#define __MLIBC_INT8_MAX __INT8_MAX__ #define __MLIBC_INT16_MAX __INT16_MAX__ #define __MLIBC_INT32_MAX __INT32_MAX__ #define __MLIBC_INT64_MAX __INT64_MAX__ -#define __MLIBC_INT8_MIN (-__MLIBC_INT8_MAX - 1) +#define __MLIBC_INT8_MIN (-__MLIBC_INT8_MAX - 1) #define __MLIBC_INT16_MIN (-__MLIBC_INT16_MAX - 1) #define __MLIBC_INT32_MIN (-__MLIBC_INT32_MAX - 1) #define __MLIBC_INT64_MIN (-__MLIBC_INT64_MAX - 1) -#define __MLIBC_UINT8_MAX __UINT8_MAX__ +#define __MLIBC_UINT8_MAX __UINT8_MAX__ #define __MLIBC_UINT16_MAX __UINT16_MAX__ #define __MLIBC_UINT32_MAX __UINT32_MAX__ #define __MLIBC_UINT64_MAX __UINT64_MAX__ /* Fast types (signed). */ -#if defined (__i386__) +#if defined(__i386__) typedef __mlibc_int8 __mlibc_int_fast8; #define __MLIBC_INT_FAST8_C(x) __MLIBC_INT8_C(x) @@ -82,7 +82,7 @@ typedef __mlibc_int64 __mlibc_int_fast64; #define __MLIBC_INT_FAST64_MAX __MLIBC_INT64_MAX #define __MLIBC_INT_FAST64_MIN __MLIBC_INT64_MIN -#elif defined (__x86_64__) +#elif defined(__x86_64__) typedef __mlibc_int8 __mlibc_int_fast8; #define __MLIBC_INT_FAST8_C(x) __MLIBC_INT8_C(x) @@ -104,7 +104,7 @@ typedef __mlibc_int64 __mlibc_int_fast64; #define __MLIBC_INT_FAST64_MAX __MLIBC_INT64_MAX #define __MLIBC_INT_FAST64_MIN __MLIBC_INT64_MIN -#elif defined (__aarch64__) +#elif defined(__aarch64__) typedef __mlibc_int8 __mlibc_int_fast8; #define __MLIBC_INT_FAST8_C(x) __MLIBC_INT8_C(x) @@ -126,7 +126,7 @@ typedef __mlibc_int64 __mlibc_int_fast64; #define __MLIBC_INT_FAST64_MAX __MLIBC_INT64_MAX #define __MLIBC_INT_FAST64_MIN __MLIBC_INT64_MIN -#elif defined (__riscv) && __riscv_xlen == 64 +#elif defined(__riscv) && __riscv_xlen == 64 typedef __mlibc_int8 __mlibc_int_fast8; #define __MLIBC_INT_FAST8_C(x) __MLIBC_INT8_C(x) @@ -148,7 +148,7 @@ typedef __mlibc_int64 __mlibc_int_fast64; #define __MLIBC_INT_FAST64_MAX __MLIBC_INT64_MAX #define __MLIBC_INT_FAST64_MIN __MLIBC_INT64_MIN -#elif defined (__m68k__) +#elif defined(__m68k__) typedef __mlibc_int8 __mlibc_int_fast8; #define __MLIBC_INT_FAST8_C(x) __MLIBC_INT8_C(x) @@ -171,12 +171,12 @@ typedef __mlibc_int64 __mlibc_int_fast64; #define __MLIBC_INT_FAST64_MIN __MLIBC_INT64_MIN #else -# error "Missing architecture specific code" +#error "Missing architecture specific code" #endif /* Fast types (unsigned). */ -#if defined (__i386__) +#if defined(__i386__) typedef __mlibc_uint8 __mlibc_uint_fast8; #define __MLIBC_UINT_FAST8_C(x) __MLIBC_UINT8_C(x) @@ -198,7 +198,7 @@ typedef __mlibc_uint64 __mlibc_uint_fast64; #define __MLIBC_UINT_FAST64_MAX __MLIBC_UINT64_MAX #define __MLIBC_UINT_FAST64_MIN __MLIBC_UINT64_MIN -#elif defined (__x86_64__) +#elif defined(__x86_64__) typedef __mlibc_uint8 __mlibc_uint_fast8; #define __MLIBC_UINT_FAST8_C(x) __MLIBC_UINT8_C(x) @@ -220,7 +220,7 @@ typedef __mlibc_uint64 __mlibc_uint_fast64; #define __MLIBC_UINT_FAST64_MAX __MLIBC_UINT64_MAX #define __MLIBC_UINT_FAST64_MIN __MLIBC_UINT64_MIN -#elif defined (__aarch64__) +#elif defined(__aarch64__) typedef __mlibc_uint8 __mlibc_uint_fast8; #define __MLIBC_UINT_FAST8_C(x) __MLIBC_UINT8_C(x) @@ -242,7 +242,7 @@ typedef __mlibc_uint64 __mlibc_uint_fast64; #define __MLIBC_UINT_FAST64_MAX __MLIBC_UINT64_MAX #define __MLIBC_UINT_FAST64_MIN __MLIBC_UINT64_MIN -#elif defined (__riscv) && __riscv_xlen == 64 +#elif defined(__riscv) && __riscv_xlen == 64 typedef __mlibc_uint8 __mlibc_uint_fast8; #define __MLIBC_UINT_FAST8_C(x) __MLIBC_UINT8_C(x) @@ -264,7 +264,7 @@ typedef __mlibc_uint64 __mlibc_uint_fast64; #define __MLIBC_UINT_FAST64_MAX __MLIBC_UINT64_MAX #define __MLIBC_UINT_FAST64_MIN __MLIBC_UINT64_MIN -#elif defined (__m68k__) +#elif defined(__m68k__) typedef __mlibc_uint8 __mlibc_uint_fast8; #define __MLIBC_UINT_FAST8_C(x) __MLIBC_UINT8_C(x) @@ -287,13 +287,13 @@ typedef __mlibc_uint64 __mlibc_uint_fast64; #define __MLIBC_UINT_FAST64_MIN __MLIBC_UINT64_MIN #else -# error "Missing architecture specific code" +#error "Missing architecture specific code" #endif /* Special types. */ -typedef __INTMAX_TYPE__ __mlibc_intmax; -typedef __INTPTR_TYPE__ __mlibc_intptr; +typedef __INTMAX_TYPE__ __mlibc_intmax; +typedef __INTPTR_TYPE__ __mlibc_intptr; typedef __PTRDIFF_TYPE__ __mlibc_ptrdiff; #define __MLIBC_INTMAX_MAX __INTMAX_MAX__ #define __MLIBC_INTMAX_MIN (-__INTMAX_MAX__ - 1) @@ -304,7 +304,7 @@ typedef __PTRDIFF_TYPE__ __mlibc_ptrdiff; typedef __UINTMAX_TYPE__ __mlibc_uintmax; typedef __UINTPTR_TYPE__ __mlibc_uintptr; -typedef __SIZE_TYPE__ __mlibc_size; +typedef __SIZE_TYPE__ __mlibc_size; #define __MLIBC_UINTMAX_MAX __UINTMAX_MAX__ #define __MLIBC_UINTPTR_MAX __UINTPTR_MAX__ #define __MLIBC_SIZE_MAX __SIZE_MAX__ @@ -325,24 +325,23 @@ typedef __SIZE_TYPE__ __mlibc_size; /* ---------------------------------------------------------------------------- */ #if defined(__cplusplus) && defined(__cpp_static_assert) && __cpp_static_assert >= 200410L -# define __MLIBC_STATIC_ASSERT(c, text) static_assert(c, text) +#define __MLIBC_STATIC_ASSERT(c, text) static_assert(c, text) #elif !defined(__cplusplus) /* _Static_assert is an extension in C89/C99. */ -# define __MLIBC_STATIC_ASSERT(c, text) __extension__ _Static_assert(c, text) +#define __MLIBC_STATIC_ASSERT(c, text) __extension__ _Static_assert(c, text) #else -# define __MLIBC_STATIC_ASSERT(c, text) extern int __static_assert_unavailable +#define __MLIBC_STATIC_ASSERT(c, text) extern int __static_assert_unavailable #endif -#define __MLIBC_CHECK_TYPE(T1, T2) __MLIBC_STATIC_ASSERT(sizeof(T1) == sizeof(T2),\ - #T1 " != " #T2) +#define __MLIBC_CHECK_TYPE(T1, T2) __MLIBC_STATIC_ASSERT(sizeof(T1) == sizeof(T2), #T1 " != " #T2) /* Least-width. */ -__MLIBC_CHECK_TYPE(__mlibc_int8, __INT_LEAST8_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_int8, __INT_LEAST8_TYPE__); __MLIBC_CHECK_TYPE(__mlibc_int16, __INT_LEAST16_TYPE__); __MLIBC_CHECK_TYPE(__mlibc_int32, __INT_LEAST32_TYPE__); __MLIBC_CHECK_TYPE(__mlibc_int64, __INT_LEAST64_TYPE__); -__MLIBC_CHECK_TYPE(__mlibc_uint8, __UINT_LEAST8_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_uint8, __UINT_LEAST8_TYPE__); __MLIBC_CHECK_TYPE(__mlibc_uint16, __UINT_LEAST16_TYPE__); __MLIBC_CHECK_TYPE(__mlibc_uint32, __UINT_LEAST32_TYPE__); __MLIBC_CHECK_TYPE(__mlibc_uint64, __UINT_LEAST64_TYPE__); @@ -350,15 +349,15 @@ __MLIBC_CHECK_TYPE(__mlibc_uint64, __UINT_LEAST64_TYPE__); /* Fast-width. */ /* Unfortunately, GCC and Clang disagree about fast types. */ #ifndef __clang__ - __MLIBC_CHECK_TYPE(__mlibc_int_fast8, __INT_FAST8_TYPE__); - __MLIBC_CHECK_TYPE(__mlibc_int_fast16, __INT_FAST16_TYPE__); - __MLIBC_CHECK_TYPE(__mlibc_int_fast32, __INT_FAST32_TYPE__); - __MLIBC_CHECK_TYPE(__mlibc_int_fast64, __INT_FAST64_TYPE__); - - __MLIBC_CHECK_TYPE(__mlibc_uint_fast8, __UINT_FAST8_TYPE__); - __MLIBC_CHECK_TYPE(__mlibc_uint_fast16, __UINT_FAST16_TYPE__); - __MLIBC_CHECK_TYPE(__mlibc_uint_fast32, __UINT_FAST32_TYPE__); - __MLIBC_CHECK_TYPE(__mlibc_uint_fast64, __UINT_FAST64_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_int_fast8, __INT_FAST8_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_int_fast16, __INT_FAST16_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_int_fast32, __INT_FAST32_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_int_fast64, __INT_FAST64_TYPE__); + +__MLIBC_CHECK_TYPE(__mlibc_uint_fast8, __UINT_FAST8_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_uint_fast16, __UINT_FAST16_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_uint_fast32, __UINT_FAST32_TYPE__); +__MLIBC_CHECK_TYPE(__mlibc_uint_fast64, __UINT_FAST64_TYPE__); #endif #endif /* _MLIBC_INTERNAL_TYPES_H */ diff --git a/options/internal/include/bits/wchar.h b/options/internal/include/bits/wchar.h index 478eb9071a..5fe4069076 100644 --- a/options/internal/include/bits/wchar.h +++ b/options/internal/include/bits/wchar.h @@ -3,7 +3,7 @@ #include -#define WCHAR_MAX __MLIBC_WCHAR_MAX -#define WCHAR_MIN __MLIBC_WCHAR_MIN +#define WCHAR_MAX __MLIBC_WCHAR_MAX +#define WCHAR_MIN __MLIBC_WCHAR_MIN #endif /* MLIBC_WCHAR_H */ diff --git a/options/internal/include/bits/wchar_t.h b/options/internal/include/bits/wchar_t.h index 83aa5e546c..d30052091c 100644 --- a/options/internal/include/bits/wchar_t.h +++ b/options/internal/include/bits/wchar_t.h @@ -9,4 +9,3 @@ typedef __WCHAR_TYPE__ wchar_t; #endif #endif /* MLIBC_WCHAR_T_H */ - diff --git a/options/internal/include/bits/wctype_t.h b/options/internal/include/bits/wctype_t.h index 7cb6de42ea..947db9ed81 100644 --- a/options/internal/include/bits/wctype_t.h +++ b/options/internal/include/bits/wctype_t.h @@ -4,4 +4,3 @@ typedef unsigned long wctype_t; #endif /* MLIBC_WCTYPE_T_H */ - diff --git a/options/internal/include/bits/winsize.h b/options/internal/include/bits/winsize.h index 3edbcd4122..b652587052 100644 --- a/options/internal/include/bits/winsize.h +++ b/options/internal/include/bits/winsize.h @@ -10,4 +10,3 @@ struct winsize { }; #endif /* MLIBC_WINSIZE_H */ - diff --git a/options/internal/include/mlibc/all-sysdeps.hpp b/options/internal/include/mlibc/all-sysdeps.hpp index d34fd60b42..e37dd8e42e 100644 --- a/options/internal/include/mlibc/all-sysdeps.hpp +++ b/options/internal/include/mlibc/all-sysdeps.hpp @@ -1,30 +1,30 @@ #ifndef MLIBC_ALL_SYSDEPS #define MLIBC_ALL_SYSDEPS -#include #include +#include /* The ANSI option is always enabled. */ #include #if __MLIBC_POSIX_OPTION -# include +#include #endif /* __MLIBC_POSIX_OPTION */ #if __MLIBC_LINUX_OPTION -# include +#include #endif /* __MLIBC_LINUX_OPTION */ #if __MLIBC_GLIBC_OPTION -# include +#include #endif /* __MLIBC_GLIBC_OPTION */ #if __MLIBC_BSD_OPTION -# include +#include #endif /* __MLIBC_BSD_OPTION */ #if MLIBC_BUILDING_RTLD -# include +#include #endif /* MLIBC_BUILDING_RTLD */ #include diff --git a/options/internal/include/mlibc/allocator.hpp b/options/internal/include/mlibc/allocator.hpp index 852620a5f3..56abbdbc29 100644 --- a/options/internal/include/mlibc/allocator.hpp +++ b/options/internal/include/mlibc/allocator.hpp @@ -1,15 +1,15 @@ #ifndef MLIBC_FRIGG_ALLOC #define MLIBC_FRIGG_ALLOC -#include #include #include #include +#include #if !MLIBC_DEBUG_ALLOCATOR struct VirtualAllocator { -public: + public: uintptr_t map(size_t length); void unmap(uintptr_t address, size_t length); diff --git a/options/internal/include/mlibc/bitutil.hpp b/options/internal/include/mlibc/bitutil.hpp index 6d2b25e0d1..d77e67920f 100644 --- a/options/internal/include/mlibc/bitutil.hpp +++ b/options/internal/include/mlibc/bitutil.hpp @@ -5,28 +5,18 @@ namespace mlibc { -template -struct bit_util; - -template<> -struct bit_util { - static uint64_t byteswap(uint64_t x) { - return __builtin_bswap64(x); - } +template struct bit_util; + +template <> struct bit_util { + static uint64_t byteswap(uint64_t x) { return __builtin_bswap64(x); } }; -template<> -struct bit_util { - static uint32_t byteswap(uint32_t x) { - return __builtin_bswap32(x); - } +template <> struct bit_util { + static uint32_t byteswap(uint32_t x) { return __builtin_bswap32(x); } }; -template<> -struct bit_util { - static uint16_t byteswap(uint16_t x) { - return __builtin_bswap16(x); - } +template <> struct bit_util { + static uint16_t byteswap(uint16_t x) { return __builtin_bswap16(x); } }; } // namespace mlibc diff --git a/options/internal/include/mlibc/charcode.hpp b/options/internal/include/mlibc/charcode.hpp index 67bd03d986..da1d27cad6 100644 --- a/options/internal/include/mlibc/charcode.hpp +++ b/options/internal/include/mlibc/charcode.hpp @@ -1,30 +1,21 @@ #ifndef MLIBC_CHARCODE_HPP #define MLIBC_CHARCODE_HPP -#include -#include #include #include #include +#include +#include namespace mlibc { -enum class charcode_error { - null, - dirty, - illegal_input, - input_underflow, - output_overflow -}; +enum class charcode_error { null, dirty, illegal_input, input_underflow, output_overflow }; -template -struct code_seq { +template struct code_seq { C *it; const C *end; - explicit operator bool () { - return it != end; - } + explicit operator bool() { return it != end; } }; // Some encodings (e.g. the one defined in RFC 1843) have "shift states", @@ -47,7 +38,7 @@ struct polymorphic_charcode { // Helper function to decode a single char. charcode_error promote(char nc, codepoint &wc) { auto uc = static_cast(nc); - if(uc <= 0x7F && preserves_7bit_units) { + if (uc <= 0x7F && preserves_7bit_units) { wc = uc; return charcode_error::null; } @@ -56,7 +47,7 @@ struct polymorphic_charcode { code_seq wseq{&wc, &wc + 1}; __mlibc_mbstate st = __MLIBC_MBSTATE_INITIALIZER; - if(auto e = decode(nseq, wseq, st); e != charcode_error::null) + if (auto e = decode(nseq, wseq, st); e != charcode_error::null) return e; // This should have read/written exactly one code unit/code point. __ensure(nseq.it == nseq.end); @@ -67,7 +58,7 @@ struct polymorphic_charcode { // Helper function to decode a single char. charcode_error promote_wtranscode(char nc, wchar_t &wc) { auto uc = static_cast(nc); - if(uc <= 0x7F && preserves_7bit_units) { // TODO: Use "wtranscode_preserves_7bit_units". + if (uc <= 0x7F && preserves_7bit_units) { // TODO: Use "wtranscode_preserves_7bit_units". wc = uc; return charcode_error::null; } @@ -76,7 +67,7 @@ struct polymorphic_charcode { code_seq wseq{&wc, &wc + 1}; __mlibc_mbstate st = __MLIBC_MBSTATE_INITIALIZER; - if(auto e = decode_wtranscode(nseq, wseq, st); e != charcode_error::null) + if (auto e = decode_wtranscode(nseq, wseq, st); e != charcode_error::null) return e; // This should have read/written exactly one code unit/code point. __ensure(nseq.it == nseq.end); @@ -85,22 +76,23 @@ struct polymorphic_charcode { } polymorphic_charcode(bool preserves_7bit_units_, bool has_shift_states_) - : preserves_7bit_units{preserves_7bit_units_}, has_shift_states{has_shift_states_} { } + : preserves_7bit_units{preserves_7bit_units_}, + has_shift_states{has_shift_states_} {} - virtual charcode_error decode(code_seq &nseq, code_seq &wseq, - __mlibc_mbstate &st) = 0; + virtual charcode_error + decode(code_seq &nseq, code_seq &wseq, __mlibc_mbstate &st) = 0; - virtual charcode_error decode_wtranscode(code_seq &nseq, code_seq &wseq, - __mlibc_mbstate &st) = 0; + virtual charcode_error + decode_wtranscode(code_seq &nseq, code_seq &wseq, __mlibc_mbstate &st) = 0; - virtual charcode_error decode_wtranscode_length(code_seq &nseq, size_t *n, - __mlibc_mbstate &st) = 0; + virtual charcode_error + decode_wtranscode_length(code_seq &nseq, size_t *n, __mlibc_mbstate &st) = 0; - virtual charcode_error encode_wtranscode(code_seq &nseq, code_seq &wseq, - __mlibc_mbstate &st) = 0; + virtual charcode_error + encode_wtranscode(code_seq &nseq, code_seq &wseq, __mlibc_mbstate &st) = 0; - virtual charcode_error encode_wtranscode_length(code_seq &wseq, size_t *n, - __mlibc_mbstate &st) = 0; + virtual charcode_error + encode_wtranscode_length(code_seq &wseq, size_t *n, __mlibc_mbstate &st) = 0; // True if promotion only zero-extends units below 0x7F. const bool preserves_7bit_units; diff --git a/options/internal/include/mlibc/debug.hpp b/options/internal/include/mlibc/debug.hpp index 7067039a7e..fadcf802b2 100644 --- a/options/internal/include/mlibc/debug.hpp +++ b/options/internal/include/mlibc/debug.hpp @@ -9,14 +9,14 @@ struct InfoSink { // constexpr so that this can be initialized statically. constexpr InfoSink() = default; - void operator() (const char *message); + void operator()(const char *message); }; struct PanicSink { // constexpr so that this can be initialized statically. constexpr PanicSink() = default; - void operator() (const char *message); + void operator()(const char *message); }; extern frg::stack_buffer_logger infoLogger; diff --git a/options/internal/include/mlibc/file-window.hpp b/options/internal/include/mlibc/file-window.hpp index 72af2d8d9f..324985b45c 100644 --- a/options/internal/include/mlibc/file-window.hpp +++ b/options/internal/include/mlibc/file-window.hpp @@ -2,29 +2,27 @@ #define MLIBC_FILE_WINDOW #include +#include #include #include #include -#include struct file_window { file_window(const char *path) { int fd; - if(mlibc::sys_open(path, O_RDONLY, 0, &fd)) - mlibc::panicLogger() << "mlibc: Error opening file_window to " - << path << frg::endlog; + if (mlibc::sys_open(path, O_RDONLY, 0, &fd)) + mlibc::panicLogger() << "mlibc: Error opening file_window to " << path << frg::endlog; - if(!mlibc::sys_stat) { + if (!mlibc::sys_stat) { MLIBC_MISSING_SYSDEP(); __ensure(!"cannot proceed without sys_stat"); } struct stat info; - if(mlibc::sys_stat(mlibc::fsfd_target::fd, fd, "", 0, &info)) + if (mlibc::sys_stat(mlibc::fsfd_target::fd, fd, "", 0, &info)) mlibc::panicLogger() << "mlibc: Error getting TZinfo stats" << frg::endlog; #if MLIBC_MAP_FILE_WINDOWS - if(mlibc::sys_vm_map(nullptr, (size_t)info.st_size, PROT_READ, MAP_PRIVATE, - fd, 0, &_ptr)) + if (mlibc::sys_vm_map(nullptr, (size_t)info.st_size, PROT_READ, MAP_PRIVATE, fd, 0, &_ptr)) mlibc::panicLogger() << "mlibc: Error mapping TZinfo" << frg::endlog; #else _ptr = getAllocator().allocate(info.st_size); @@ -32,33 +30,32 @@ struct file_window { size_t progress = 0; size_t st_size = static_cast(info.st_size); - while(progress < st_size) { + while (progress < st_size) { ssize_t chunk; - if(int e = mlibc::sys_read(fd, reinterpret_cast(_ptr) + progress, - st_size - progress, &chunk); e) + if (int e = mlibc::sys_read( + fd, reinterpret_cast(_ptr) + progress, st_size - progress, &chunk + ); + e) mlibc::panicLogger() << "mlibc: Read from file_window failed" << frg::endlog; - if(!chunk) + if (!chunk) break; progress += chunk; } - if(progress != st_size) + if (progress != st_size) mlibc::panicLogger() << "stat reports " << info.st_size << " but we only read " - << progress << " bytes" << frg::endlog; + << progress << " bytes" << frg::endlog; #endif - if(mlibc::sys_close(fd)) + if (mlibc::sys_close(fd)) mlibc::panicLogger() << "mlibc: Error closing TZinfo" << frg::endlog; } // TODO: Write destructor to deallocate/unmap memory. - void *get() { - return _ptr; - } + void *get() { return _ptr; } -private: + private: void *_ptr; }; #endif // MLIBC_FILE_WINDOW - diff --git a/options/internal/include/mlibc/fsfd_target.hpp b/options/internal/include/mlibc/fsfd_target.hpp index b577325f3d..f193302cca 100644 --- a/options/internal/include/mlibc/fsfd_target.hpp +++ b/options/internal/include/mlibc/fsfd_target.hpp @@ -3,12 +3,7 @@ namespace mlibc { -enum class fsfd_target { - none, - path, - fd, - fd_path -}; +enum class fsfd_target { none, path, fd, fd_path }; } // namespace mlibc diff --git a/options/internal/include/mlibc/global-config.hpp b/options/internal/include/mlibc/global-config.hpp index 7eaed3c106..ece4ea25ce 100644 --- a/options/internal/include/mlibc/global-config.hpp +++ b/options/internal/include/mlibc/global-config.hpp @@ -5,7 +5,7 @@ namespace mlibc { struct GlobalConfig { GlobalConfig(); - + bool debugMalloc; }; @@ -14,6 +14,6 @@ inline const GlobalConfig &globalConfig() { return cached; } -} +} // namespace mlibc #endif // MLIBC_GLOBAL_CONFIG diff --git a/options/internal/include/mlibc/internal-sysdeps.hpp b/options/internal/include/mlibc/internal-sysdeps.hpp index 02df713030..fa1bf03c2c 100644 --- a/options/internal/include/mlibc/internal-sysdeps.hpp +++ b/options/internal/include/mlibc/internal-sysdeps.hpp @@ -4,10 +4,10 @@ #include #include +#include #include #include #include -#include #include namespace [[gnu::visibility("hidden")]] mlibc { @@ -29,13 +29,14 @@ int sys_read(int fd, void *buf, size_t count, ssize_t *bytes_read); int sys_seek(int fd, off_t offset, int whence, off_t *new_offset); int sys_close(int fd); -[[gnu::weak]] int sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, - struct stat *statbuf); -// mlibc assumes that anonymous memory returned by sys_vm_map() is zeroed by the kernel / whatever is behind the sysdeps +[[gnu::weak]] int +sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, struct stat *statbuf); +// mlibc assumes that anonymous memory returned by sys_vm_map() is zeroed by the kernel / whatever +// is behind the sysdeps int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offset, void **window); int sys_vm_unmap(void *pointer, size_t size); [[gnu::weak]] int sys_vm_protect(void *pointer, size_t size, int prot); -} //namespace mlibc +} // namespace mlibc #endif // MLIBC_INTERNAL_SYSDEPS diff --git a/options/internal/include/mlibc/lock.hpp b/options/internal/include/mlibc/lock.hpp index 85ceb4e231..8f9eafbe31 100644 --- a/options/internal/include/mlibc/lock.hpp +++ b/options/internal/include/mlibc/lock.hpp @@ -1,24 +1,23 @@ #ifndef MLIBC_LOCK_HPP #define MLIBC_LOCK_HPP +#include #include -#include -#include #include +#include #include -#include +#include // alignas(4) is specified for the benefit of m68k, where default alignment is // 2 bytes for a uint32_t, while the futex syscall requires 4-byte alignment. // It is a no-op on any other architecture. -template -struct alignas(4) FutexLockImpl { - FutexLockImpl() : _state{0}, _recursion{0} { } +template struct alignas(4) FutexLockImpl { + FutexLockImpl() : _state{0}, _recursion{0} {} FutexLockImpl(const FutexLockImpl &) = delete; - FutexLockImpl &operator= (const FutexLockImpl &) = delete; + FutexLockImpl &operator=(const FutexLockImpl &) = delete; static constexpr uint32_t waitersBit = (1 << 31); static constexpr uint32_t ownerMask = (static_cast(1) << 30) - 1; @@ -27,44 +26,53 @@ struct alignas(4) FutexLockImpl { unsigned int this_tid = mlibc::this_tid(); unsigned int expected = 0; - while(true) { - if(!expected) { + while (true) { + if (!expected) { // Try to take the mutex here. - if(__atomic_compare_exchange_n(&_state, - &expected, this_tid, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) { + if (__atomic_compare_exchange_n( + &_state, &expected, this_tid, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE + )) { if constexpr (Recursive) { __ensure(!_recursion); _recursion = 1; } return; } - }else{ + } else { // If this (recursive) mutex is already owned by us, increment the recursion level. - if((expected & ownerMask) == this_tid) { + if ((expected & ownerMask) == this_tid) { if constexpr (Recursive) ++_recursion; else - mlibc::panicLogger() << "mlibc: FutexLock deadlock detected!" << frg::endlog; + mlibc::panicLogger() + << "mlibc: FutexLock deadlock detected!" << frg::endlog; return; } // Wait on the futex if the waiters flag is set. - if(expected & waitersBit) { + if (expected & waitersBit) { int e = mlibc::sys_futex_wait((int *)&_state, expected, nullptr); // If the wait returns EAGAIN, that means that the waitersBit was just unset by // some other thread. In this case, we should loop back around. // Also loop around in case of a signal interrupting the wait if (e && e != EAGAIN && e != EINTR) - mlibc::panicLogger() << "sys_futex_wait() failed with error code " << e << frg::endlog; + mlibc::panicLogger() + << "sys_futex_wait() failed with error code " << e << frg::endlog; // Opportunistically try to take the lock after we wake up. expected = 0; - }else{ + } else { // Otherwise we have to set the waiters flag first. unsigned int desired = expected | waitersBit; - if(__atomic_compare_exchange_n((int *)&_state, - reinterpret_cast(&expected), desired, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) + if (__atomic_compare_exchange_n( + (int *)&_state, + reinterpret_cast(&expected), + desired, + false, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) expected = desired; } } @@ -75,17 +83,18 @@ struct alignas(4) FutexLockImpl { unsigned int this_tid = mlibc::this_tid(); unsigned int expected = __atomic_load_n(&_state, __ATOMIC_RELAXED); - if(!expected) { + if (!expected) { // Try to take the mutex here. - if(__atomic_compare_exchange_n(&_state, - &expected, this_tid, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) { + if (__atomic_compare_exchange_n( + &_state, &expected, this_tid, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE + )) { if constexpr (Recursive) _recursion = 1; return true; } } else { // If this (recursive) mutex is already owned by us, increment the recursion level. - if((expected & ownerMask) == this_tid) { + if ((expected & ownerMask) == this_tid) { if constexpr (Recursive) { __ensure(!_recursion); ++_recursion; @@ -103,7 +112,7 @@ struct alignas(4) FutexLockImpl { // Decrement the recursion level and unlock if we hit zero. if constexpr (Recursive) { __ensure(_recursion); - if(--_recursion) + if (--_recursion) return; } @@ -111,14 +120,16 @@ struct alignas(4) FutexLockImpl { auto state = __atomic_exchange_n(&_state, 0, __ATOMIC_RELEASE); __ensure((state & ownerMask) == mlibc::this_tid()); - if(state & waitersBit) { - // Wake the futex if there were waiters. Since the mutex might not exist at this location - // anymore, we must conservatively ignore EACCES and EINVAL which may occur as a result. + if (state & waitersBit) { + // Wake the futex if there were waiters. Since the mutex might not exist at this + // location anymore, we must conservatively ignore EACCES and EINVAL which may occur as + // a result. int e = mlibc::sys_futex_wake((int *)&_state); __ensure(e >= 0 || e == EACCES || e == EINVAL); } } -private: + + private: uint32_t _state; uint32_t _recursion; }; diff --git a/options/internal/include/mlibc/strtofp.hpp b/options/internal/include/mlibc/strtofp.hpp index f9c5e20d72..f45c0a8d83 100644 --- a/options/internal/include/mlibc/strtofp.hpp +++ b/options/internal/include/mlibc/strtofp.hpp @@ -1,14 +1,13 @@ #ifndef MLIBC_STRTOFP_HPP #define MLIBC_STRTOFP_HPP -#include #include +#include #include namespace mlibc { -template -T strtofp(const char *str, char **endptr) { +template T strtofp(const char *str, char **endptr) { if (strcmp(str, "INF") == 0 || strcmp(str, "inf") == 0) { if (endptr) *endptr = (char *)str + 3; @@ -19,14 +18,14 @@ T strtofp(const char *str, char **endptr) { else return __builtin_infl(); } else if (strcmp(str, "INFINITY") == 0 || strcmp(str, "infinity") == 0) { - if (endptr) - *endptr = (char *)str + 8; - if constexpr (std::is_same_v) - return __builtin_inff(); - else if constexpr (std::is_same_v) - return __builtin_inf(); - else - return __builtin_infl(); + if (endptr) + *endptr = (char *)str + 8; + if constexpr (std::is_same_v) + return __builtin_inff(); + else if constexpr (std::is_same_v) + return __builtin_inf(); + else + return __builtin_infl(); } else if (strncmp(str, "NAN", 3) == 0 || strncmp(str, "nan", 3) == 0) { if (endptr) *endptr = (char *)str + 3; @@ -89,7 +88,8 @@ T strtofp(const char *str, char **endptr) { while (true) { if (!isxdigit(*tmp)) break; - result += static_cast(*tmp <= '9' ? (*tmp - '0') : (tolower(*tmp) - 'a' + 10)) / d; + result += + static_cast(*tmp <= '9' ? (*tmp - '0') : (tolower(*tmp) - 'a' + 10)) / d; d *= static_cast(16); tmp++; } @@ -160,6 +160,6 @@ T strtofp(const char *str, char **endptr) { return result; } -} +} // namespace mlibc #endif // MLIBC_STRTOFP_HPP diff --git a/options/internal/include/mlibc/strtol.hpp b/options/internal/include/mlibc/strtol.hpp index 2dab276715..124b92fe6d 100644 --- a/options/internal/include/mlibc/strtol.hpp +++ b/options/internal/include/mlibc/strtol.hpp @@ -1,43 +1,38 @@ #ifndef MLIBC_STRTOL_HPP #define MLIBC_STRTOL_HPP -#include #include -#include #include +#include +#include namespace mlibc { -template struct int_limits {}; +template struct int_limits {}; -template<> -struct int_limits { +template <> struct int_limits { static long max() { return LONG_MAX; } static long min() { return LONG_MIN; } }; -template<> -struct int_limits { +template <> struct int_limits { static unsigned long max() { return ULONG_MAX; } static unsigned long min() { return 0; } }; -template<> -struct int_limits { +template <> struct int_limits { static long long max() { return LLONG_MAX; } static long long min() { return LLONG_MIN; } }; -template<> -struct int_limits { +template <> struct int_limits { static unsigned long long max() { return ULLONG_MAX; } static unsigned long long min() { return 0; } }; -template struct char_detail {}; +template struct char_detail {}; -template<> -struct char_detail { +template <> struct char_detail { static bool isSpace(char c) { return isspace(c); } static bool isDigit(char c) { return isdigit(c); } static bool isHexDigit(char c) { return isxdigit(c); } @@ -45,8 +40,7 @@ struct char_detail { static bool isUpper(char c) { return isupper(c); } }; -template<> -struct char_detail { +template <> struct char_detail { static bool isSpace(wchar_t c) { return iswspace(c); } static bool isDigit(wchar_t c) { return iswdigit(c); } static bool isHexDigit(wchar_t c) { return iswxdigit(c); } @@ -54,9 +48,9 @@ struct char_detail { static bool isUpper(wchar_t c) { return iswupper(c); } }; -template Char widen(char c) { return static_cast(c); } +template Char widen(char c) { return static_cast(c); } -template +template Return stringToInteger(const Char *__restrict nptr, Char **__restrict endptr, int baseInt) { using UnsignedReturn = std::make_unsigned_t; @@ -80,7 +74,6 @@ Return stringToInteger(const Char *__restrict nptr, Char **__restrict endptr, in s++; } - bool hasOctalPrefix = s[0] == widen('0'); bool hasHexPrefix = hasOctalPrefix && (s[1] == widen('x') || s[1] == widen('X')); bool hasBinPrefix = hasOctalPrefix && (s[1] == widen('b') || s[1] == widen('B')); @@ -97,7 +90,7 @@ Return stringToInteger(const Char *__restrict nptr, Char **__restrict endptr, in base = 2; } else if ((base == 0 || base == 8) && hasOctalPrefix) { base = 8; - } else if (base == 0) { + } else if (base == 0) { base = 10; } @@ -158,6 +151,6 @@ Return stringToInteger(const Char *__restrict nptr, Char **__restrict endptr, in return negative ? -totalValue : totalValue; } -} +} // namespace mlibc #endif // MLIBC_STRTOL_HPP diff --git a/options/internal/include/mlibc/tcb.hpp b/options/internal/include/mlibc/tcb.hpp index 129fdd66fd..a346f6cd3d 100644 --- a/options/internal/include/mlibc/tcb.hpp +++ b/options/internal/include/mlibc/tcb.hpp @@ -1,9 +1,9 @@ #pragma once -#include -#include #include #include +#include +#include #include "elf.hpp" @@ -34,52 +34,49 @@ */ namespace { - // Set when the cancellation is enabled - constexpr unsigned int tcbCancelEnableBit = 1 << 0; - // 1 - cancellation is asynchronous, 0 - cancellation is deferred - constexpr unsigned int tcbCancelAsyncBit = 1 << 1; - // Set when the thread has been cancelled - constexpr unsigned int tcbCancelTriggerBit = 1 << 2; - // Set when the thread is in the process of being cancelled. - constexpr unsigned int tcbCancelingBit = 1 << 3; - // Set when the thread is exiting. - constexpr unsigned int tcbExitingBit = 1 << 4; -} +// Set when the cancellation is enabled +constexpr unsigned int tcbCancelEnableBit = 1 << 0; +// 1 - cancellation is asynchronous, 0 - cancellation is deferred +constexpr unsigned int tcbCancelAsyncBit = 1 << 1; +// Set when the thread has been cancelled +constexpr unsigned int tcbCancelTriggerBit = 1 << 2; +// Set when the thread is in the process of being cancelled. +constexpr unsigned int tcbCancelingBit = 1 << 3; +// Set when the thread is exiting. +constexpr unsigned int tcbExitingBit = 1 << 4; +} // namespace namespace mlibc { - // Returns true when bitmask indicates thread has been asynchronously - // cancelled. - static constexpr bool tcb_async_cancelled(int value) { - return (value & (tcbCancelEnableBit | tcbCancelAsyncBit - | tcbCancelTriggerBit)) == (tcbCancelEnableBit - | tcbCancelAsyncBit | tcbCancelTriggerBit); - } +// Returns true when bitmask indicates thread has been asynchronously +// cancelled. +static constexpr bool tcb_async_cancelled(int value) { + return (value & (tcbCancelEnableBit | tcbCancelAsyncBit | tcbCancelTriggerBit)) == + (tcbCancelEnableBit | tcbCancelAsyncBit | tcbCancelTriggerBit); +} - // Returns true when bitmask indicates async cancellation is enabled. - static constexpr bool tcb_async_cancel(int value) { - return (value & (tcbCancelEnableBit | tcbCancelAsyncBit)) - == (tcbCancelEnableBit | tcbCancelAsyncBit); - } +// Returns true when bitmask indicates async cancellation is enabled. +static constexpr bool tcb_async_cancel(int value) { + return (value & (tcbCancelEnableBit | tcbCancelAsyncBit)) == + (tcbCancelEnableBit | tcbCancelAsyncBit); +} - // Returns true when bitmask indicates cancellation is enabled. - static constexpr bool tcb_cancel_enabled(int value) { - return (value & tcbCancelEnableBit); - } +// Returns true when bitmask indicates cancellation is enabled. +static constexpr bool tcb_cancel_enabled(int value) { return (value & tcbCancelEnableBit); } - // Returns true when bitmask indicates threas has been cancelled. - static constexpr bool tcb_cancelled(int value) { - return (value & (tcbCancelEnableBit | tcbCancelTriggerBit)) - == (tcbCancelEnableBit | tcbCancelTriggerBit); - } +// Returns true when bitmask indicates threas has been cancelled. +static constexpr bool tcb_cancelled(int value) { + return (value & (tcbCancelEnableBit | tcbCancelTriggerBit)) == + (tcbCancelEnableBit | tcbCancelTriggerBit); +} #if !MLIBC_STATIC_BUILD && !MLIBC_BUILDING_RTLD - // In non-static builds, libc.so always has a TCB available. - constexpr bool tcb_available_flag = true; +// In non-static builds, libc.so always has a TCB available. +constexpr bool tcb_available_flag = true; #else - // Otherwise this will be set to true after RTLD has initialized the TCB. - extern bool tcb_available_flag; +// Otherwise this will be set to true after RTLD has initialized the TCB. +extern bool tcb_available_flag; #endif -} +} // namespace mlibc enum class TcbThreadReturnValue { Pointer, @@ -139,7 +136,7 @@ struct Tcb { size_t guardSize; inline void invokeThreadFunc(void *entry, void *user_arg) { - if(returnValueType == TcbThreadReturnValue::Pointer) { + if (returnValueType == TcbThreadReturnValue::Pointer) { auto func = reinterpret_cast(entry); returnValue.voidPtr = func(user_arg); } else { @@ -177,7 +174,7 @@ static_assert(sizeof(Tcb) - offsetof(Tcb, cancelBits) - TP_TCB_OFFSET == 80); // sysdeps/linux/riscv64/cp_syscall.S needs to be updated whenever // the struct is expanded. static_assert(sizeof(Tcb) - offsetof(Tcb, cancelBits) == 96); -#elif defined (__m68k__) +#elif defined(__m68k__) // The thread pointer on m68k points to 0x7000 bytes *after* the end of the // TCB, so similarly to as on RISC-V, we need to keep the value in // sysdeps/linux/m68k/cp_syscall.S up-to-date. diff --git a/options/internal/include/mlibc/threads.hpp b/options/internal/include/mlibc/threads.hpp index 989a8e5ddb..3754e22ab4 100644 --- a/options/internal/include/mlibc/threads.hpp +++ b/options/internal/include/mlibc/threads.hpp @@ -5,11 +5,19 @@ namespace mlibc { -int thread_create(struct __mlibc_thread_data **__restrict thread, const struct __mlibc_threadattr *__restrict attrp, void *entry, void *__restrict user_arg, bool returns_int); +int thread_create( + struct __mlibc_thread_data **__restrict thread, + const struct __mlibc_threadattr *__restrict attrp, + void *entry, + void *__restrict user_arg, + bool returns_int +); int thread_attr_init(struct __mlibc_threadattr *attr); int thread_join(struct __mlibc_thread_data *thread, void *res); -int thread_mutex_init(struct __mlibc_mutex *__restrict mutex, const struct __mlibc_mutexattr *__restrict attr); +int thread_mutex_init( + struct __mlibc_mutex *__restrict mutex, const struct __mlibc_mutexattr *__restrict attr +); int thread_mutex_destroy(struct __mlibc_mutex *mutex); int thread_mutex_lock(struct __mlibc_mutex *mutex); int thread_mutex_unlock(struct __mlibc_mutex *mutex); @@ -19,9 +27,15 @@ int thread_mutexattr_destroy(struct __mlibc_mutexattr *attr); int thread_mutexattr_gettype(const struct __mlibc_mutexattr *__restrict attr, int *__restrict type); int thread_mutexattr_settype(struct __mlibc_mutexattr *attr, int type); -int thread_cond_init(struct __mlibc_cond *__restrict cond, const struct __mlibc_condattr *__restrict attr); +int thread_cond_init( + struct __mlibc_cond *__restrict cond, const struct __mlibc_condattr *__restrict attr +); int thread_cond_destroy(struct __mlibc_cond *cond); int thread_cond_broadcast(struct __mlibc_cond *cond); -int thread_cond_timedwait(struct __mlibc_cond *__restrict cond, __mlibc_mutex *__restrict mutex, const struct timespec *__restrict abstime); +int thread_cond_timedwait( + struct __mlibc_cond *__restrict cond, + __mlibc_mutex *__restrict mutex, + const struct timespec *__restrict abstime +); -} +} // namespace mlibc diff --git a/options/internal/include/mlibc/tid.hpp b/options/internal/include/mlibc/tid.hpp index 9cae787040..d536ec55bf 100644 --- a/options/internal/include/mlibc/tid.hpp +++ b/options/internal/include/mlibc/tid.hpp @@ -1,18 +1,18 @@ #pragma once -#include #include +#include namespace mlibc { - inline unsigned int this_tid() { - // During RTLD initialization, we don't have a TCB. - if (mlibc::tcb_available_flag) { - auto tcb = get_current_tcb(); - return tcb->tid; - } else if (mlibc::sys_futex_tid) { - return mlibc::sys_futex_tid(); - } else { - return 1; - } +inline unsigned int this_tid() { + // During RTLD initialization, we don't have a TCB. + if (mlibc::tcb_available_flag) { + auto tcb = get_current_tcb(); + return tcb->tid; + } else if (mlibc::sys_futex_tid) { + return mlibc::sys_futex_tid(); + } else { + return 1; } } +} // namespace mlibc diff --git a/options/internal/include/stdint.h b/options/internal/include/stdint.h index 36ec413d8d..a3024eeac2 100644 --- a/options/internal/include/stdint.h +++ b/options/internal/include/stdint.h @@ -9,37 +9,37 @@ /* ---------------------------------------------------------------------------- */ /* Fixed-width (signed). */ -typedef __mlibc_int8 int8_t; +typedef __mlibc_int8 int8_t; typedef __mlibc_int16 int16_t; typedef __mlibc_int32 int32_t; typedef __mlibc_int64 int64_t; /* Fixed-width (unsigned). */ -typedef __mlibc_uint8 uint8_t; +typedef __mlibc_uint8 uint8_t; typedef __mlibc_uint16 uint16_t; typedef __mlibc_uint32 uint32_t; typedef __mlibc_uint64 uint64_t; /* Least-width (signed). */ -typedef __mlibc_int8 int_least8_t; +typedef __mlibc_int8 int_least8_t; typedef __mlibc_int16 int_least16_t; typedef __mlibc_int32 int_least32_t; typedef __mlibc_int64 int_least64_t; /* Least-width (unsigned). */ -typedef __mlibc_uint8 uint_least8_t; +typedef __mlibc_uint8 uint_least8_t; typedef __mlibc_uint16 uint_least16_t; typedef __mlibc_uint32 uint_least32_t; typedef __mlibc_uint64 uint_least64_t; /* Fast-width (signed). */ -typedef __mlibc_int_fast8 int_fast8_t; +typedef __mlibc_int_fast8 int_fast8_t; typedef __mlibc_int_fast16 int_fast16_t; typedef __mlibc_int_fast32 int_fast32_t; typedef __mlibc_int_fast64 int_fast64_t; /* Fast-width (unsigned). */ -typedef __mlibc_uint_fast8 uint_fast8_t; +typedef __mlibc_uint_fast8 uint_fast8_t; typedef __mlibc_uint_fast16 uint_fast16_t; typedef __mlibc_uint_fast32 uint_fast32_t; typedef __mlibc_uint_fast64 uint_fast64_t; @@ -57,14 +57,14 @@ typedef __mlibc_uintptr uintptr_t; /* ---------------------------------------------------------------------------- */ /* Fixed-width (signed). */ -#define INT8_C(x) __MLIBC_INT8_C(x) +#define INT8_C(x) __MLIBC_INT8_C(x) #define INT16_C(x) __MLIBC_INT16_C(x) #define INT32_C(x) __MLIBC_INT32_C(x) #define INT64_C(x) __MLIBC_INT64_C(x) #define INTMAX_C(x) __MLIBC_INTMAX_C(x) /* Fixed-width (unsigned). */ -#define UINT8_C(x) __MLIBC_UINT8_C(x) +#define UINT8_C(x) __MLIBC_UINT8_C(x) #define UINT16_C(x) __MLIBC_UINT16_C(x) #define UINT32_C(x) __MLIBC_UINT32_C(x) #define UINT64_C(x) __MLIBC_UINT64_C(x) @@ -75,52 +75,52 @@ typedef __mlibc_uintptr uintptr_t; /* ---------------------------------------------------------------------------- */ /* Fixed-width (signed). */ -#define INT8_MAX __MLIBC_INT8_MAX +#define INT8_MAX __MLIBC_INT8_MAX #define INT16_MAX __MLIBC_INT16_MAX #define INT32_MAX __MLIBC_INT32_MAX #define INT64_MAX __MLIBC_INT64_MAX -#define INT8_MIN __MLIBC_INT8_MIN +#define INT8_MIN __MLIBC_INT8_MIN #define INT16_MIN __MLIBC_INT16_MIN #define INT32_MIN __MLIBC_INT32_MIN #define INT64_MIN __MLIBC_INT64_MIN /* Fixed-width (unsigned). */ -#define UINT8_MAX __MLIBC_UINT8_MAX +#define UINT8_MAX __MLIBC_UINT8_MAX #define UINT16_MAX __MLIBC_UINT16_MAX #define UINT32_MAX __MLIBC_UINT32_MAX #define UINT64_MAX __MLIBC_UINT64_MAX /* Least-width (signed). */ -#define INT_LEAST8_MAX __MLIBC_INT8_MAX +#define INT_LEAST8_MAX __MLIBC_INT8_MAX #define INT_LEAST16_MAX __MLIBC_INT16_MAX #define INT_LEAST32_MAX __MLIBC_INT32_MAX #define INT_LEAST64_MAX __MLIBC_INT64_MAX -#define INT_LEAST8_MIN __MLIBC_INT8_MIN +#define INT_LEAST8_MIN __MLIBC_INT8_MIN #define INT_LEAST16_MIN __MLIBC_INT16_MIN #define INT_LEAST32_MIN __MLIBC_INT32_MIN #define INT_LEAST64_MIN __MLIBC_INT64_MIN /* Least-width (unsigned). */ -#define UINT_LEAST8_MAX __MLIBC_UINT8_MAX +#define UINT_LEAST8_MAX __MLIBC_UINT8_MAX #define UINT_LEAST16_MAX __MLIBC_UINT16_MAX #define UINT_LEAST32_MAX __MLIBC_UINT32_MAX #define UINT_LEAST64_MAX __MLIBC_UINT64_MAX /* Fast-width (signed). */ -#define INT_FAST8_MAX __MLIBC_INT_FAST8_MAX +#define INT_FAST8_MAX __MLIBC_INT_FAST8_MAX #define INT_FAST16_MAX __MLIBC_INT_FAST16_MAX #define INT_FAST32_MAX __MLIBC_INT_FAST32_MAX #define INT_FAST64_MAX __MLIBC_INT_FAST64_MAX -#define INT_FAST8_MIN __MLIBC_INT_FAST8_MIN +#define INT_FAST8_MIN __MLIBC_INT_FAST8_MIN #define INT_FAST16_MIN __MLIBC_INT_FAST16_MIN #define INT_FAST32_MIN __MLIBC_INT_FAST32_MIN #define INT_FAST64_MIN __MLIBC_INT_FAST64_MIN /* Fast-width (unsigned). */ -#define UINT_FAST8_MAX __MLIBC_UINT_FAST8_MAX +#define UINT_FAST8_MAX __MLIBC_UINT_FAST8_MAX #define UINT_FAST16_MAX __MLIBC_UINT_FAST16_MAX #define UINT_FAST32_MAX __MLIBC_UINT_FAST32_MAX #define UINT_FAST64_MAX __MLIBC_UINT_FAST64_MAX @@ -137,12 +137,12 @@ typedef __mlibc_uintptr uintptr_t; #define UINTPTR_MAX __MLIBC_UINTPTR_MAX /* Other limits (signed). */ -#define PTRDIFF_MAX __MLIBC_PTRDIFF_MAX -#define PTRDIFF_MIN __MLIBC_PTRDIFF_MIN +#define PTRDIFF_MAX __MLIBC_PTRDIFF_MAX +#define PTRDIFF_MIN __MLIBC_PTRDIFF_MIN #define SIG_ATOMIC_MAX __MLIBC_SIG_ATOMIC_MAX #define SIG_ATOMIC_MIN __MLIBC_SIG_ATOMIC_MIN -#define WINT_MAX __MLIBC_WINT_MAX -#define WINT_MIN __MLIBC_WINT_MIN +#define WINT_MAX __MLIBC_WINT_MAX +#define WINT_MIN __MLIBC_WINT_MIN /* Other limits (unsigned). */ #define SIZE_MAX __MLIBC_SIZE_MAX diff --git a/options/internal/m68k-include/mlibc/thread.hpp b/options/internal/m68k-include/mlibc/thread.hpp index 9142b08f19..7b144d63bb 100644 --- a/options/internal/m68k-include/mlibc/thread.hpp +++ b/options/internal/m68k-include/mlibc/thread.hpp @@ -1,9 +1,9 @@ #pragma once -#include +#include #include #include -#include +#include namespace mlibc { @@ -17,7 +17,7 @@ inline Tcb *get_current_tcb() { inline uintptr_t get_sp() { uintptr_t sp; - asm ("move.l %%sp, %0" : "=r"(sp)); + asm("move.l %%sp, %0" : "=r"(sp)); return sp; } diff --git a/options/internal/riscv64-include/mlibc/thread.hpp b/options/internal/riscv64-include/mlibc/thread.hpp index 7428b759b7..9b26b6f2c2 100644 --- a/options/internal/riscv64-include/mlibc/thread.hpp +++ b/options/internal/riscv64-include/mlibc/thread.hpp @@ -1,8 +1,8 @@ #pragma once -#include -#include #include +#include +#include namespace mlibc { @@ -16,7 +16,7 @@ inline Tcb *get_current_tcb() { inline uintptr_t get_sp() { uintptr_t sp; - asm ("mv %0, sp" : "=r"(sp)); + asm("mv %0, sp" : "=r"(sp)); return sp; } diff --git a/options/internal/x86-include/mlibc/arch-defs.hpp b/options/internal/x86-include/mlibc/arch-defs.hpp old mode 100755 new mode 100644 index aa8fe38507..0a4789f539 --- a/options/internal/x86-include/mlibc/arch-defs.hpp +++ b/options/internal/x86-include/mlibc/arch-defs.hpp @@ -10,4 +10,3 @@ inline constexpr size_t page_size = 0x1000; } // namespace mlibc #endif // MLIBC_ARCH_DEFS_HPP - diff --git a/options/internal/x86-include/mlibc/thread.hpp b/options/internal/x86-include/mlibc/thread.hpp old mode 100755 new mode 100644 index 3475fb4968..97e4d54adf --- a/options/internal/x86-include/mlibc/thread.hpp +++ b/options/internal/x86-include/mlibc/thread.hpp @@ -1,21 +1,20 @@ #pragma once -#include #include +#include namespace mlibc { inline Tcb *get_current_tcb() { uintptr_t ptr; - asm ("movl %%gs:0, %0" : "=r"(ptr)); + asm("movl %%gs:0, %0" : "=r"(ptr)); return reinterpret_cast(ptr); } inline uintptr_t get_sp() { uintptr_t esp; - asm ("mov %%esp, %0" : "=r"(esp)); + asm("mov %%esp, %0" : "=r"(esp)); return esp; } } // namespace mlibc - diff --git a/options/internal/x86_64-include/mlibc/thread.hpp b/options/internal/x86_64-include/mlibc/thread.hpp index ed02b677e9..d48dd4269d 100644 --- a/options/internal/x86_64-include/mlibc/thread.hpp +++ b/options/internal/x86_64-include/mlibc/thread.hpp @@ -1,19 +1,19 @@ #pragma once -#include #include +#include namespace mlibc { inline Tcb *get_current_tcb() { uintptr_t ptr; - asm ("movq %%fs:0, %0" : "=r"(ptr)); + asm("movq %%fs:0, %0" : "=r"(ptr)); return reinterpret_cast(ptr); } inline uintptr_t get_sp() { uintptr_t rsp; - asm ("mov %%rsp, %0" : "=r"(rsp)); + asm("mov %%rsp, %0" : "=r"(rsp)); return rsp; } diff --git a/options/linux/generic/cpuset.cpp b/options/linux/generic/cpuset.cpp index d0292b7633..d7c93043c7 100644 --- a/options/linux/generic/cpuset.cpp +++ b/options/linux/generic/cpuset.cpp @@ -20,7 +20,7 @@ void __mlibc_cpu_zero(const size_t setsize, cpu_set_t *set) { } void __mlibc_cpu_set(const int cpu, const size_t setsize, cpu_set_t *set) { - if(cpu >= static_cast(setsize * CHAR_BIT)) { + if (cpu >= static_cast(setsize * CHAR_BIT)) { return; } @@ -32,7 +32,7 @@ void __mlibc_cpu_set(const int cpu, const size_t setsize, cpu_set_t *set) { } void __mlibc_cpu_clear(const int cpu, const size_t setsize, cpu_set_t *set) { - if(cpu >= static_cast(setsize * CHAR_BIT)) { + if (cpu >= static_cast(setsize * CHAR_BIT)) { return; } @@ -43,9 +43,8 @@ void __mlibc_cpu_clear(const int cpu, const size_t setsize, cpu_set_t *set) { ptr[off] &= ~mask; } - int __mlibc_cpu_isset(const int cpu, const size_t setsize, const cpu_set_t *set) { - if(cpu >= static_cast(setsize * CHAR_BIT)) { + if (cpu >= static_cast(setsize * CHAR_BIT)) { return false; } @@ -60,9 +59,9 @@ int __mlibc_cpu_count(const size_t setsize, const cpu_set_t *set) { size_t count = 0; const unsigned char *ptr = reinterpret_cast(set); - for(size_t i = 0; i < setsize; i++) { - for(size_t bit = 0; bit < CHAR_BIT; bit++) { - if((1 << bit) & ptr[i]) + for (size_t i = 0; i < setsize; i++) { + for (size_t bit = 0; bit < CHAR_BIT; bit++) { + if ((1 << bit) & ptr[i]) count++; } } diff --git a/options/linux/generic/ifaddrs.cpp b/options/linux/generic/ifaddrs.cpp index 85565c0b7f..d0b0fb4fd0 100644 --- a/options/linux/generic/ifaddrs.cpp +++ b/options/linux/generic/ifaddrs.cpp @@ -1,11 +1,11 @@ +#include +#include #include #include -#include -#include int getifaddrs(struct ifaddrs **ifap) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getifaddrs, -1); - if(int e = sysdep(ifap); e) { + if (int e = sysdep(ifap); e) { errno = e; return -1; } diff --git a/options/linux/generic/linux-unistd.cpp b/options/linux/generic/linux-unistd.cpp index ec13f72b01..d384679a83 100644 --- a/options/linux/generic/linux-unistd.cpp +++ b/options/linux/generic/linux-unistd.cpp @@ -1,17 +1,17 @@ -#include #include +#include #include #include #include int dup3(int oldfd, int newfd, int flags) { - if(oldfd == newfd) { + if (oldfd == newfd) { errno = EINVAL; return -1; } MLIBC_CHECK_OR_ENOSYS(mlibc::sys_dup2, -1); - if(int e = mlibc::sys_dup2(oldfd, flags, newfd); e) { + if (int e = mlibc::sys_dup2(oldfd, flags, newfd); e) { errno = e; return -1; } @@ -23,9 +23,7 @@ int vhangup(void) { __builtin_unreachable(); } -int getdtablesize(void){ - return sysconf(_SC_OPEN_MAX); -} +int getdtablesize(void) { return sysconf(_SC_OPEN_MAX); } int syncfs(int) { __ensure(!"Not implemented"); diff --git a/options/linux/generic/mntent.cpp b/options/linux/generic/mntent.cpp index 35c0e928c2..e0af1f9ba8 100644 --- a/options/linux/generic/mntent.cpp +++ b/options/linux/generic/mntent.cpp @@ -1,23 +1,21 @@ +#include #include +#include #include #include -#include #include -#include namespace { char *internal_buf; size_t internal_bufsize; -} +} // namespace #define SENTINEL (char *)&internal_buf -FILE *setmntent(const char *name, const char *mode) { - return fopen(name, mode); -} +FILE *setmntent(const char *name, const char *mode) { return fopen(name, mode); } struct mntent *getmntent(FILE *f) { static struct mntent mnt; @@ -25,24 +23,29 @@ struct mntent *getmntent(FILE *f) { } int addmntent(FILE *f, const struct mntent *mnt) { - if(fseek(f, 0, SEEK_END)) { + if (fseek(f, 0, SEEK_END)) { return 1; } - return fprintf(f, "%s\t%s\t%s\t%s\t%d\t%d\n", - mnt->mnt_fsname, mnt->mnt_dir, mnt->mnt_type, mnt->mnt_opts, - mnt->mnt_freq, mnt->mnt_passno) < 0; + return fprintf( + f, + "%s\t%s\t%s\t%s\t%d\t%d\n", + mnt->mnt_fsname, + mnt->mnt_dir, + mnt->mnt_type, + mnt->mnt_opts, + mnt->mnt_freq, + mnt->mnt_passno + ) < 0; } int endmntent(FILE *f) { - if(f) { + if (f) { fclose(f); } return 1; } -char *hasmntopt(const struct mntent *mnt, const char *opt) { - return strstr(mnt->mnt_opts, opt); -} +char *hasmntopt(const struct mntent *mnt, const char *opt) { return strstr(mnt->mnt_opts, opt); } /* Adapted from musl */ struct mntent *getmntent_r(FILE *f, struct mntent *mnt, char *linebuf, int buflen) { @@ -55,34 +58,45 @@ struct mntent *getmntent_r(FILE *f, struct mntent *mnt, char *linebuf, int bufle mnt->mnt_passno = 0; do { - if(use_internal) { + if (use_internal) { getline(&internal_buf, &internal_bufsize, f); linebuf = internal_buf; } else { fgets(linebuf, buflen, f); } - if(feof(f) || ferror(f)) { + if (feof(f) || ferror(f)) { return 0; } - if(!strchr(linebuf, '\n')) { + if (!strchr(linebuf, '\n')) { fscanf(f, "%*[^\n]%*[\n]"); errno = ERANGE; return 0; } len = strlen(linebuf); - if(len > INT_MAX) { + if (len > INT_MAX) { continue; } - for(i = 0; i < sizeof n / sizeof *n; i++) { + for (i = 0; i < sizeof n / sizeof *n; i++) { n[i] = len; } - sscanf(linebuf, " %n%*s%n %n%*s%n %n%*s%n %n%*s%n %d %d", - n, n + 1, n + 2, n + 3, n + 4, n + 5, n + 6, n + 7, - &mnt->mnt_freq, &mnt->mnt_passno); - } while(linebuf[n[0]] == '#' || n[1] == len); + sscanf( + linebuf, + " %n%*s%n %n%*s%n %n%*s%n %n%*s%n %d %d", + n, + n + 1, + n + 2, + n + 3, + n + 4, + n + 5, + n + 6, + n + 7, + &mnt->mnt_freq, + &mnt->mnt_passno + ); + } while (linebuf[n[0]] == '#' || n[1] == len); linebuf[n[1]] = 0; linebuf[n[3]] = 0; diff --git a/options/linux/generic/module.cpp b/options/linux/generic/module.cpp index 53b6dc8677..9fa7a74732 100644 --- a/options/linux/generic/module.cpp +++ b/options/linux/generic/module.cpp @@ -7,7 +7,7 @@ int init_module(void *module, unsigned long length, const char *args) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_init_module, -1); - if(int e = mlibc::sys_init_module(module, length, args); e) { + if (int e = mlibc::sys_init_module(module, length, args); e) { errno = e; return -1; } @@ -16,7 +16,7 @@ int init_module(void *module, unsigned long length, const char *args) { int delete_module(const char *name, unsigned flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_delete_module, -1); - if(int e = mlibc::sys_delete_module(name, flags); e) { + if (int e = mlibc::sys_delete_module(name, flags); e) { errno = e; return -1; } diff --git a/options/linux/generic/pty.cpp b/options/linux/generic/pty.cpp index ac00856e10..bb45ad5764 100644 --- a/options/linux/generic/pty.cpp +++ b/options/linux/generic/pty.cpp @@ -4,40 +4,40 @@ #include #include #include -#include #include +#include #include #include -#include +#include #include #include int openpty(int *mfd, int *sfd, char *name, const struct termios *ios, const struct winsize *win) { int ptmx_fd; - if(int e = mlibc::sys_open("/dev/ptmx", O_RDWR | O_NOCTTY, 0, &ptmx_fd); e) { + if (int e = mlibc::sys_open("/dev/ptmx", O_RDWR | O_NOCTTY, 0, &ptmx_fd); e) { errno = e; goto fail; } char spath[32]; - if(!name) + if (!name) name = spath; - if(ptsname_r(ptmx_fd, name, 32)) + if (ptsname_r(ptmx_fd, name, 32)) goto fail; int pts_fd; unlockpt(ptmx_fd); - if(int e = mlibc::sys_open(name, O_RDWR | O_NOCTTY, 0, &pts_fd); e) { + if (int e = mlibc::sys_open(name, O_RDWR | O_NOCTTY, 0, &pts_fd); e) { errno = e; goto fail; } - if(ios) + if (ios) tcsetattr(ptmx_fd, TCSAFLUSH, ios); - if(win) - ioctl(ptmx_fd, TIOCSWINSZ, (void*)win); + if (win) + ioctl(ptmx_fd, TIOCSWINSZ, (void *)win); *mfd = ptmx_fd; *sfd = pts_fd; @@ -49,26 +49,26 @@ int openpty(int *mfd, int *sfd, char *name, const struct termios *ios, const str } int login_tty(int fd) { - if(setsid() == -1) + if (setsid() == -1) return -1; - if(ioctl(fd, TIOCSCTTY, 0)) + if (ioctl(fd, TIOCSCTTY, 0)) return -1; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_dup2, -1); - if(int e = mlibc::sys_dup2(fd, 0, STDIN_FILENO); e) { + if (int e = mlibc::sys_dup2(fd, 0, STDIN_FILENO); e) { errno = e; return -1; } - if(int e = mlibc::sys_dup2(fd, 0, STDOUT_FILENO); e) { + if (int e = mlibc::sys_dup2(fd, 0, STDOUT_FILENO); e) { errno = e; return -1; } - if(int e = mlibc::sys_dup2(fd, 0, STDERR_FILENO); e) { + if (int e = mlibc::sys_dup2(fd, 0, STDERR_FILENO); e) { errno = e; return -1; } - if(int e = mlibc::sys_close(fd); e) { + if (int e = mlibc::sys_close(fd); e) { errno = e; return -1; } @@ -77,21 +77,21 @@ int login_tty(int fd) { int forkpty(int *mfd, char *name, const struct termios *ios, const struct winsize *win) { int sfd; - if(openpty(mfd, &sfd, name, ios, win)) + if (openpty(mfd, &sfd, name, ios, win)) return -1; pid_t child; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fork, -1); - if(int e = mlibc::sys_fork(&child); e) { + if (int e = mlibc::sys_fork(&child); e) { errno = e; return -1; } - if(!child) { - if(login_tty(sfd)) + if (!child) { + if (login_tty(sfd)) mlibc::panicLogger() << "mlibc: TTY login fail in forkpty() child" << frg::endlog; - }else{ - if(int e = mlibc::sys_close(sfd); e) { + } else { + if (int e = mlibc::sys_close(sfd); e) { errno = e; return -1; } @@ -99,4 +99,3 @@ int forkpty(int *mfd, char *name, const struct termios *ios, const struct winsiz return child; } - diff --git a/options/linux/generic/sched.cpp b/options/linux/generic/sched.cpp index 760a9f5476..b90539ead9 100644 --- a/options/linux/generic/sched.cpp +++ b/options/linux/generic/sched.cpp @@ -8,7 +8,7 @@ int sched_getcpu(void) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getcpu, -1); int cpu; - if(int e = mlibc::sys_getcpu(&cpu); e) { + if (int e = mlibc::sys_getcpu(&cpu); e) { errno = e; return -1; } @@ -27,7 +27,7 @@ int sched_getscheduler(pid_t) { int sched_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getaffinity, -1); - if(int e = mlibc::sys_getaffinity(pid, cpusetsize, mask); e) { + if (int e = mlibc::sys_getaffinity(pid, cpusetsize, mask); e) { errno = e; return -1; } diff --git a/options/linux/generic/sys-epoll.cpp b/options/linux/generic/sys-epoll.cpp index 799d1a989c..714123c7d8 100644 --- a/options/linux/generic/sys-epoll.cpp +++ b/options/linux/generic/sys-epoll.cpp @@ -9,18 +9,17 @@ int epoll_create(int) { int fd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_epoll_create, -1); - if(int e = mlibc::sys_epoll_create(0, &fd); e) { + if (int e = mlibc::sys_epoll_create(0, &fd); e) { errno = e; return -1; } return fd; } -int epoll_pwait(int epfd, struct epoll_event *evnts, int n, int timeout, - const sigset_t *sigmask) { +int epoll_pwait(int epfd, struct epoll_event *evnts, int n, int timeout, const sigset_t *sigmask) { int raised; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_epoll_pwait, -1); - if(int e = mlibc::sys_epoll_pwait(epfd, evnts, n, timeout, sigmask, &raised)) { + if (int e = mlibc::sys_epoll_pwait(epfd, evnts, n, timeout, sigmask, &raised)) { errno = e; return -1; } @@ -30,7 +29,7 @@ int epoll_pwait(int epfd, struct epoll_event *evnts, int n, int timeout, int epoll_create1(int flags) { int fd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_epoll_create, -1); - if(int e = mlibc::sys_epoll_create(flags, &fd); e) { + if (int e = mlibc::sys_epoll_create(flags, &fd); e) { errno = e; return -1; } @@ -39,7 +38,7 @@ int epoll_create1(int flags) { int epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_epoll_ctl, -1); - if(int e = mlibc::sys_epoll_ctl(epfd, mode, fd, ev); e) { + if (int e = mlibc::sys_epoll_ctl(epfd, mode, fd, ev); e) { errno = e; return -1; } @@ -49,10 +48,9 @@ int epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) { int epoll_wait(int epfd, struct epoll_event *evnts, int n, int timeout) { int raised; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_epoll_pwait, -1); - if(int e = mlibc::sys_epoll_pwait(epfd, evnts, n, timeout, NULL, &raised)) { + if (int e = mlibc::sys_epoll_pwait(epfd, evnts, n, timeout, NULL, &raised)) { errno = e; return -1; } return raised; } - diff --git a/options/linux/generic/sys-eventfd.cpp b/options/linux/generic/sys-eventfd.cpp index 1d83d8c93c..1aeb7b960d 100644 --- a/options/linux/generic/sys-eventfd.cpp +++ b/options/linux/generic/sys-eventfd.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include diff --git a/options/linux/generic/sys-inotify.cpp b/options/linux/generic/sys-inotify.cpp index 0bc25c9222..9539d13880 100644 --- a/options/linux/generic/sys-inotify.cpp +++ b/options/linux/generic/sys-inotify.cpp @@ -9,7 +9,7 @@ int inotify_init(void) { int fd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_inotify_create, -1); - if(int e = mlibc::sys_inotify_create(0, &fd); e) { + if (int e = mlibc::sys_inotify_create(0, &fd); e) { errno = e; return -1; } @@ -19,7 +19,7 @@ int inotify_init(void) { int inotify_init1(int flags) { int fd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_inotify_create, -1); - if(int e = mlibc::sys_inotify_create(flags, &fd); e) { + if (int e = mlibc::sys_inotify_create(flags, &fd); e) { errno = e; return -1; } @@ -29,7 +29,7 @@ int inotify_init1(int flags) { int inotify_add_watch(int ifd, const char *path, uint32_t mask) { int wd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_inotify_add_watch, -1); - if(int e = mlibc::sys_inotify_add_watch(ifd, path, mask, &wd); e) { + if (int e = mlibc::sys_inotify_add_watch(ifd, path, mask, &wd); e) { errno = e; return -1; } @@ -38,10 +38,9 @@ int inotify_add_watch(int ifd, const char *path, uint32_t mask) { int inotify_rm_watch(int ifd, int wd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_inotify_rm_watch, -1); - if(int e = mlibc::sys_inotify_rm_watch(ifd, wd); e) { + if (int e = mlibc::sys_inotify_rm_watch(ifd, wd); e) { errno = e; return -1; } return 0; } - diff --git a/options/linux/generic/sys-mount.cpp b/options/linux/generic/sys-mount.cpp index 47831835ff..d164815da8 100644 --- a/options/linux/generic/sys-mount.cpp +++ b/options/linux/generic/sys-mount.cpp @@ -5,23 +5,26 @@ #include #include -int mount(const char *source, const char *target, - const char *fstype, unsigned long flags, const void *data) { +int mount( + const char *source, + const char *target, + const char *fstype, + unsigned long flags, + const void *data +) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mount, -1); - if(int e = mlibc::sys_mount(source, target, fstype, flags, data); e) { + if (int e = mlibc::sys_mount(source, target, fstype, flags, data); e) { errno = e; return -1; } return 0; } -int umount(const char *target) { - return umount2(target, 0); -} +int umount(const char *target) { return umount2(target, 0); } int umount2(const char *target, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_umount2, -1); - if(int e = mlibc::sys_umount2(target, flags); e) { + if (int e = mlibc::sys_umount2(target, flags); e) { errno = e; return -1; } diff --git a/options/linux/generic/sys-prctl.cpp b/options/linux/generic/sys-prctl.cpp index 5280332c4e..d110c245a5 100644 --- a/options/linux/generic/sys-prctl.cpp +++ b/options/linux/generic/sys-prctl.cpp @@ -1,7 +1,7 @@ -#include -#include #include +#include +#include #include #include @@ -14,7 +14,7 @@ int prctl(int op, ...) { int val; va_list ap; va_start(ap, op); - if(int e = mlibc::sys_prctl(op, ap, &val); e) { + if (int e = mlibc::sys_prctl(op, ap, &val); e) { errno = e; return -1; } @@ -22,4 +22,3 @@ int prctl(int op, ...) { return val; } - diff --git a/options/linux/generic/sys-ptrace.cpp b/options/linux/generic/sys-ptrace.cpp index 8c836c548a..9d37f02c01 100644 --- a/options/linux/generic/sys-ptrace.cpp +++ b/options/linux/generic/sys-ptrace.cpp @@ -1,7 +1,7 @@ -#include -#include #include +#include +#include #include #include @@ -17,20 +17,19 @@ long ptrace(int req, ...) { va_end(ap); long ret; - if(req > 0 && req < 4) { + if (req > 0 && req < 4) { data = &ret; } MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ptrace, -1); long out; - if(int e = mlibc::sys_ptrace(req, pid, addr, data, &out); e) { + if (int e = mlibc::sys_ptrace(req, pid, addr, data, &out); e) { errno = e; return -1; - } else if(req > 0 && req < 4) { + } else if (req > 0 && req < 4) { errno = 0; return ret; } return out; } - diff --git a/options/linux/generic/sys-random.cpp b/options/linux/generic/sys-random.cpp index 5e5057ff7f..e4efc3eb8b 100644 --- a/options/linux/generic/sys-random.cpp +++ b/options/linux/generic/sys-random.cpp @@ -1,6 +1,6 @@ -#include #include +#include #include #include @@ -8,12 +8,12 @@ #include ssize_t getrandom(void *buffer, size_t max_size, unsigned int flags) { - if(flags & ~(GRND_RANDOM | GRND_NONBLOCK)) { + if (flags & ~(GRND_RANDOM | GRND_NONBLOCK)) { errno = EINVAL; return -1; } MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getentropy, -1); - if(int e = mlibc::sys_getentropy(buffer, max_size); e) { + if (int e = mlibc::sys_getentropy(buffer, max_size); e) { errno = e; return -1; } diff --git a/options/linux/generic/sys-reboot.cpp b/options/linux/generic/sys-reboot.cpp index c9b503fc89..e1424046f1 100644 --- a/options/linux/generic/sys-reboot.cpp +++ b/options/linux/generic/sys-reboot.cpp @@ -1,7 +1,7 @@ -#include -#include #include +#include #include +#include int reboot(int what) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_reboot, -1); diff --git a/options/linux/generic/sys-sendfile.cpp b/options/linux/generic/sys-sendfile.cpp index 25cd0a0eae..9f3d188f7f 100644 --- a/options/linux/generic/sys-sendfile.cpp +++ b/options/linux/generic/sys-sendfile.cpp @@ -1,9 +1,8 @@ -#include #include +#include ssize_t sendfile(int, int, off_t *, size_t) { __ensure(!"Not implemented"); __builtin_unreachable(); } - diff --git a/options/linux/generic/sys-signalfd.cpp b/options/linux/generic/sys-signalfd.cpp index 8dd2cf8e1a..4b9369834c 100644 --- a/options/linux/generic/sys-signalfd.cpp +++ b/options/linux/generic/sys-signalfd.cpp @@ -7,16 +7,15 @@ #include int signalfd(int fd, const sigset_t *mask, int flags) { - if(fd != -1) { + if (fd != -1) { mlibc::infoLogger() << "mlibc: signalfd with fd != -1 is not supported yet" << frg::endlog; return 0; } __ensure(fd == -1); MLIBC_CHECK_OR_ENOSYS(mlibc::sys_signalfd_create, -1); - if(int e = mlibc::sys_signalfd_create(mask, flags, &fd); e) { + if (int e = mlibc::sys_signalfd_create(mask, flags, &fd); e) { errno = e; return -1; } return fd; } - diff --git a/options/linux/generic/sys-statfs.cpp b/options/linux/generic/sys-statfs.cpp index 853c8088cd..c6a802f1be 100644 --- a/options/linux/generic/sys-statfs.cpp +++ b/options/linux/generic/sys-statfs.cpp @@ -1,14 +1,14 @@ +#include #include #include -#include #include #include int statfs(const char *path, struct statfs *buf) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_statfs, -1); - if(int e = mlibc::sys_statfs(path, buf); e) { + if (int e = mlibc::sys_statfs(path, buf); e) { errno = e; return -1; } @@ -25,4 +25,3 @@ int fstatfs(int fd, struct statfs *buf) { } [[gnu::alias("fstatfs")]] int fstatfs64(int, struct statfs64 *); - diff --git a/options/linux/generic/sys-statx.cpp b/options/linux/generic/sys-statx.cpp index 67a972d574..b317b4ba3b 100644 --- a/options/linux/generic/sys-statx.cpp +++ b/options/linux/generic/sys-statx.cpp @@ -1,34 +1,36 @@ +#include #include #include #include -#include #include -#include #include +#include int statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct statx *statxbuf) { - if(!mlibc::sys_statx) { + if (!mlibc::sys_statx) { struct stat statbuf; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_stat, -1); if (!(flags & AT_NO_AUTOMOUNT)) { - mlibc::infoLogger() - << "mlibc: sys_statx is unavailable, and stat does not support not specifying AT_NO_MOUNTPOINT" - << frg::endlog; + mlibc::infoLogger() << "mlibc: sys_statx is unavailable, and stat does not support not " + "specifying AT_NO_MOUNTPOINT" + << frg::endlog; } // AT_STATX_SYNC_AS_STAT is the default and behaves like good old stat if ((flags & AT_STATX_FORCE_SYNC) || (flags & AT_STATX_DONT_SYNC)) { - mlibc::infoLogger() - << "mlibc: sys_statx is unavailable, and stat does not support modes other than AT_STATX_SYNC_AS_STAT" - << frg::endlog; + mlibc::infoLogger() << "mlibc: sys_statx is unavailable, and stat does not support " + "modes other than AT_STATX_SYNC_AS_STAT" + << frg::endlog; } // Mask out flags not appropriate for regular stat - flags &= ~(AT_NO_AUTOMOUNT | AT_STATX_SYNC_AS_STAT | AT_STATX_FORCE_SYNC | AT_STATX_DONT_SYNC); + flags &= + ~(AT_NO_AUTOMOUNT | AT_STATX_SYNC_AS_STAT | AT_STATX_FORCE_SYNC | AT_STATX_DONT_SYNC); - if(int e = mlibc::sys_stat(mlibc::fsfd_target::fd_path, dirfd, pathname, flags, &statbuf); e) { + if (int e = mlibc::sys_stat(mlibc::fsfd_target::fd_path, dirfd, pathname, flags, &statbuf); + e) { errno = e; return -1; } @@ -62,10 +64,9 @@ int statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct } auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_statx, -1); - if(int e = sysdep(dirfd, pathname, flags, mask, statxbuf); e) { + if (int e = sysdep(dirfd, pathname, flags, mask, statxbuf); e) { errno = e; return -1; } return 0; } - diff --git a/options/linux/generic/sys-swap.cpp b/options/linux/generic/sys-swap.cpp index 44ddf98e53..8a7aa57ec9 100644 --- a/options/linux/generic/sys-swap.cpp +++ b/options/linux/generic/sys-swap.cpp @@ -7,7 +7,7 @@ int swapon(const char *path, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_swapon, -1); - if(int e = mlibc::sys_swapon(path, flags); e) { + if (int e = mlibc::sys_swapon(path, flags); e) { errno = e; return -1; } @@ -16,7 +16,7 @@ int swapon(const char *path, int flags) { int swapoff(const char *path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_swapoff, -1); - if(int e = mlibc::sys_swapoff(path); e) { + if (int e = mlibc::sys_swapoff(path); e) { errno = e; return -1; } diff --git a/options/linux/generic/sys-sysinfo.cpp b/options/linux/generic/sys-sysinfo.cpp index 950c38a33d..f86c8d42df 100644 --- a/options/linux/generic/sys-sysinfo.cpp +++ b/options/linux/generic/sys-sysinfo.cpp @@ -7,7 +7,7 @@ int sysinfo(struct sysinfo *info) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sysinfo, -1); - if(int e = mlibc::sys_sysinfo(info); e) { + if (int e = mlibc::sys_sysinfo(info); e) { errno = e; return -1; } diff --git a/options/linux/generic/sys-timerfd.cpp b/options/linux/generic/sys-timerfd.cpp index 80bca1b867..b1b8358702 100644 --- a/options/linux/generic/sys-timerfd.cpp +++ b/options/linux/generic/sys-timerfd.cpp @@ -9,17 +9,17 @@ int timerfd_create(int clockid, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_timerfd_create, -1); int fd; - if(int e = mlibc::sys_timerfd_create(clockid, flags, &fd); e) { + if (int e = mlibc::sys_timerfd_create(clockid, flags, &fd); e) { errno = e; return -1; } return fd; } -int timerfd_settime(int fd, int flags, const struct itimerspec *value, - struct itimerspec *oldvalue) { +int +timerfd_settime(int fd, int flags, const struct itimerspec *value, struct itimerspec *oldvalue) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_timerfd_settime, -1); - if(int e = mlibc::sys_timerfd_settime(fd, flags, value, oldvalue); e) { + if (int e = mlibc::sys_timerfd_settime(fd, flags, value, oldvalue); e) { errno = e; return -1; } @@ -30,4 +30,3 @@ int timerfd_gettime(int, struct itimerspec *) { __ensure(!"Not implemented"); __builtin_unreachable(); } - diff --git a/options/linux/generic/sys-xattr.cpp b/options/linux/generic/sys-xattr.cpp index c8d598f395..3fb50c1a90 100644 --- a/options/linux/generic/sys-xattr.cpp +++ b/options/linux/generic/sys-xattr.cpp @@ -1,11 +1,10 @@ #include #include -#include #include +#include -int setxattr(const char *path, const char *name, const void *val, size_t size, - int flags) { +int setxattr(const char *path, const char *name, const void *val, size_t size, int flags) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setxattr, -1); if (int e = sysdep(path, name, val, size, flags); e) { @@ -15,8 +14,7 @@ int setxattr(const char *path, const char *name, const void *val, size_t size, return 0; } -int lsetxattr(const char *path, const char *name, const void *val, size_t size, - int flags) { +int lsetxattr(const char *path, const char *name, const void *val, size_t size, int flags) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_lsetxattr, -1); if (int e = sysdep(path, name, val, size, flags); e) { @@ -26,8 +24,7 @@ int lsetxattr(const char *path, const char *name, const void *val, size_t size, return 0; } -int fsetxattr(int fd, const char *name, const void *val, size_t size, - int flags) { +int fsetxattr(int fd, const char *name, const void *val, size_t size, int flags) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fsetxattr, -1); if (int e = sysdep(fd, name, val, size, flags); e) { diff --git a/options/linux/generic/utmp.cpp b/options/linux/generic/utmp.cpp index 658dfd3123..3bdfa85624 100644 --- a/options/linux/generic/utmp.cpp +++ b/options/linux/generic/utmp.cpp @@ -1,8 +1,8 @@ -#include #include #include #include #include +#include #include #include @@ -22,9 +22,9 @@ static off_t offset; static struct utmp last_entry; void setutent(void) { - if(fd < 0) { + if (fd < 0) { fd = open("/run/utmp", O_RDONLY | O_LARGEFILE | O_CLOEXEC); - if(fd == -1) { + if (fd == -1) { return; } } @@ -37,9 +37,9 @@ static ssize_t read_last_entry(void) { struct utmp buf; ssize_t bytes_read = pread(fd, &buf, sizeof(buf), offset); - if(bytes_read < 0) { + if (bytes_read < 0) { return -1; - } else if(bytes_read != sizeof(buf)) { + } else if (bytes_read != sizeof(buf)) { // EOF return 0; } else { @@ -52,14 +52,14 @@ static ssize_t read_last_entry(void) { struct utmp *getutent(void) { struct utmp *result; static struct utmp *buf; - if(buf == NULL) { + if (buf == NULL) { buf = (struct utmp *)malloc(sizeof(struct utmp)); - if(buf == NULL) { + if (buf == NULL) { return NULL; } } - if(getutent_r(buf, &result) < 0) { + if (getutent_r(buf, &result) < 0) { return NULL; } return result; @@ -68,14 +68,14 @@ struct utmp *getutent(void) { int getutent_r(struct utmp *buf, struct utmp **res) { int saved_errno = errno; - if(fd < 0) { + if (fd < 0) { setutent(); } ssize_t bytes_read = read_last_entry(); - if(bytes_read <= 0) { - if(bytes_read == 0) { + if (bytes_read <= 0) { + if (bytes_read == 0) { errno = saved_errno; *res = NULL; return -1; @@ -89,7 +89,7 @@ int getutent_r(struct utmp *buf, struct utmp **res) { } void endutent(void) { - if(fd >= 0) { + if (fd >= 0) { close(fd); fd = -1; } diff --git a/options/linux/generic/utmpx.cpp b/options/linux/generic/utmpx.cpp index 474256736e..f44752804d 100644 --- a/options/linux/generic/utmpx.cpp +++ b/options/linux/generic/utmpx.cpp @@ -1,8 +1,8 @@ #include -#include #include -#include #include +#include +#include void updwtmpx(const char *, const struct utmpx *) { // Empty as musl does diff --git a/options/linux/include/bits/linux/linux_sched.h b/options/linux/include/bits/linux/linux_sched.h index 2cbd9fa680..96013079e3 100644 --- a/options/linux/include/bits/linux/linux_sched.h +++ b/options/linux/include/bits/linux/linux_sched.h @@ -7,12 +7,12 @@ extern "C" { #endif #include -#include #include +#include #define CLONE_VM 0x00000100 #define CLONE_FS 0x00000200 -#define CLONE_FILES 0x00000400 +#define CLONE_FILES 0x00000400 #define CLONE_SIGHAND 0x00000800 #define CLONE_PTRACE 0x00002000 #define CLONE_VFORK 0x00004000 diff --git a/options/linux/include/bits/linux/linux_stat.h b/options/linux/include/bits/linux/linux_stat.h index c7ca0f6105..51a1738817 100644 --- a/options/linux/include/bits/linux/linux_stat.h +++ b/options/linux/include/bits/linux/linux_stat.h @@ -9,7 +9,9 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -int statx(int __dirfd, const char *__pathname, int __flags, unsigned int __mask, struct statx *__statxbuf); +int statx( + int __dirfd, const char *__pathname, int __flags, unsigned int __mask, struct statx *__statxbuf +); #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/linux/include/ifaddrs.h b/options/linux/include/ifaddrs.h index c57ff3d11e..ca5a867b9f 100644 --- a/options/linux/include/ifaddrs.h +++ b/options/linux/include/ifaddrs.h @@ -1,6 +1,6 @@ -#ifndef _IFADDRS_H -#define _IFADDRS_H +#ifndef _IFADDRS_H +#define _IFADDRS_H #ifdef __cplusplus extern "C" { diff --git a/options/linux/include/lastlog.h b/options/linux/include/lastlog.h index a10b0bb9ba..6ff999e816 100644 --- a/options/linux/include/lastlog.h +++ b/options/linux/include/lastlog.h @@ -1,2 +1,2 @@ /* Maches glibc */ -#include \ No newline at end of file +#include diff --git a/options/linux/include/malloc.h b/options/linux/include/malloc.h index 382dac2aae..7f9b034f42 100644 --- a/options/linux/include/malloc.h +++ b/options/linux/include/malloc.h @@ -29,4 +29,3 @@ void *memalign(size_t __alignment, size_t __size); #endif #endif /* _MALLOC_H */ - diff --git a/options/linux/include/memory.h b/options/linux/include/memory.h index 296f8adaac..55cd8e5bb6 100644 --- a/options/linux/include/memory.h +++ b/options/linux/include/memory.h @@ -6,4 +6,3 @@ #include #endif /* _MEMORY_H */ - diff --git a/options/linux/include/mlibc/linux-sysdeps.hpp b/options/linux/include/mlibc/linux-sysdeps.hpp index 0ac22f185a..2bdedcfdd0 100644 --- a/options/linux/include/mlibc/linux-sysdeps.hpp +++ b/options/linux/include/mlibc/linux-sysdeps.hpp @@ -1,18 +1,18 @@ #ifndef MLIBC_LINUX_SYSDEPS #define MLIBC_LINUX_SYSDEPS +#include +#include +#include +#include +#include #include +#include #include #include #include -#include #include -#include -#include -#include -#include -#include -#include +#include namespace [[gnu::visibility("hidden")]] mlibc { @@ -29,15 +29,21 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result); [[gnu::weak]] int sys_inotify_rm_watch(int ifd, int wd); [[gnu::weak]] int sys_epoll_create(int flags, int *fd); [[gnu::weak]] int sys_epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev); -[[gnu::weak]] int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, - int timeout, const sigset_t *sigmask, int *raised); -[[gnu::weak]] int sys_mount(const char *source, const char *target, - const char *fstype, unsigned long flags, const void *data); +[[gnu::weak]] int sys_epoll_pwait( + int epfd, struct epoll_event *ev, int n, int timeout, const sigset_t *sigmask, int *raised +); +[[gnu::weak]] int sys_mount( + const char *source, + const char *target, + const char *fstype, + unsigned long flags, + const void *data +); [[gnu::weak]] int sys_umount2(const char *target, int flags); [[gnu::weak]] int sys_eventfd_create(unsigned int initval, int flags, int *fd); [[gnu::weak]] int sys_timerfd_create(int clockid, int flags, int *fd); -[[gnu::weak]] int sys_timerfd_settime(int fd, int flags, - const struct itimerspec *value, struct itimerspec *oldvalue); +[[gnu::weak]] int +sys_timerfd_settime(int fd, int flags, const struct itimerspec *value, struct itimerspec *oldvalue); [[gnu::weak]] int sys_signalfd_create(const sigset_t *, int flags, int *fd); [[gnu::weak]] int sys_reboot(int cmd); [[gnu::weak]] int sys_ptrace(long req, pid_t pid, void *addr, void *data, long *out); @@ -51,26 +57,21 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result); [[gnu::weak]] int sys_swapon(const char *path, int flags); [[gnu::weak]] int sys_swapoff(const char *path); -[[gnu::weak]] int sys_setxattr(const char *path, const char *name, - const void *val, size_t size, int flags); -[[gnu::weak]] int sys_lsetxattr(const char *path, const char *name, - const void *val, size_t size, int flags); -[[gnu::weak]] int sys_fsetxattr(int fd, const char *name, const void *val, - size_t size, int flags); +[[gnu::weak]] int +sys_setxattr(const char *path, const char *name, const void *val, size_t size, int flags); +[[gnu::weak]] int +sys_lsetxattr(const char *path, const char *name, const void *val, size_t size, int flags); +[[gnu::weak]] int sys_fsetxattr(int fd, const char *name, const void *val, size_t size, int flags); -[[gnu::weak]] int sys_getxattr(const char *path, const char *name, - void *val, size_t size, ssize_t *nread); -[[gnu::weak]] int sys_lgetxattr(const char *path, const char *name, - void *val, size_t size, ssize_t *nread); -[[gnu::weak]] int sys_fgetxattr(int fd, const char *name, void *val, - size_t size, ssize_t *nread); +[[gnu::weak]] int +sys_getxattr(const char *path, const char *name, void *val, size_t size, ssize_t *nread); +[[gnu::weak]] int +sys_lgetxattr(const char *path, const char *name, void *val, size_t size, ssize_t *nread); +[[gnu::weak]] int sys_fgetxattr(int fd, const char *name, void *val, size_t size, ssize_t *nread); -[[gnu::weak]] int sys_listxattr(const char *path, char *list, size_t size, - ssize_t *nread); -[[gnu::weak]] int sys_llistxattr(const char *path, char *list, size_t size, - ssize_t *nread); -[[gnu::weak]] int sys_flistxattr(int fd, char *list, size_t size, - ssize_t *nread); +[[gnu::weak]] int sys_listxattr(const char *path, char *list, size_t size, ssize_t *nread); +[[gnu::weak]] int sys_llistxattr(const char *path, char *list, size_t size, ssize_t *nread); +[[gnu::weak]] int sys_flistxattr(int fd, char *list, size_t size, ssize_t *nread); [[gnu::weak]] int sys_removexattr(const char *path, const char *name); [[gnu::weak]] int sys_lremovexattr(const char *path, const char *name); @@ -79,7 +80,8 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result); [[gnu::weak]] int sys_statfs(const char *path, struct statfs *buf); [[gnu::weak]] int sys_fstatfs(int fd, struct statfs *buf); -[[gnu::weak]] int sys_statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct statx *statxbuf); +[[gnu::weak]] int +sys_statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct statx *statxbuf); [[gnu::weak]] int sys_getifaddrs(struct ifaddrs **); diff --git a/options/linux/include/mntent.h b/options/linux/include/mntent.h index 284c4b69d7..e8c68614cd 100644 --- a/options/linux/include/mntent.h +++ b/options/linux/include/mntent.h @@ -7,12 +7,12 @@ #define MOUNTED "/etc/mtab" /* Generic mount options */ -#define MNTOPT_DEFAULTS "defaults" /* Use all default options. */ -#define MNTOPT_RO "ro" /* Read only. */ -#define MNTOPT_RW "rw" /* Read/write. */ -#define MNTOPT_SUID "suid" /* Set uid allowed. */ -#define MNTOPT_NOSUID "nosuid" /* No set uid allowed. */ -#define MNTOPT_NOAUTO "noauto" /* Do not auto mount. */ +#define MNTOPT_DEFAULTS "defaults" /* Use all default options. */ +#define MNTOPT_RO "ro" /* Read only. */ +#define MNTOPT_RW "rw" /* Read/write. */ +#define MNTOPT_SUID "suid" /* Set uid allowed. */ +#define MNTOPT_NOSUID "nosuid" /* No set uid allowed. */ +#define MNTOPT_NOAUTO "noauto" /* Do not auto mount. */ #ifdef __cplusplus extern "C" { diff --git a/options/linux/include/pty.h b/options/linux/include/pty.h index 6379ae738c..6c53239dd0 100644 --- a/options/linux/include/pty.h +++ b/options/linux/include/pty.h @@ -1,6 +1,6 @@ -#ifndef _PTY_H -#define _PTY_H +#ifndef _PTY_H +#define _PTY_H #include @@ -10,7 +10,9 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -int openpty(int *__mfd, int *__sfd, char *__name, const struct termios *__ios, const struct winsize *__win); +int openpty( + int *__mfd, int *__sfd, char *__name, const struct termios *__ios, const struct winsize *__win +); int forkpty(int *__mfd, char *__name, const struct termios *__ios, const struct winsize *__win); #endif /* !__MLIBC_ABI_ONLY */ @@ -20,4 +22,3 @@ int forkpty(int *__mfd, char *__name, const struct termios *__ios, const struct #endif #endif /* _PTY_H */ - diff --git a/options/linux/include/scsi/scsi.h b/options/linux/include/scsi/scsi.h index fd9cf82af3..b6c7d8a8ee 100644 --- a/options/linux/include/scsi/scsi.h +++ b/options/linux/include/scsi/scsi.h @@ -15,4 +15,3 @@ #define SCSI_IOCTL_PROBE_HOST 0x5385 #endif /* _LINUX_SCSI_SCSI_H */ - diff --git a/options/linux/include/scsi/scsi_ioctl.h b/options/linux/include/scsi/scsi_ioctl.h index 888ae398e8..2593624ff0 100644 --- a/options/linux/include/scsi/scsi_ioctl.h +++ b/options/linux/include/scsi/scsi_ioctl.h @@ -3,4 +3,3 @@ #define _LINUX_SCSI_SCSI_IOCTL_H #endif /* _LINUX_SCSI_SCSI_IOCTL_H */ - diff --git a/options/linux/include/scsi/sg.h b/options/linux/include/scsi/sg.h index 5b3d379ae5..d3da0c4a2e 100644 --- a/options/linux/include/scsi/sg.h +++ b/options/linux/include/scsi/sg.h @@ -22,51 +22,51 @@ extern "C" { #endif typedef struct sg_io_hdr { - int interface_id; - int dxfer_direction; - unsigned char cmd_len; - unsigned char mx_sb_len; - unsigned short iovec_count; - unsigned int dxfer_len; - void *dxferp; - unsigned char *cmdp; - unsigned char *sbp; - unsigned int timeout; - unsigned int flags; - int pack_id; - void *usr_ptr; - unsigned char status; - unsigned char masked_status; - unsigned char msg_status; - unsigned char sb_len_wr; - unsigned short host_status; - unsigned short driver_status; - int resid; - unsigned int duration; - unsigned int info; + int interface_id; + int dxfer_direction; + unsigned char cmd_len; + unsigned char mx_sb_len; + unsigned short iovec_count; + unsigned int dxfer_len; + void *dxferp; + unsigned char *cmdp; + unsigned char *sbp; + unsigned int timeout; + unsigned int flags; + int pack_id; + void *usr_ptr; + unsigned char status; + unsigned char masked_status; + unsigned char msg_status; + unsigned char sb_len_wr; + unsigned short host_status; + unsigned short driver_status; + int resid; + unsigned int duration; + unsigned int info; } sg_io_hdr_t; struct sg_scsi_id { - int host_no; - int channel; - int scsi_id; - int lun; - int scsi_type; - short int h_cmd_per_lun; - short int d_queue_depth; - int unused[2]; + int host_no; + int channel; + int scsi_id; + int lun; + int scsi_type; + short int h_cmd_per_lun; + short int d_queue_depth; + int unused[2]; }; typedef struct sg_req_info { - char req_state; - char orphan; - char sg_io_owned; - char problem; - int pack_id; - void *usr_ptr; - unsigned int duration; + char req_state; + char orphan; + char sg_io_owned; + char problem; + int pack_id; + void *usr_ptr; + unsigned int duration; - int unused; + int unused; } sg_req_info_t; #ifdef __cplusplus @@ -74,4 +74,3 @@ typedef struct sg_req_info { #endif #endif /* _LINUX_SCSI_SG_H */ - diff --git a/options/linux/include/sys/epoll.h b/options/linux/include/sys/epoll.h index aca9b131dd..0a2c29479c 100644 --- a/options/linux/include/sys/epoll.h +++ b/options/linux/include/sys/epoll.h @@ -1,10 +1,10 @@ -#ifndef _SYS_EPOLL_H -#define _SYS_EPOLL_H +#ifndef _SYS_EPOLL_H +#define _SYS_EPOLL_H -#include -#include #include #include +#include +#include #define EPOLL_NONBLOCK O_NONBLOCK @@ -55,7 +55,13 @@ int epoll_create(int __flags); int epoll_create1(int __flags); int epoll_ctl(int __epfd, int __mode, int __fd, struct epoll_event *__ev); int epoll_wait(int __epfd, struct epoll_event *__events, int __maxevents, int __timeout); -int epoll_pwait(int __epfd, struct epoll_event *__events, int __maxevents, int __timeout, const sigset_t *__sigmask); +int epoll_pwait( + int __epfd, + struct epoll_event *__events, + int __maxevents, + int __timeout, + const sigset_t *__sigmask +); #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/linux/include/sys/eventfd.h b/options/linux/include/sys/eventfd.h index 74b200d67d..5271d75375 100644 --- a/options/linux/include/sys/eventfd.h +++ b/options/linux/include/sys/eventfd.h @@ -5,8 +5,8 @@ extern "C" { #endif -#include #include +#include typedef uint64_t eventfd_t; diff --git a/options/linux/include/sys/fsuid.h b/options/linux/include/sys/fsuid.h index 0fa0fb3470..113427eec6 100644 --- a/options/linux/include/sys/fsuid.h +++ b/options/linux/include/sys/fsuid.h @@ -1,8 +1,8 @@ #ifndef _SYS_FSUID_H #define _SYS_FSUID_H -#include #include +#include #ifdef __cplusplus extern "C" { diff --git a/options/linux/include/sys/inotify.h b/options/linux/include/sys/inotify.h index bf9c7c5fef..c533d3f988 100644 --- a/options/linux/include/sys/inotify.h +++ b/options/linux/include/sys/inotify.h @@ -1,9 +1,9 @@ #ifndef _SYS_INOTIFY_H #define _SYS_INOTIFY_H -#include #include #include +#include #ifdef __cplusplus extern "C" { @@ -33,10 +33,9 @@ extern "C" { #define IN_Q_OVERFLOW 0x4000 #define IN_UNMOUNT 0x2000 -#define IN_ALL_EVENTS (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | \ - IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | \ - IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF | \ - IN_MOVE_SELF) +#define IN_ALL_EVENTS \ + (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_CLOSE_NOWRITE | IN_OPEN | \ + IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF | IN_MOVE_SELF) struct inotify_event { int wd; @@ -68,4 +67,3 @@ int inotify_rm_watch(int __ifd, int __wd); #endif #endif /*_SYS_INOTIFY_H */ - diff --git a/options/linux/include/sys/mount.h b/options/linux/include/sys/mount.h index 4094c61f71..a1f7fa036d 100644 --- a/options/linux/include/sys/mount.h +++ b/options/linux/include/sys/mount.h @@ -76,8 +76,13 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -int mount(const char *__source, const char *__target, - const char *__fstype, unsigned long __flags, const void *__data); +int mount( + const char *__source, + const char *__target, + const char *__fstype, + unsigned long __flags, + const void *__data +); int umount(const char *__target); int umount2(const char *__target, int __flags); diff --git a/options/linux/include/sys/prctl.h b/options/linux/include/sys/prctl.h index 61e9eb5aab..5b69a494d0 100644 --- a/options/linux/include/sys/prctl.h +++ b/options/linux/include/sys/prctl.h @@ -125,4 +125,3 @@ int prctl(int __op, ...); #endif /* !__MLIBC_ABI_ONLY */ #endif /* _SYS_PRCTL_H */ - diff --git a/options/linux/include/sys/ptrace.h b/options/linux/include/sys/ptrace.h index 915b01df78..422c6d428b 100644 --- a/options/linux/include/sys/ptrace.h +++ b/options/linux/include/sys/ptrace.h @@ -52,4 +52,3 @@ long ptrace(int __op, ...); #endif #endif /* _SYS_PTRACE_H */ - diff --git a/options/linux/include/sys/quota.h b/options/linux/include/sys/quota.h index 8f6ea0533e..2bd1ec58c5 100644 --- a/options/linux/include/sys/quota.h +++ b/options/linux/include/sys/quota.h @@ -1,5 +1,5 @@ -#ifndef _SYS_QUOTA_H -#define _SYS_QUOTA_H +#ifndef _SYS_QUOTA_H +#define _SYS_QUOTA_H #include diff --git a/options/linux/include/sys/random.h b/options/linux/include/sys/random.h index 51b0b1b8fa..70c768ee9f 100644 --- a/options/linux/include/sys/random.h +++ b/options/linux/include/sys/random.h @@ -9,8 +9,8 @@ extern "C" { #define GRND_RANDOM 1 #define GRND_NONBLOCK 2 -#include #include +#include #ifndef __MLIBC_ABI_ONLY @@ -23,4 +23,3 @@ ssize_t getrandom(void *__buffer, size_t __max_size, unsigned int __flags); #endif #endif /*_SYS_RANDOM_H */ - diff --git a/options/linux/include/sys/sendfile.h b/options/linux/include/sys/sendfile.h index 4a0c359a93..aea5d95103 100644 --- a/options/linux/include/sys/sendfile.h +++ b/options/linux/include/sys/sendfile.h @@ -19,4 +19,3 @@ ssize_t sendfile(int __out_fd, int __in_fd, off_t *__offset, size_t __size); #endif #endif /* _SYS_SENDFILE_H_ */ - diff --git a/options/linux/include/sys/signalfd.h b/options/linux/include/sys/signalfd.h index 13327c12b0..96c7355183 100644 --- a/options/linux/include/sys/signalfd.h +++ b/options/linux/include/sys/signalfd.h @@ -4,8 +4,8 @@ /* TODO: Define sigset separately and remove this include. */ #include /* musl includes those. Restructure this so we do not need them? */ -#include #include +#include #define SFD_CLOEXEC O_CLOEXEC #define SFD_NONBLOCK O_NONBLOCK @@ -15,24 +15,24 @@ extern "C" { #endif struct signalfd_siginfo { - uint32_t ssi_signo; - int32_t ssi_errno; - int32_t ssi_code; - uint32_t ssi_pid; - uint32_t ssi_uid; - int32_t ssi_fd; - uint32_t ssi_tid; - uint32_t ssi_band; - uint32_t ssi_overrun; - uint32_t ssi_trapno; - int32_t ssi_status; - int32_t ssi_int; - uint64_t ssi_ptr; - uint64_t ssi_utime; - uint64_t ssi_stime; - uint64_t ssi_addr; - uint16_t ssi_addr_lsb; - uint8_t pad[128-12*4-4*8-2]; + uint32_t ssi_signo; + int32_t ssi_errno; + int32_t ssi_code; + uint32_t ssi_pid; + uint32_t ssi_uid; + int32_t ssi_fd; + uint32_t ssi_tid; + uint32_t ssi_band; + uint32_t ssi_overrun; + uint32_t ssi_trapno; + int32_t ssi_status; + int32_t ssi_int; + uint64_t ssi_ptr; + uint64_t ssi_utime; + uint64_t ssi_stime; + uint64_t ssi_addr; + uint16_t ssi_addr_lsb; + uint8_t pad[128 - 12 * 4 - 4 * 8 - 2]; }; #ifndef __MLIBC_ABI_ONLY diff --git a/options/linux/include/sys/statfs.h b/options/linux/include/sys/statfs.h index c446307544..ec50ebd4ce 100644 --- a/options/linux/include/sys/statfs.h +++ b/options/linux/include/sys/statfs.h @@ -20,4 +20,3 @@ int fstatfs64(int __fd, struct statfs64 *__buf); #endif #endif /* _SYS_STATFS_H */ - diff --git a/options/linux/include/sys/sysmacros.h b/options/linux/include/sys/sysmacros.h index 98b6580843..dfb23e2b19 100644 --- a/options/linux/include/sys/sysmacros.h +++ b/options/linux/include/sys/sysmacros.h @@ -7,21 +7,21 @@ extern "C" { #include -__MLIBC_INLINE_DEFINITION unsigned int __mlibc_dev_major( - unsigned long long int __dev) { - return ((__dev >> 8) & 0xfff) | ((unsigned int)(__dev >> 32) & ~0xfff); +__MLIBC_INLINE_DEFINITION unsigned int __mlibc_dev_major(unsigned long long int __dev) { + return ((__dev >> 8) & 0xfff) | ((unsigned int)(__dev >> 32) & ~0xfff); } -__MLIBC_INLINE_DEFINITION unsigned int __mlibc_dev_minor( - unsigned long long int __dev) { - return (__dev & 0xff) | ((unsigned int)(__dev >> 12) & ~0xff); +__MLIBC_INLINE_DEFINITION unsigned int __mlibc_dev_minor(unsigned long long int __dev) { + return (__dev & 0xff) | ((unsigned int)(__dev >> 12) & ~0xff); } -__MLIBC_INLINE_DEFINITION unsigned long long int __mlibc_dev_makedev( - unsigned int __major, unsigned int __minor) { - return ((__minor & 0xff) | ((__major & 0xfff) << 8) - | (((unsigned long long int)(__minor & ~0xff)) << 12) - | (((unsigned long long int)(__major & ~0xfff)) << 32)); +__MLIBC_INLINE_DEFINITION unsigned long long int +__mlibc_dev_makedev(unsigned int __major, unsigned int __minor) { + return ( + (__minor & 0xff) | ((__major & 0xfff) << 8) | + (((unsigned long long int)(__minor & ~0xff)) << 12) | + (((unsigned long long int)(__major & ~0xfff)) << 32) + ); } #define major(dev) __mlibc_dev_major(dev) diff --git a/options/linux/include/sys/timerfd.h b/options/linux/include/sys/timerfd.h index 5caac5d890..3782f1f166 100644 --- a/options/linux/include/sys/timerfd.h +++ b/options/linux/include/sys/timerfd.h @@ -2,8 +2,8 @@ #define _SYS_TIMERFD_H /* musl includes those. Refactor and remove them? */ -#include #include +#include #define TFD_NONBLOCK O_NONBLOCK #define TFD_CLOEXEC O_CLOEXEC @@ -20,7 +20,9 @@ struct itimerspec; #ifndef __MLIBC_ABI_ONLY int timerfd_create(int __clockid, int __flags); -int timerfd_settime(int __fd, int __flags, const struct itimerspec *__value, struct itimerspec *__oldvalue); +int timerfd_settime( + int __fd, int __flags, const struct itimerspec *__value, struct itimerspec *__oldvalue +); int timerfd_gettime(int __fd, struct itimerspec *__value); #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/linux/include/sys/vfs.h b/options/linux/include/sys/vfs.h index 7e7e60d694..0f501af559 100644 --- a/options/linux/include/sys/vfs.h +++ b/options/linux/include/sys/vfs.h @@ -13,4 +13,3 @@ extern "C" { #endif #endif /* _SYS_VFS_H */ - diff --git a/options/linux/include/sys/xattr.h b/options/linux/include/sys/xattr.h index 1b9486d28c..d2a65a6a53 100644 --- a/options/linux/include/sys/xattr.h +++ b/options/linux/include/sys/xattr.h @@ -1,8 +1,8 @@ #ifndef _MLIBC_LINUX_SYS_XATTR_H #define _MLIBC_LINUX_SYS_XATTR_H -#include #include +#include #ifdef __cplusplus extern "C" { @@ -10,12 +10,10 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -int setxattr(const char *__path, const char *__name, const void *__val, size_t __size, - int __flags); -int lsetxattr(const char *__path, const char *__name, const void *__val, size_t __size, - int __flags); -int fsetxattr(int __fd, const char *__name, const void *__val, size_t __size, - int __flags); +int setxattr(const char *__path, const char *__name, const void *__val, size_t __size, int __flags); +int +lsetxattr(const char *__path, const char *__name, const void *__val, size_t __size, int __flags); +int fsetxattr(int __fd, const char *__name, const void *__val, size_t __size, int __flags); ssize_t getxattr(const char *__path, const char *__name, void *__val, size_t __size); ssize_t lgetxattr(const char *__path, const char *__name, void *__val, size_t __size); diff --git a/options/linux/include/utmp.h b/options/linux/include/utmp.h index 3b228c3bc2..887dc86c67 100644 --- a/options/linux/include/utmp.h +++ b/options/linux/include/utmp.h @@ -1,5 +1,5 @@ -#ifndef _UTMP_H -#define _UTMP_H +#ifndef _UTMP_H +#define _UTMP_H #include #include @@ -44,7 +44,7 @@ struct utmp { char ut_user[UT_NAMESIZE]; char ut_host[UT_HOSTSIZE]; struct exit_status ut_exit; - long ut_session; + long ut_session; struct timeval ut_tv; __mlibc_int32 ut_addr_v6[4]; char __unused[20]; diff --git a/options/linux/include/utmpx.h b/options/linux/include/utmpx.h index cfcc9cd8f7..6f6dfaa550 100644 --- a/options/linux/include/utmpx.h +++ b/options/linux/include/utmpx.h @@ -1,6 +1,6 @@ -#ifndef _UTMPX_H -#define _UTMPX_H +#ifndef _UTMPX_H +#define _UTMPX_H #ifdef __cplusplus extern "C" { @@ -43,15 +43,15 @@ void endutxent(void); #endif /* !__MLIBC_ABI_ONLY */ -#define EMPTY 0 -#define RUN_LVL 1 -#define BOOT_TIME 2 -#define NEW_TIME 3 -#define OLD_TIME 4 -#define INIT_PROCESS 5 -#define LOGIN_PROCESS 6 -#define USER_PROCESS 7 -#define DEAD_PROCESS 8 +#define EMPTY 0 +#define RUN_LVL 1 +#define BOOT_TIME 2 +#define NEW_TIME 3 +#define OLD_TIME 4 +#define INIT_PROCESS 5 +#define LOGIN_PROCESS 6 +#define USER_PROCESS 7 +#define DEAD_PROCESS 8 #ifdef _GNU_SOURCE #define ACCOUNTING 9 diff --git a/options/linux/include/values.h b/options/linux/include/values.h index 75a4345b9e..18c66440c9 100644 --- a/options/linux/include/values.h +++ b/options/linux/include/values.h @@ -2,8 +2,8 @@ #ifndef _VALUES_H #define _VALUES_H -#include #include +#include #define CHARBITS (sizeof(char) * 8) #define SHORTBITS (sizeof(short) * 8) @@ -36,4 +36,3 @@ #define BITSPERBYTE CHAR_BIT #endif /* _VALUES_H */ - diff --git a/options/lsb/generic/auxv.cpp b/options/lsb/generic/auxv.cpp index a4d2c8f24c..3809cd3d92 100644 --- a/options/lsb/generic/auxv.cpp +++ b/options/lsb/generic/auxv.cpp @@ -13,17 +13,17 @@ int peekauxval(unsigned long type, unsigned long *out) { aux += *aux + 1; // Skip argc and all arguments __ensure(!*aux); aux++; - while(*aux) // Now, we skip the environment. + while (*aux) // Now, we skip the environment. aux++; aux++; // Parse the auxiliary vector. - while(true) { + while (true) { auto value = aux + 1; - if(*aux == AT_NULL) { + if (*aux == AT_NULL) { errno = ENOENT; return -1; - }else if(*aux == type) { + } else if (*aux == type) { *out = *value; return 0; } @@ -33,7 +33,7 @@ int peekauxval(unsigned long type, unsigned long *out) { unsigned long getauxval(unsigned long type) { unsigned long value = 0; - if(peekauxval(type, &value)) + if (peekauxval(type, &value)) return 0; return value; } @@ -51,7 +51,7 @@ unsigned long getauxval(unsigned long type) { extern "C" unsigned long __getauxval(unsigned long type) { unsigned long value = 0; - if(peekauxval(type, &value)) + if (peekauxval(type, &value)) return 0; return value; } diff --git a/options/lsb/generic/dso_exit.cpp b/options/lsb/generic/dso_exit.cpp index 2372f8b6cc..27385ac254 100644 --- a/options/lsb/generic/dso_exit.cpp +++ b/options/lsb/generic/dso_exit.cpp @@ -50,7 +50,9 @@ extern "C" void __cxa_finalize(void *dso) { // This is referenced by the compiler when generating constructors for global // C++ objects so that it can call __cxa_finalize with a unique argument. -extern "C" { [[gnu::visibility("hidden")]] void *__dso_handle; } +extern "C" { +[[gnu::visibility("hidden")]] void *__dso_handle; +} [[gnu::destructor]] void __mlibc_do_destructors() { // In normal programs this call to __cxa_finalize is provided by libgcc. diff --git a/options/lsb/generic/tls.cpp b/options/lsb/generic/tls.cpp index 76d312b55e..18a2764fc3 100644 --- a/options/lsb/generic/tls.cpp +++ b/options/lsb/generic/tls.cpp @@ -1,23 +1,20 @@ #include -#include #include +#include #if (defined(__riscv) || defined(__m68k__)) && defined(MLIBC_STATIC_BUILD) - // On RISC-V and m68k, linker optimisation is not guaranteed and so we may - // still get calls to this function in statically linked binaries. - // TODO: This will break dlopen calls from statically linked programs. - extern "C" void *__tls_get_addr(struct __abi_tls_entry *entry) { - Tcb *tcbPtr = mlibc::get_current_tcb(); - auto dtvPtr = reinterpret_cast(tcbPtr->dtvPointers[0]); - return reinterpret_cast(dtvPtr + entry->offset + TLS_DTV_OFFSET); - } +// On RISC-V and m68k, linker optimisation is not guaranteed and so we may +// still get calls to this function in statically linked binaries. +// TODO: This will break dlopen calls from statically linked programs. +extern "C" void *__tls_get_addr(struct __abi_tls_entry *entry) { + Tcb *tcbPtr = mlibc::get_current_tcb(); + auto dtvPtr = reinterpret_cast(tcbPtr->dtvPointers[0]); + return reinterpret_cast(dtvPtr + entry->offset + TLS_DTV_OFFSET); +} #elif defined(__i386__) - extern "C" __attribute__((regparm(1))) void *___tls_get_addr(struct __abi_tls_entry *entry) { - return __dlapi_get_tls(entry); - } +extern "C" __attribute__((regparm(1))) void *___tls_get_addr(struct __abi_tls_entry *entry) { + return __dlapi_get_tls(entry); +} #else - extern "C" void *__tls_get_addr(struct __abi_tls_entry *entry) { - return __dlapi_get_tls(entry); - } +extern "C" void *__tls_get_addr(struct __abi_tls_entry *entry) { return __dlapi_get_tls(entry); } #endif - diff --git a/options/posix/generic/arpa-inet.cpp b/options/posix/generic/arpa-inet.cpp index 03fe9555cb..26d9955759 100644 --- a/options/posix/generic/arpa-inet.cpp +++ b/options/posix/generic/arpa-inet.cpp @@ -1,13 +1,13 @@ #include #include -#include #include -#include #include -#include #include #include +#include +#include +#include const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; @@ -46,7 +46,7 @@ uint16_t ntohs(uint16_t x) { // ---------------------------------------------------------------------------- in_addr_t inet_addr(const char *p) { struct in_addr a; - if(!inet_aton(p, &a)) + if (!inet_aton(p, &a)) return -1; return a.s_addr; } @@ -55,9 +55,15 @@ char *inet_ntoa(struct in_addr addr) { // 4 * 3 + 3 + 1 = 12 + 4 = 16 thread_local static char buffer[16]; uint32_t proper = htonl(addr.s_addr); - snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d", - (proper >> 24) & 0xff, ((proper >> 16) & 0xff), - (proper >> 8) & 0xff, proper & 0xff); + snprintf( + buffer, + sizeof(buffer), + "%d.%d.%d.%d", + (proper >> 24) & 0xff, + ((proper >> 16) & 0xff), + (proper >> 8) & 0xff, + proper & 0xff + ); return buffer; } int inet_aton(const char *string, struct in_addr *dest) { @@ -75,28 +81,24 @@ int inet_aton(const char *string, struct in_addr *dest) { } switch (i) { - case 0: - dest->s_addr = htonl(array[0]); - break; - case 1: - if (array[0] > 255 || array[1] > 0xffffff) - return 0; - dest->s_addr = htonl((array[0] << 24) | array[1]); - break; - case 2: - if (array[0] > 255 || array[1] > 255 || - array[2] > 0xffff) - return 0; - dest->s_addr = htonl((array[0] << 24) | (array[1] << 16) | - array[2]); - break; - case 3: - if (array[0] > 255 || array[1] > 255 || - array[2] > 255 || array[3] > 255) - return 0; - dest->s_addr = htonl((array[0] << 24) | (array[1] << 16) | - (array[2] << 8) | array[3]); - break; + case 0: + dest->s_addr = htonl(array[0]); + break; + case 1: + if (array[0] > 255 || array[1] > 0xffffff) + return 0; + dest->s_addr = htonl((array[0] << 24) | array[1]); + break; + case 2: + if (array[0] > 255 || array[1] > 255 || array[2] > 0xffff) + return 0; + dest->s_addr = htonl((array[0] << 24) | (array[1] << 16) | array[2]); + break; + case 3: + if (array[0] > 255 || array[1] > 255 || array[2] > 255 || array[3] > 255) + return 0; + dest->s_addr = htonl((array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3]); + break; } return 1; @@ -105,77 +107,81 @@ int inet_aton(const char *string, struct in_addr *dest) { // ---------------------------------------------------------------------------- // Generic IP address manipulation. // ---------------------------------------------------------------------------- -const char *inet_ntop(int af, const void *__restrict src, char *__restrict dst, - socklen_t size) { +const char *inet_ntop(int af, const void *__restrict src, char *__restrict dst, socklen_t size) { switch (af) { - case AF_INET: { - auto source = reinterpret_cast(src); - uint32_t addr = ntohl(source->s_addr); - if (snprintf(dst, size, "%d.%d.%d.%d", - (addr >> 24) & 0xff, - (addr >> 16) & 0xff, - (addr >> 8) & 0xff, - addr & 0xff) < (int)size) - return dst; - break; - } - case AF_INET6: { - auto source = reinterpret_cast(src); - size_t cur_zeroes_off = 0; - size_t cur_zeroes_len = 0; - size_t max_zeroes_off = 0; - size_t max_zeroes_len = 0; - - /* we look for the largest block of zeroed quartet(s) */ - for(size_t i = 0; i < 8; i++) { - auto ptr = source->s6_addr + (i * 2); - if(!ptr[0] && !ptr[1]) { - cur_zeroes_len++; - if(max_zeroes_len < cur_zeroes_len) { - max_zeroes_len = cur_zeroes_len; - max_zeroes_off = cur_zeroes_off; - } - } else { - /* advance the offset to the next quartet to check */ - cur_zeroes_len = 0; - cur_zeroes_off = i + 1; + case AF_INET: { + auto source = reinterpret_cast(src); + uint32_t addr = ntohl(source->s_addr); + if (snprintf( + dst, + size, + "%d.%d.%d.%d", + (addr >> 24) & 0xff, + (addr >> 16) & 0xff, + (addr >> 8) & 0xff, + addr & 0xff + ) < (int)size) + return dst; + break; + } + case AF_INET6: { + auto source = reinterpret_cast(src); + size_t cur_zeroes_off = 0; + size_t cur_zeroes_len = 0; + size_t max_zeroes_off = 0; + size_t max_zeroes_len = 0; + + /* we look for the largest block of zeroed quartet(s) */ + for (size_t i = 0; i < 8; i++) { + auto ptr = source->s6_addr + (i * 2); + if (!ptr[0] && !ptr[1]) { + cur_zeroes_len++; + if (max_zeroes_len < cur_zeroes_len) { + max_zeroes_len = cur_zeroes_len; + max_zeroes_off = cur_zeroes_off; } + } else { + /* advance the offset to the next quartet to check */ + cur_zeroes_len = 0; + cur_zeroes_off = i + 1; } + } - size_t off = 0; - for(size_t i = 0; i < 8; i++) { - auto ptr = source->s6_addr + (i * 2); - - /* if we are at the beginning of the largest block of zeroed quartets, place "::" */ - if(i == max_zeroes_off && max_zeroes_len >= 2) { - if(off < size) { - dst[off++] = ':'; - } - if(off < size) { - dst[off++] = ':'; - } - i += max_zeroes_len - 1; - - continue; - } + size_t off = 0; + for (size_t i = 0; i < 8; i++) { + auto ptr = source->s6_addr + (i * 2); - /* place a colon if we're not at the beginning of the string and it is not already there */ - if(off && dst[off - 1] != ':') { - if(off < size) { - dst[off++] = ':'; - } + /* if we are at the beginning of the largest block of zeroed quartets, place "::" */ + if (i == max_zeroes_off && max_zeroes_len >= 2) { + if (off < size) { + dst[off++] = ':'; + } + if (off < size) { + dst[off++] = ':'; } + i += max_zeroes_len - 1; - off += snprintf(dst + off, size - off, "%x", ptr[0] << 8 | ptr[1]); + continue; } - dst[off] = 0; + /* place a colon if we're not at the beginning of the string and it is not already there + */ + if (off && dst[off - 1] != ':') { + if (off < size) { + dst[off++] = ':'; + } + } - return dst; + off += snprintf(dst + off, size - off, "%x", ptr[0] << 8 | ptr[1]); } - default: - errno = EAFNOSUPPORT; - return NULL; + + dst[off] = 0; + + return dst; + } + default: + errno = EAFNOSUPPORT; + return NULL; } errno = ENOSPC; @@ -183,29 +189,29 @@ const char *inet_ntop(int af, const void *__restrict src, char *__restrict dst, } int inet_pton(int af, const char *__restrict src, void *__restrict dst) { switch (af) { - case AF_INET: { - uint8_t array[4] = {}; - for (int i = 0; i < 4; i++) { - char *end; - long int value = strtol(src, &end, 10); - if (value > 255) - return 0; - if (*end != '\0' && *end != '.') - return 0; - src = end + 1; - array[i] = value; - } - auto addr = reinterpret_cast(dst); - uint32_t ip = (array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3]; - addr->s_addr = htonl(ip); - break; + case AF_INET: { + uint8_t array[4] = {}; + for (int i = 0; i < 4; i++) { + char *end; + long int value = strtol(src, &end, 10); + if (value > 255) + return 0; + if (*end != '\0' && *end != '.') + return 0; + src = end + 1; + array[i] = value; } - case AF_INET6: - mlibc::infoLogger() << "inet_pton: ipv6 is not implemented!" << frg::endlog; - /* fallthrough */ - default: - errno = EAFNOSUPPORT; - return -1; + auto addr = reinterpret_cast(dst); + uint32_t ip = (array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3]; + addr->s_addr = htonl(ip); + break; + } + case AF_INET6: + mlibc::infoLogger() << "inet_pton: ipv6 is not implemented!" << frg::endlog; + /* fallthrough */ + default: + errno = EAFNOSUPPORT; + return -1; } return 1; diff --git a/options/posix/generic/dirent.cpp b/options/posix/generic/dirent.cpp index 1163d805e7..3872fac04b 100644 --- a/options/posix/generic/dirent.cpp +++ b/options/posix/generic/dirent.cpp @@ -1,16 +1,16 @@ -#include #include +#include #include -#include -#include #include +#include +#include #include #include #include -#include #include +#include // Code taken from musl int alphasort(const struct dirent **a, const struct dirent **b) { @@ -22,21 +22,19 @@ int closedir(DIR *dir) { close(dir->__handle); return 0; } -int dirfd(DIR *dir) { - return dir->__handle; -} +int dirfd(DIR *dir) { return dir->__handle; } DIR *fdopendir(int fd) { struct stat st; - if(fstat(fd, &st) < 0) { + if (fstat(fd, &st) < 0) { return nullptr; } // Musl implements this, but O_PATH is only declared on the linux abi /*if(fcntl(fd, F_GETFL) & O_PATH) { - errno = EBADF; - return nullptr; + errno = EBADF; + return nullptr; }*/ - if(!S_ISDIR(st.st_mode)) { + if (!S_ISDIR(st.st_mode)) { errno = ENOTDIR; return nullptr; } @@ -56,23 +54,25 @@ DIR *opendir(const char *path) { dir->__ent_limit = 0; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_open_dir, nullptr); - if(int e = mlibc::sys_open_dir(path, &dir->__handle); e) { + if (int e = mlibc::sys_open_dir(path, &dir->__handle); e) { errno = e; frg::destruct(getAllocator(), dir); return nullptr; - }else{ + } else { return dir; } } struct dirent *readdir(DIR *dir) { __ensure(dir->__ent_next <= dir->__ent_limit); - if(dir->__ent_next == dir->__ent_limit) { + if (dir->__ent_next == dir->__ent_limit) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_read_entries, nullptr); - if(int e = mlibc::sys_read_entries(dir->__handle, dir->__ent_buffer, 2048, &dir->__ent_limit); e) + if (int e = + mlibc::sys_read_entries(dir->__handle, dir->__ent_buffer, 2048, &dir->__ent_limit); + e) __ensure(!"mlibc::sys_read_entries() failed"); dir->__ent_next = 0; - if(!dir->__ent_limit) + if (!dir->__ent_limit) return nullptr; } @@ -86,17 +86,19 @@ struct dirent *readdir(DIR *dir) { [[gnu::alias("readdir")]] struct dirent64 *readdir64(DIR *dir); int readdir_r(DIR *dir, struct dirent *entry, struct dirent **result) { - if(!mlibc::sys_read_entries) { + if (!mlibc::sys_read_entries) { MLIBC_MISSING_SYSDEP(); return ENOSYS; } __ensure(dir->__ent_next <= dir->__ent_limit); - if(dir->__ent_next == dir->__ent_limit) { - if(int e = mlibc::sys_read_entries(dir->__handle, dir->__ent_buffer, 2048, &dir->__ent_limit); e) + if (dir->__ent_next == dir->__ent_limit) { + if (int e = + mlibc::sys_read_entries(dir->__handle, dir->__ent_buffer, 2048, &dir->__ent_limit); + e) __ensure(!"mlibc::sys_read_entries() failed"); dir->__ent_next = 0; - if(!dir->__ent_limit) { + if (!dir->__ent_limit) { *result = NULL; return 0; } @@ -115,8 +117,12 @@ void rewinddir(DIR *dir) { dir->__ent_next = 0; } -int scandir(const char *path, struct dirent ***res, int (*select)(const struct dirent *), - int (*compare)(const struct dirent **, const struct dirent **)) { +int scandir( + const char *path, + struct dirent ***res, + int (*select)(const struct dirent *), + int (*compare)(const struct dirent **, const struct dirent **) +) { DIR *dir = opendir(path); if (!dir) return -1; // errno will be set by opendir() @@ -129,33 +135,32 @@ int scandir(const char *path, struct dirent ***res, int (*select)(const struct d struct dirent **array = nullptr, **tmp = nullptr; int length = 0; int count = 0; - while((dir_ent = readdir(dir)) && !errno) { - if(select && !select(dir_ent)) + while ((dir_ent = readdir(dir)) && !errno) { + if (select && !select(dir_ent)) continue; - if(count >= length) { - length = 2*length + 1; - tmp = static_cast(realloc(array, - length * sizeof(struct dirent*))); + if (count >= length) { + length = 2 * length + 1; + tmp = static_cast(realloc(array, length * sizeof(struct dirent *))); // we need to check the call actually goes through // before we overwrite array so that we can // deallocate the already written entries should realloc() // have failed - if(!tmp) + if (!tmp) break; array = tmp; } - array[count] = static_cast(malloc(dir_ent->d_reclen)); - if(!array[count]) + array[count] = static_cast(malloc(dir_ent->d_reclen)); + if (!array[count]) break; memcpy(array[count], dir_ent, dir_ent->d_reclen); count++; } - if(errno) { - if(array) - while(count-- > 0) + if (errno) { + if (array) + while (count-- > 0) free(array[count]); free(array); return -1; @@ -164,9 +169,8 @@ int scandir(const char *path, struct dirent ***res, int (*select)(const struct d // from here we can set the old errno back errno = old_errno; - if(compare) - qsort(array, count, sizeof(struct dirent*), - (int (*)(const void *, const void *)) compare); + if (compare) + qsort(array, count, sizeof(struct dirent *), (int (*)(const void *, const void *))compare); *res = array; return count; } diff --git a/options/posix/generic/dlfcn.cpp b/options/posix/generic/dlfcn.cpp index fc34a3b985..8066c7c3c9 100644 --- a/options/posix/generic/dlfcn.cpp +++ b/options/posix/generic/dlfcn.cpp @@ -19,13 +19,9 @@ extern "C" void *__dlapi_resolve(void *, const char *, void *); extern "C" int __dlapi_reverse(const void *, __dlapi_symbol *); extern "C" int __dlapi_close(void *); -int dlclose(void *handle) { - return __dlapi_close(handle); -} +int dlclose(void *handle) { return __dlapi_close(handle); } -char *dlerror(void) { - return const_cast(__dlapi_error()); -} +char *dlerror(void) { return const_cast(__dlapi_error()); } [[gnu::noinline]] void *dlopen(const char *file, int flags) { @@ -40,19 +36,20 @@ void *dlsym(void *__restrict handle, const char *__restrict string) { } [[gnu::noinline]] -void *dlvsym(void *__restrict handle, const char *__restrict string, const char *__restrict version) { +void * +dlvsym(void *__restrict handle, const char *__restrict string, const char *__restrict version) { mlibc::infoLogger() << "mlibc: dlvsym ignores version " << version << frg::endlog; auto ra = __builtin_extract_return_addr(__builtin_return_address(0)); return __dlapi_resolve(handle, string, ra); } -//gnu extensions +// gnu extensions #if __MLIBC_GLIBC_OPTION int dladdr(const void *ptr, Dl_info *out) { __dlapi_symbol info; - if(__dlapi_reverse(ptr, &info)) + if (__dlapi_reverse(ptr, &info)) return 0; out->dli_fname = info.file; @@ -64,7 +61,7 @@ int dladdr(const void *ptr, Dl_info *out) { int dladdr1(const void *ptr, Dl_info *out, void **extra, int flags) { __dlapi_symbol info; - if(__dlapi_reverse(ptr, &info)) { + if (__dlapi_reverse(ptr, &info)) { return 0; } @@ -73,7 +70,7 @@ int dladdr1(const void *ptr, Dl_info *out, void **extra, int flags) { out->dli_sname = info.symbol; out->dli_saddr = info.address; - switch(flags) { + switch (flags) { case RTLD_DL_SYMENT: *const_cast(extra) = info.elf_symbol; break; diff --git a/options/posix/generic/fcntl.cpp b/options/posix/generic/fcntl.cpp index c05d51b59d..f506243cd9 100644 --- a/options/posix/generic/fcntl.cpp +++ b/options/posix/generic/fcntl.cpp @@ -1,6 +1,6 @@ -#include #include +#include #include #include @@ -8,7 +8,7 @@ #include int creat(const char *pathname, mode_t mode) { - return open(pathname, O_CREAT|O_WRONLY|O_TRUNC, mode); + return open(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode); } int fallocate(int, int, off_t, off_t) { @@ -22,7 +22,7 @@ int fcntl(int fd, int command, ...) { va_start(args, command); int result; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fcntl, -1); - if(int e = mlibc::sys_fcntl(fd, command, args, &result); e) { + if (int e = mlibc::sys_fcntl(fd, command, args, &result); e) { errno = e; return -1; } @@ -36,11 +36,11 @@ int openat(int dirfd, const char *pathname, int flags, ...) { mode_t mode = 0; int fd; - if((flags & (O_CREAT | O_TMPFILE))) + if ((flags & (O_CREAT | O_TMPFILE))) mode = va_arg(args, mode_t); MLIBC_CHECK_OR_ENOSYS(mlibc::sys_openat, -1); - if(int e = mlibc::sys_openat(dirfd, pathname, flags, mode, &fd); e) { + if (int e = mlibc::sys_openat(dirfd, pathname, flags, mode, &fd); e) { errno = e; return -1; } @@ -49,7 +49,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) { } int posix_fadvise(int fd, off_t offset, off_t length, int advice) { - if(!mlibc::sys_fadvise) { + if (!mlibc::sys_fadvise) { mlibc::infoLogger() << "mlibc: fadvise() ignored due to missing sysdep" << frg::endlog; return 0; } @@ -60,7 +60,7 @@ int posix_fadvise(int fd, off_t offset, off_t length, int advice) { int posix_fallocate(int fd, off_t offset, off_t size) { // posix_fallocate() returns an error instead of setting errno. - if(!mlibc::sys_fallocate) { + if (!mlibc::sys_fallocate) { MLIBC_MISSING_SYSDEP(); return ENOSYS; } @@ -99,11 +99,11 @@ int open(const char *pathname, int flags, ...) { } int fd; - if(int e = mlibc::sys_open(pathname, flags, mode, &fd); e) { + if (int e = mlibc::sys_open(pathname, flags, mode, &fd); e) { errno = e; return -1; } return fd; } -[[gnu::alias("open")]] int open64(const char *pathname, int flags, ...); \ No newline at end of file +[[gnu::alias("open")]] int open64(const char *pathname, int flags, ...); diff --git a/options/posix/generic/ftw.cpp b/options/posix/generic/ftw.cpp index 2d939954c9..d9420014e6 100644 --- a/options/posix/generic/ftw.cpp +++ b/options/posix/generic/ftw.cpp @@ -9,10 +9,8 @@ int ftw(const char *, int (*fn)(const char *, const struct stat *, int), int) { __builtin_unreachable(); } -int nftw(const char *, int (*fn)(const char *, const struct stat *, int, struct FTW *), - int, int) { +int nftw(const char *, int (*fn)(const char *, const struct stat *, int, struct FTW *), int, int) { (void)fn; __ensure(!"nftw() not implemented"); __builtin_unreachable(); } - diff --git a/options/posix/generic/grp.cpp b/options/posix/generic/grp.cpp index 5175ab6288..17c660c9d8 100644 --- a/options/posix/generic/grp.cpp +++ b/options/posix/generic/grp.cpp @@ -1,209 +1,203 @@ -#include +#include #include +#include #include #include #include -#include #include #include namespace { - FILE *global_file; - - bool open_global_file() { - if(!global_file) { - global_file = fopen("/etc/group", "r"); - if(!global_file) { - errno = EIO; - return false; - } +FILE *global_file; + +bool open_global_file() { + if (!global_file) { + global_file = fopen("/etc/group", "r"); + if (!global_file) { + errno = EIO; + return false; } + } + + return true; +} - return true; +void close_global_file() { + if (global_file) { + fclose(global_file); + global_file = nullptr; } +} - void close_global_file() { - if(global_file) { - fclose(global_file); - global_file = nullptr; - } +template void walk_segments(frg::string_view line, char delimiter, F fn) { + size_t s = 0; + while (true) { + size_t d = line.find_first(delimiter, s); + if (d == size_t(-1)) + break; + auto chunk = line.sub_string(s, d - s); + fn(chunk); + s = d + 1; } + if (line[s]) { + auto chunk = line.sub_string(s, line.size() - s); + + if (chunk.size() > 0) { + // Remove trailing newline + if (chunk[chunk.size() - 1] == '\n') + chunk = chunk.sub_string(0, chunk.size() - 1); - template - void walk_segments(frg::string_view line, char delimiter, F fn) { - size_t s = 0; - while(true) { - size_t d = line.find_first(delimiter, s); - if(d == size_t(-1)) - break; - auto chunk = line.sub_string(s, d - s); fn(chunk); - s = d + 1; } - if(line[s]) { - auto chunk = line.sub_string(s, line.size() - s); + } +} - if (chunk.size() > 0) { - // Remove trailing newline - if (chunk[chunk.size() - 1] == '\n') - chunk = chunk.sub_string(0, chunk.size() - 1); +bool extract_entry(frg::string_view line, group *entry) { + frg::string_view segments[5]; - fn(chunk); - } - } - } + // Parse the line into 3 or 4 segments (depending if the group has members or not) + int n = 0; + walk_segments(line, ':', [&](frg::string_view s) { + __ensure(n < 4); + segments[n++] = s; + }); - bool extract_entry(frg::string_view line, group *entry) { - frg::string_view segments[5]; + if (n < 3) // n can be 3 when there are no members in the group + return false; - // Parse the line into 3 or 4 segments (depending if the group has members or not) - int n = 0; - walk_segments(line, ':', [&] (frg::string_view s) { - __ensure(n < 4); - segments[n++] = s; - }); + // TODO: Handle strndup() and malloc() failure. + auto name = strndup(segments[0].data(), segments[0].size()); + __ensure(name); - if(n < 3) // n can be 3 when there are no members in the group - return false; + auto passwd = strndup(segments[1].data(), segments[1].size()); - // TODO: Handle strndup() and malloc() failure. - auto name = strndup(segments[0].data(), segments[0].size()); - __ensure(name); + auto gid = segments[2].to_number(); + if (!gid) + return false; - auto passwd = strndup(segments[1].data(), segments[1].size()); + size_t n_members = 0; + walk_segments(segments[3], ',', [&](frg::string_view) { n_members++; }); - auto gid = segments[2].to_number(); - if(!gid) - return false; + auto members = reinterpret_cast(malloc(sizeof(char *) * (n_members + 1))); + __ensure(members); + size_t k = 0; + walk_segments(segments[3], ',', [&](frg::string_view m) { + members[k] = strndup(m.data(), m.size()); + __ensure(members[k]); + k++; + }); + members[k] = nullptr; - size_t n_members = 0; - walk_segments(segments[3], ',', [&] (frg::string_view) { - n_members++; - }); - - auto members = reinterpret_cast(malloc(sizeof(char *) * (n_members + 1))); - __ensure(members); - size_t k = 0; - walk_segments(segments[3], ',', [&] (frg::string_view m) { - members[k] = strndup(m.data(), m.size()); - __ensure(members[k]); - k++; - }); - members[k] = nullptr; - - entry->gr_name = name; - entry->gr_passwd = passwd; - entry->gr_gid = *gid; - entry->gr_mem = members; - return true; + entry->gr_name = name; + entry->gr_passwd = passwd; + entry->gr_gid = *gid; + entry->gr_mem = members; + return true; +} + +void clear_entry(group *entry) { + free(entry->gr_name); + if (entry->gr_mem) { + for (size_t i = 0; entry->gr_mem[i]; i++) + free(entry->gr_mem[i]); + free(entry->gr_mem); } + entry->gr_name = nullptr; + entry->gr_mem = nullptr; +} - void clear_entry(group *entry) { - free(entry->gr_name); - if(entry->gr_mem) { - for(size_t i = 0; entry->gr_mem[i]; i++) - free(entry->gr_mem[i]); - free(entry->gr_mem); - } - entry->gr_name = nullptr; - entry->gr_mem = nullptr; +template int walk_file(struct group *entry, C cond) { + auto file = fopen("/etc/group", "r"); + if (!file) { + return EIO; } - template - int walk_file(struct group *entry, C cond) { - auto file = fopen("/etc/group", "r"); - if(!file) { - return EIO; + char line[512]; + while (fgets(line, 512, file)) { + if (!extract_entry(line, entry)) + continue; + if (cond(entry)) { + fclose(file); + return 0; } + } - char line[512]; - while(fgets(line, 512, file)) { - if(!extract_entry(line, entry)) - continue; - if(cond(entry)) { - fclose(file); - return 0; - } - } + int err = ESRCH; + if (ferror(file)) { + err = EIO; + } - int err = ESRCH; - if(ferror(file)) { - err = EIO; - } + fclose(file); + return err; +} - fclose(file); - return err; +int copy_to_buffer(struct group *grp, char *buffer, size_t size) { + // Adjust to correct alignment so that we can put gr_mem first in buffer + uintptr_t mask = sizeof(char *) - 1; + size_t offset = (reinterpret_cast(buffer) % sizeof(char *) + mask) & ~mask; + if (size < offset) + return ERANGE; + + buffer += offset; + size -= offset; + + // Calculate the amount of space we need + size_t nmemb, required_size = 0; + for (nmemb = 0; grp->gr_mem[nmemb] != nullptr; nmemb++) { + // One for the string's null terminator and one for the pointer in gr_mem + required_size += strlen(grp->gr_mem[nmemb]) + 1 + sizeof(char *); } - int copy_to_buffer(struct group *grp, char *buffer, size_t size) { - // Adjust to correct alignment so that we can put gr_mem first in buffer - uintptr_t mask = sizeof(char *) - 1; - size_t offset = (reinterpret_cast(buffer) % sizeof(char *) + mask) & ~mask; - if (size < offset) - return ERANGE; - - buffer += offset; - size -= offset; - - // Calculate the amount of space we need - size_t nmemb, required_size = 0; - for (nmemb = 0; grp->gr_mem[nmemb] != nullptr; nmemb++) { - // One for the string's null terminator and one for the pointer in gr_mem - required_size += strlen(grp->gr_mem[nmemb]) + 1 + sizeof(char *); - } - - // One for null terminator of gr_name, plus sizeof(char *) for nullptr terminator of gr_mem - required_size += strlen(grp->gr_name) + 1 + sizeof(char *); - if (size < required_size) - return ERANGE; + // One for null terminator of gr_name, plus sizeof(char *) for nullptr terminator of gr_mem + required_size += strlen(grp->gr_name) + 1 + sizeof(char *); + if (size < required_size) + return ERANGE; - // Put the gr_mem array first in the buffer as we are guaranteed - // that the pointer is aligned correctly - char *string_data = buffer + (nmemb + 1) * sizeof(char *); + // Put the gr_mem array first in the buffer as we are guaranteed + // that the pointer is aligned correctly + char *string_data = buffer + (nmemb + 1) * sizeof(char *); - for (size_t i = 0; i < nmemb; i++) { - reinterpret_cast(buffer)[i] = string_data; - string_data = stpcpy(string_data, grp->gr_mem[i]) + 1; - free(grp->gr_mem[i]); - } + for (size_t i = 0; i < nmemb; i++) { + reinterpret_cast(buffer)[i] = string_data; + string_data = stpcpy(string_data, grp->gr_mem[i]) + 1; + free(grp->gr_mem[i]); + } - reinterpret_cast(buffer)[nmemb] = nullptr; - free(grp->gr_mem); - grp->gr_mem = reinterpret_cast(buffer); + reinterpret_cast(buffer)[nmemb] = nullptr; + free(grp->gr_mem); + grp->gr_mem = reinterpret_cast(buffer); - char *gr_name = stpcpy(string_data, grp->gr_name) + 1; - free(grp->gr_name); - grp->gr_name = string_data; + char *gr_name = stpcpy(string_data, grp->gr_name) + 1; + free(grp->gr_name); + grp->gr_name = string_data; - __ensure(gr_name <= buffer + size); - return 0; - } + __ensure(gr_name <= buffer + size); + return 0; } +} // namespace -void endgrent(void) { - close_global_file(); -} +void endgrent(void) { close_global_file(); } struct group *getgrent(void) { static group entry; char line[512]; - if(!open_global_file()) { + if (!open_global_file()) { return nullptr; } - if(fgets(line, 512, global_file)) { + if (fgets(line, 512, global_file)) { clear_entry(&entry); - if(!extract_entry(line, &entry)) { + if (!extract_entry(line, &entry)) { errno = EINVAL; return nullptr; } return &entry; } - if(ferror(global_file)) { + if (ferror(global_file)) { errno = EIO; } @@ -213,9 +207,7 @@ struct group *getgrent(void) { struct group *getgrgid(gid_t gid) { static group entry; - int err = walk_file(&entry, [&] (group *entry) { - return entry->gr_gid == gid; - }); + int err = walk_file(&entry, [&](group *entry) { return entry->gr_gid == gid; }); if (err) { errno = err; @@ -227,9 +219,7 @@ struct group *getgrgid(gid_t gid) { int getgrgid_r(gid_t gid, struct group *grp, char *buffer, size_t size, struct group **result) { *result = nullptr; - int err = walk_file(grp, [&] (group *entry) { - return entry->gr_gid == gid; - }); + int err = walk_file(grp, [&](group *entry) { return entry->gr_gid == gid; }); if (err) { return err; @@ -247,9 +237,7 @@ int getgrgid_r(gid_t gid, struct group *grp, char *buffer, size_t size, struct g struct group *getgrnam(const char *name) { static group entry; - int err = walk_file(&entry, [&] (group *entry) { - return !strcmp(entry->gr_name, name); - }); + int err = walk_file(&entry, [&](group *entry) { return !strcmp(entry->gr_name, name); }); if (err) { errno = err; @@ -259,12 +247,11 @@ struct group *getgrnam(const char *name) { return &entry; } -int getgrnam_r(const char *name, struct group *grp, char *buffer, size_t size, struct group **result) { +int +getgrnam_r(const char *name, struct group *grp, char *buffer, size_t size, struct group **result) { *result = nullptr; - int err = walk_file(grp, [&] (group *entry) { - return !strcmp(entry->gr_name, name); - }); + int err = walk_file(grp, [&](group *entry) { return !strcmp(entry->gr_name, name); }); if (err) { return err; @@ -280,7 +267,7 @@ int getgrnam_r(const char *name, struct group *grp, char *buffer, size_t size, s } void setgrent(void) { - if(!open_global_file()) { + if (!open_global_file()) { return; } rewind(global_file); @@ -288,7 +275,7 @@ void setgrent(void) { int setgroups(size_t size, const gid_t *list) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setgroups, -1); - if(int e = mlibc::sys_setgroups(size, list); e) { + if (int e = mlibc::sys_setgroups(size, list); e) { errno = e; return -1; } @@ -301,16 +288,14 @@ int initgroups(const char *, gid_t) { } int putgrent(const struct group *g, FILE *f) { - auto invalid = [](const char *s) { - return s == nullptr || strchr(s, '\n') || strchr(s, ':'); - }; + auto invalid = [](const char *s) { return s == nullptr || strchr(s, '\n') || strchr(s, ':'); }; - if(g == nullptr || invalid(g->gr_name) || invalid(g->gr_passwd)) { + if (g == nullptr || invalid(g->gr_name) || invalid(g->gr_passwd)) { errno = EINVAL; return -1; } - for(int i = 0; g->gr_mem != nullptr && g->gr_mem[i] != nullptr; ++i) { + for (int i = 0; g->gr_mem != nullptr && g->gr_mem[i] != nullptr; ++i) { if (invalid(g->gr_mem[i])) { errno = EINVAL; return -1; @@ -321,12 +306,12 @@ int putgrent(const struct group *g, FILE *f) { flockfile(f); int r = fprintf(f, "%s:%s:%u:", g->gr_name, g->gr_passwd, g->gr_gid); - if(r < 0) + if (r < 0) goto leave; - for(int i = 0; g->gr_mem != nullptr && g->gr_mem[i] != nullptr; ++i) { + for (int i = 0; g->gr_mem != nullptr && g->gr_mem[i] != nullptr; ++i) { r = fprintf(f, "%s%s", i ? "," : "", g->gr_mem[i]); - if(r < 0) + if (r < 0) goto leave; } @@ -347,20 +332,21 @@ int getgrouplist(const char *user, gid_t gid, gid_t *groups, int *ngroups) { int n_limit = *ngroups; struct group grp; - if(n_limit >= 1) + if (n_limit >= 1) *groups++ = gid; - int err = walk_file(&grp, [&] (group *entry) { + int err = walk_file(&grp, [&](group *entry) { size_t i = 0; - for(; entry->gr_mem[i] && strcmp(user, entry->gr_mem[i]); i++); - if(!entry->gr_mem[i]) + for (; entry->gr_mem[i] && strcmp(user, entry->gr_mem[i]); i++) + ; + if (!entry->gr_mem[i]) return false; - if(++n <= n_limit) + if (++n <= n_limit) *groups++ = entry->gr_gid; return false; }); - if(err != ESRCH) { + if (err != ESRCH) { errno = err; return -1; } diff --git a/options/posix/generic/langinfo.cpp b/options/posix/generic/langinfo.cpp index b239cbdc14..a73d39c93b 100644 --- a/options/posix/generic/langinfo.cpp +++ b/options/posix/generic/langinfo.cpp @@ -1,15 +1,12 @@ -#include #include +#include #include #include -char *nl_langinfo(nl_item item) { - return mlibc::nl_langinfo(item); -} +char *nl_langinfo(nl_item item) { return mlibc::nl_langinfo(item); } char *nl_langinfo_l(nl_item, locale_t) { __ensure(!"Not implemented"); __builtin_unreachable(); } - diff --git a/options/posix/generic/libgen.cpp b/options/posix/generic/libgen.cpp index ff80349a99..cc2c2f7948 100644 --- a/options/posix/generic/libgen.cpp +++ b/options/posix/generic/libgen.cpp @@ -10,15 +10,15 @@ char *basename(char *s) { // This empty string behavior is specified by POSIX. if (!s || !*s) return const_cast("."); - + // Delete trailing slashes. // Note that we do not delete the slash at index zero. auto i = strlen(s) - 1; - for(; i && s[i] == '/'; i--) + for (; i && s[i] == '/'; i--) s[i] = 0; // Find the last non-trailing slash. - for(; i && s[i - 1] != '/'; i--) + for (; i && s[i - 1] != '/'; i--) ; return s + i; } @@ -31,21 +31,20 @@ char *dirname(char *s) { // Skip trailing slashes. for (; s[i] == '/'; i--) - if(!i) // Path only consists of slashes. + if (!i) // Path only consists of slashes. return const_cast("/"); // Skip the last non-slash path component. for (; s[i] != '/'; i--) - if(!i) // Path only contains a single component. + if (!i) // Path only contains a single component. return const_cast("."); // Skip slashes. for (; s[i] == '/'; i--) - if(!i) // Path is entry in root directory. + if (!i) // Path is entry in root directory. return const_cast("/"); - s[i+1] = 0; + s[i + 1] = 0; return s; } - diff --git a/options/posix/generic/lookup.cpp b/options/posix/generic/lookup.cpp index cc98c353de..77b51cd021 100644 --- a/options/posix/generic/lookup.cpp +++ b/options/posix/generic/lookup.cpp @@ -1,24 +1,24 @@ +#include +#include #include #include -#include -#include +#include +#include +#include #include #include +#include #include -#include -#include #include -#include -#include namespace mlibc { namespace { - constexpr unsigned int RECORD_A = 1; - constexpr unsigned int RECORD_CNAME = 5; - constexpr unsigned int RECORD_PTR = 12; -} +constexpr unsigned int RECORD_A = 1; +constexpr unsigned int RECORD_CNAME = 5; +constexpr unsigned int RECORD_PTR = 12; +} // namespace static frg::string read_dns_name(char *buf, char *&it) { frg::string res{getAllocator()}; @@ -46,8 +46,9 @@ static frg::string read_dns_name(char *buf, char *&it) { return res; } -int lookup_name_dns(struct lookup_result &buf, const char *name, - frg::string &canon_name) { +int lookup_name_dns( + struct lookup_result &buf, const char *name, frg::string &canon_name +) { frg::string request{getAllocator()}; int num_q = 1; @@ -98,10 +99,11 @@ int lookup_name_dns(struct lookup_result &buf, const char *name, return -EAI_SYSTEM; } - size_t sent = sendto(fd, request.data(), request.size(), 0, - (struct sockaddr*)&sin, sizeof(sin)); + size_t sent = + sendto(fd, request.data(), request.size(), 0, (struct sockaddr *)&sin, sizeof(sin)); if (sent != request.size()) { - mlibc::infoLogger() << "lookup_name_dns(): sendto() failed to send everything" << frg::endlog; + mlibc::infoLogger() << "lookup_name_dns(): sendto() failed to send everything" + << frg::endlog; return -EAI_SYSTEM; } @@ -111,14 +113,14 @@ int lookup_name_dns(struct lookup_result &buf, const char *name, while ((rlen = recvfrom(fd, response, 256, 0, NULL, NULL)) >= 0) { if ((size_t)rlen < sizeof(struct dns_header)) continue; - auto response_header = reinterpret_cast(response); + auto response_header = reinterpret_cast(response); if (response_header->identification != header.identification) return -EAI_FAIL; auto it = response + sizeof(struct dns_header); for (int i = 0; i < ntohs(response_header->no_q); i++) { auto dns_name = read_dns_name(response, it); - (void) dns_name; + (void)dns_name; it += 4; } @@ -133,21 +135,21 @@ int lookup_name_dns(struct lookup_result &buf, const char *name, (void)rr_class; switch (rr_type) { - case RECORD_A: - memcpy(buffer.addr, it, rr_length); - it += rr_length; - buffer.family = AF_INET; - buffer.name = std::move(dns_name); - buf.buf.push(std::move(buffer)); - break; - case RECORD_CNAME: - canon_name = read_dns_name(response, it); - buf.aliases.push(std::move(dns_name)); - break; - default: - mlibc::infoLogger() << "lookup_name_dns: unknown rr type " - << rr_type << frg::endlog; - break; + case RECORD_A: + memcpy(buffer.addr, it, rr_length); + it += rr_length; + buffer.family = AF_INET; + buffer.name = std::move(dns_name); + buf.buf.push(std::move(buffer)); + break; + case RECORD_CNAME: + canon_name = read_dns_name(response, it); + buf.aliases.push(std::move(dns_name)); + break; + default: + mlibc::infoLogger() + << "lookup_name_dns: unknown rr type " << rr_type << frg::endlog; + break; } } num_ans += ntohs(response_header->no_ans); @@ -176,14 +178,14 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam memcpy(request.data(), &header, sizeof(header)); char addr_str[64]; - if(!inet_ntop(family, addr.data(), addr_str, sizeof(addr_str))) { - switch(errno) { - case EAFNOSUPPORT: - return -EAI_FAMILY; - case ENOSPC: - return -EAI_OVERFLOW; - default: - return -EAI_FAIL; + if (!inet_ntop(family, addr.data(), addr_str, sizeof(addr_str))) { + switch (errno) { + case EAFNOSUPPORT: + return -EAI_FAMILY; + case ENOSPC: + return -EAI_OVERFLOW; + default: + return -EAI_FAIL; } } frg::string req_str{getAllocator(), addr_str}; @@ -198,7 +200,7 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam request += char(length); request += substring; ptr = next + 1; - } while(ptr != 0); + } while (ptr != 0); request += char(0); // set question type to fetch PTR records @@ -208,7 +210,6 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam request += 0; request += 1; - struct sockaddr_in sin = {}; sin.sin_family = AF_INET; // TODO(geert): we could probably make this use the service lookup @@ -227,10 +228,11 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam return -EAI_SYSTEM; } - size_t sent = sendto(fd, request.data(), request.size(), 0, - (struct sockaddr*)&sin, sizeof(sin)); + size_t sent = + sendto(fd, request.data(), request.size(), 0, (struct sockaddr *)&sin, sizeof(sin)); if (sent != request.size()) { - mlibc::infoLogger() << "lookup_name_dns(): sendto() failed to send everything" << frg::endlog; + mlibc::infoLogger() << "lookup_name_dns(): sendto() failed to send everything" + << frg::endlog; return -EAI_SYSTEM; } @@ -240,14 +242,14 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam while ((rlen = recvfrom(fd, response, 256, 0, NULL, NULL)) >= 0) { if ((size_t)rlen < sizeof(struct dns_header)) continue; - auto response_header = reinterpret_cast(response); + auto response_header = reinterpret_cast(response); if (response_header->identification != header.identification) return -EAI_FAIL; auto it = response + sizeof(struct dns_header); for (int i = 0; i < ntohs(response_header->no_q); i++) { auto dns_name = read_dns_name(response, it); - (void) dns_name; + (void)dns_name; it += 4; } @@ -265,18 +267,18 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam (void)dns_name; switch (rr_type) { - case RECORD_PTR: { - auto ptr_name = read_dns_name(response, it); - if (ptr_name.size() >= name.size()) - return -EAI_OVERFLOW; - std::copy(ptr_name.begin(), ptr_name.end(), name.data()); - name.data()[ptr_name.size()] = '\0'; - return 1; - } - default: - mlibc::infoLogger() << "lookup_addr_dns: unknown rr type " - << rr_type << frg::endlog; - break; + case RECORD_PTR: { + auto ptr_name = read_dns_name(response, it); + if (ptr_name.size() >= name.size()) + return -EAI_OVERFLOW; + std::copy(ptr_name.begin(), ptr_name.end(), name.data()); + name.data()[ptr_name.size()] = '\0'; + return 1; + } + default: + mlibc::infoLogger() + << "lookup_addr_dns: unknown rr type " << rr_type << frg::endlog; + break; } num_ans += ntohs(response_header->no_ans); @@ -289,17 +291,18 @@ int lookup_addr_dns(frg::span name, frg::array &addr, int fam return 0; } -int lookup_name_hosts(struct lookup_result &buf, const char *name, - frg::string &canon_name) { +int lookup_name_hosts( + struct lookup_result &buf, const char *name, frg::string &canon_name +) { auto file = fopen("/etc/hosts", "r"); if (!file) { switch (errno) { - case ENOENT: - case ENOTDIR: - case EACCES: - return -EAI_SERVICE; - default: - return -EAI_SYSTEM; + case ENOENT: + case ENOTDIR: + case EACCES: + return -EAI_SERVICE; + default: + return -EAI_SYSTEM; } } @@ -313,12 +316,15 @@ int lookup_name_hosts(struct lookup_result &buf, const char *name, *pos = '\0'; } - for(pos = line + 1; (pos = strstr(pos, name)) && - (!isspace(pos[-1]) || !isspace(pos[name_length])); pos++); + for (pos = line + 1; + (pos = strstr(pos, name)) && (!isspace(pos[-1]) || !isspace(pos[name_length])); + pos++) + ; if (!pos) continue; - for (pos = line; !isspace(*pos); pos++); + for (pos = line; !isspace(*pos); pos++) + ; *pos = '\0'; // TODO(geert): we assume ipv4 for now @@ -327,25 +333,29 @@ int lookup_name_hosts(struct lookup_result &buf, const char *name, continue; pos++; - for(; *pos && isspace(*pos); pos++); + for (; *pos && isspace(*pos); pos++) + ; char *end; - for(end = pos; *end && !isspace(*end); end++); + for (end = pos; *end && !isspace(*end); end++) + ; struct dns_addr_buf buffer; memcpy(buffer.addr, &addr, 4); buffer.family = AF_INET; - buffer.name = frg::string{pos, - static_cast(end - pos), getAllocator()}; + buffer.name = + frg::string{pos, static_cast(end - pos), getAllocator()}; canon_name = buffer.name; buf.buf.push(std::move(buffer)); pos = end; while (pos[1]) { - for (; *pos && isspace(*pos); pos++); - for (end = pos; *end && !isspace(*end); end++); - auto name = frg::string{pos, - static_cast(end - pos), getAllocator()}; + for (; *pos && isspace(*pos); pos++) + ; + for (end = pos; *end && !isspace(*end); end++) + ; + auto name = + frg::string{pos, static_cast(end - pos), getAllocator()}; buf.aliases.push(std::move(name)); pos = end; } @@ -359,25 +369,25 @@ int lookup_addr_hosts(frg::span name, frg::array &addr, int f auto file = fopen("/etc/hosts", "r"); if (!file) { switch (errno) { - case ENOENT: - case ENOTDIR: - case EACCES: - return -EAI_SERVICE; - default: - return -EAI_SYSTEM; + case ENOENT: + case ENOTDIR: + case EACCES: + return -EAI_SERVICE; + default: + return -EAI_SYSTEM; } } // Buffer to hold ASCII version of address char addr_str[64]; - if(!inet_ntop(family, addr.data(), addr_str, sizeof(addr_str))) { - switch(errno) { - case EAFNOSUPPORT: - return -EAI_FAMILY; - case ENOSPC: - return -EAI_OVERFLOW; - default: - return -EAI_FAIL; + if (!inet_ntop(family, addr.data(), addr_str, sizeof(addr_str))) { + switch (errno) { + case EAFNOSUPPORT: + return -EAI_FAMILY; + case ENOSPC: + return -EAI_OVERFLOW; + default: + return -EAI_FAIL; } } int addr_str_len = strlen(addr_str); @@ -393,9 +403,11 @@ int lookup_addr_hosts(frg::span name, frg::array &addr, int f if (strncmp(line, addr_str, addr_str_len)) continue; - for (pos = line + addr_str_len + 1; isspace(*pos); pos++); + for (pos = line + addr_str_len + 1; isspace(*pos); pos++) + ; char *begin = pos; - for (; !isspace(*pos); pos++); + for (; !isspace(*pos); pos++) + ; char *end = pos; size_t size = end - begin; diff --git a/options/posix/generic/mqueue.cpp b/options/posix/generic/mqueue.cpp index d63541978a..e6715314bd 100644 --- a/options/posix/generic/mqueue.cpp +++ b/options/posix/generic/mqueue.cpp @@ -1,5 +1,5 @@ -#include #include +#include int mq_getattr(mqd_t, struct mq_attr *) { __ensure(!"Not implemented"); diff --git a/options/posix/generic/net-if.cpp b/options/posix/generic/net-if.cpp index 6a65a5cecc..589f54f262 100644 --- a/options/posix/generic/net-if.cpp +++ b/options/posix/generic/net-if.cpp @@ -13,7 +13,7 @@ void if_freenameindex(struct if_nameindex *) { char *if_indextoname(unsigned int index, char *name) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_if_indextoname, NULL); - if(int e = sysdep(index, name); e) { + if (int e = sysdep(index, name); e) { errno = e; return NULL; } @@ -31,7 +31,7 @@ unsigned int if_nametoindex(const char *name) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_if_nametoindex, 0); unsigned int ret = 0; - if(int e = sysdep(name, &ret); e) { + if (int e = sysdep(name, &ret); e) { errno = e; return 0; } diff --git a/options/posix/generic/netdb.cpp b/options/posix/generic/netdb.cpp index 455444bab8..ba465656f5 100644 --- a/options/posix/generic/netdb.cpp +++ b/options/posix/generic/netdb.cpp @@ -1,26 +1,24 @@ -#include #include +#include +#include +#include +#include +#include +#include +#include #include #include -#include #include -#include -#include -#include -#include -#include -#include -#include #include -#include +#include +#include +#include __thread int __mlibc_h_errno; // This function is from musl -int *__h_errno_location(void) { - return &__mlibc_h_errno; -} +int *__h_errno_location(void) { return &__mlibc_h_errno; } void endhostent(void) { __ensure(!"Not implemented"); @@ -44,7 +42,7 @@ void endservent(void) { void freeaddrinfo(struct addrinfo *ptr) { if (ptr) { - auto buf = (struct mlibc::ai_buf*) ptr - offsetof(struct mlibc::ai_buf, ai); + auto buf = (struct mlibc::ai_buf *)ptr - offsetof(struct mlibc::ai_buf, ai); // this string was allocated by a frg::string getAllocator().free(ptr->ai_canonname); free(buf); @@ -57,8 +55,12 @@ const char *gai_strerror(int code) { return buffer; } -int getaddrinfo(const char *__restrict node, const char *__restrict service, - const struct addrinfo *__restrict hints, struct addrinfo **__restrict res) { +int getaddrinfo( + const char *__restrict node, + const char *__restrict service, + const struct addrinfo *__restrict hints, + struct addrinfo **__restrict res +) { if (!node && !service) return EAI_NONAME; @@ -69,8 +71,8 @@ int getaddrinfo(const char *__restrict node, const char *__restrict service, family = hints->ai_family; flags = hints->ai_flags; - int mask = AI_V4MAPPED | AI_ADDRCONFIG | AI_NUMERICHOST | AI_PASSIVE | - AI_CANONNAME | AI_ALL | AI_NUMERICSERV; + int mask = AI_V4MAPPED | AI_ADDRCONFIG | AI_NUMERICHOST | AI_PASSIVE | AI_CANONNAME | + AI_ALL | AI_NUMERICSERV; if ((flags & mask) != flags) return EAI_BADFLAGS; @@ -89,7 +91,7 @@ int getaddrinfo(const char *__restrict node, const char *__restrict service, if (node) { if ((addr_count = mlibc::lookup_name_ip(addr_buf, node, family)) <= 0) { if (flags & AI_NUMERICHOST) - addr_count = -EAI_NONAME; + addr_count = -EAI_NONAME; else if ((addr_count = mlibc::lookup_name_hosts(addr_buf, node, canon)) <= 0) addr_count = mlibc::lookup_name_dns(addr_buf, node, canon); else @@ -107,8 +109,8 @@ int getaddrinfo(const char *__restrict node, const char *__restrict service, addr_count = lookup_name_null(addr_buf, flags, family); } - auto out = (struct mlibc::ai_buf *) calloc(serv_count * addr_count, - sizeof(struct mlibc::ai_buf)); + auto out = + (struct mlibc::ai_buf *)calloc(serv_count * addr_count, sizeof(struct mlibc::ai_buf)); if (node && !canon.size()) canon = frg::string{node, getAllocator()}; @@ -119,25 +121,25 @@ int getaddrinfo(const char *__restrict node, const char *__restrict service, out[i].ai.ai_socktype = serv_buf[j].socktype; out[i].ai.ai_protocol = serv_buf[j].protocol; out[i].ai.ai_flags = flags; - out[i].ai.ai_addr = (struct sockaddr *) &out[i].sa; + out[i].ai.ai_addr = (struct sockaddr *)&out[i].sa; if (canon.size()) out[i].ai.ai_canonname = canon.data(); else out[i].ai.ai_canonname = NULL; out[i].ai.ai_next = NULL; switch (addr_buf.buf[i].family) { - case AF_INET: - out[i].ai.ai_addrlen = sizeof(struct sockaddr_in); - out[i].sa.sin.sin_port = htons(serv_buf[j].port); - out[i].sa.sin.sin_family = AF_INET; - memcpy(&out[i].sa.sin.sin_addr, addr_buf.buf[i].addr, 4); - break; - case AF_INET6: - out[i].ai.ai_addrlen = sizeof(struct sockaddr_in6); - out[i].sa.sin6.sin6_family = htons(serv_buf[j].port); - out[i].sa.sin6.sin6_family = AF_INET6; - memcpy(&out[i].sa.sin6.sin6_addr, addr_buf.buf[i].addr, 16); - break; + case AF_INET: + out[i].ai.ai_addrlen = sizeof(struct sockaddr_in); + out[i].sa.sin.sin_port = htons(serv_buf[j].port); + out[i].sa.sin.sin_family = AF_INET; + memcpy(&out[i].sa.sin.sin_addr, addr_buf.buf[i].addr, 4); + break; + case AF_INET6: + out[i].ai.ai_addrlen = sizeof(struct sockaddr_in6); + out[i].sa.sin6.sin6_family = htons(serv_buf[j].port); + out[i].sa.sin6.sin6_family = AF_INET6; + memcpy(&out[i].sa.sin6.sin6_addr, addr_buf.buf[i].addr, 16); + break; } } } @@ -153,30 +155,37 @@ struct hostent *gethostent(void) { __builtin_unreachable(); } -int getnameinfo(const struct sockaddr *__restrict addr, socklen_t addr_len, - char *__restrict host, socklen_t host_len, char *__restrict serv, - socklen_t serv_len, int flags) { +int getnameinfo( + const struct sockaddr *__restrict addr, + socklen_t addr_len, + char *__restrict host, + socklen_t host_len, + char *__restrict serv, + socklen_t serv_len, + int flags +) { frg::array addr_array; int family = addr->sa_family; - switch(family) { - case AF_INET: { - if (addr_len < sizeof(struct sockaddr_in)) - return EAI_FAMILY; - auto sockaddr = reinterpret_cast(addr); - memcpy(addr_array.data(), reinterpret_cast(&sockaddr->sin_addr), 4); - break; - } - case AF_INET6: { - mlibc::infoLogger() << "getnameinfo(): ipv6 is not fully supported in this function" << frg::endlog; - if (addr_len < sizeof(struct sockaddr_in6)) - return EAI_FAMILY; - auto sockaddr = reinterpret_cast(addr); - memcpy(addr_array.data(), reinterpret_cast(&sockaddr->sin6_addr), 16); - break; - } - default: + switch (family) { + case AF_INET: { + if (addr_len < sizeof(struct sockaddr_in)) + return EAI_FAMILY; + auto sockaddr = reinterpret_cast(addr); + memcpy(addr_array.data(), reinterpret_cast(&sockaddr->sin_addr), 4); + break; + } + case AF_INET6: { + mlibc::infoLogger() << "getnameinfo(): ipv6 is not fully supported in this function" + << frg::endlog; + if (addr_len < sizeof(struct sockaddr_in6)) return EAI_FAMILY; + auto sockaddr = reinterpret_cast(addr); + memcpy(addr_array.data(), reinterpret_cast(&sockaddr->sin6_addr), 16); + break; + } + default: + return EAI_FAMILY; } if (host && host_len) { @@ -190,14 +199,14 @@ int getnameinfo(const struct sockaddr *__restrict addr, socklen_t addr_len, if (!res) { if (flags & NI_NAMEREQD) return EAI_NONAME; - if(!inet_ntop(family, addr_array.data(), host, host_len)) { - switch(errno) { - case EAFNOSUPPORT: - return EAI_FAMILY; - case ENOSPC: - return EAI_OVERFLOW; - default: - return EAI_FAIL; + if (!inet_ntop(family, addr_array.data(), host, host_len)) { + switch (errno) { + case EAFNOSUPPORT: + return EAI_FAMILY; + case ENOSPC: + return EAI_OVERFLOW; + default: + return EAI_FAIL; } } } @@ -265,8 +274,7 @@ struct hostent *gethostbyname(const char *name) { h.h_name = canon.data(); - h.h_aliases = reinterpret_cast(malloc((buf.aliases.size() + 1) - * sizeof(char*))); + h.h_aliases = reinterpret_cast(malloc((buf.aliases.size() + 1) * sizeof(char *))); int alias_pos = 0; for (auto &buf_name : buf.aliases) { h.h_aliases[alias_pos] = buf_name.data(); @@ -286,12 +294,12 @@ struct hostent *gethostbyname(const char *name) { // can only be AF_INET or AF_INET6 h.h_length = h.h_addrtype == AF_INET ? 4 : 16; - h.h_addr_list = reinterpret_cast(malloc((ret + 1) * sizeof(char*))); + h.h_addr_list = reinterpret_cast(malloc((ret + 1) * sizeof(char *))); int addr_pos = 0; for (int i = 0; i < ret; i++) { if (buf.buf[i].family != h.h_addrtype) continue; - h.h_addr_list[addr_pos] = reinterpret_cast(malloc(h.h_length)); + h.h_addr_list[addr_pos] = reinterpret_cast(malloc(h.h_length)); memcpy(h.h_addr_list[addr_pos], buf.buf[i].addr, h.h_length); addr_pos++; } @@ -310,14 +318,28 @@ struct hostent *gethostbyaddr(const void *, socklen_t, int) { __builtin_unreachable(); } -int gethostbyaddr_r(const void *__restrict, socklen_t, int, struct hostent *__restrict, - char *__restrict, size_t, struct hostent **__restrict, int *__restrict) { +int gethostbyaddr_r( + const void *__restrict, + socklen_t, + int, + struct hostent *__restrict, + char *__restrict, + size_t, + struct hostent **__restrict, + int *__restrict +) { __ensure(!"Not implemented"); __builtin_unreachable(); } -int gethostbyname_r(const char *__restrict, struct hostent *__restrict, char *__restrict, size_t, - struct hostent **__restrict, int *__restrict) { +int gethostbyname_r( + const char *__restrict, + struct hostent *__restrict, + char *__restrict, + size_t, + struct hostent **__restrict, + int *__restrict +) { __ensure(!"Not implemented"); __builtin_unreachable(); } @@ -339,7 +361,7 @@ struct protoent *getprotoent(void) { struct servent *getservbyname(const char *name, const char *proto) { int iproto = -1; - if (proto &&(!strncmp(proto, "tcp", 3) || !strncmp(proto, "TCP", 3))) + if (proto && (!strncmp(proto, "tcp", 3) || !strncmp(proto, "TCP", 3))) iproto = IPPROTO_TCP; else if (proto && (!strncmp(proto, "udp", 3) || !strncmp(proto, "UDP", 3))) iproto = IPPROTO_UDP; @@ -359,8 +381,7 @@ struct servent *getservbyname(const char *name, const char *proto) { } mlibc::service_result serv_buf{getAllocator()}; - int count = mlibc::lookup_serv_by_name(serv_buf, name, iproto, - 0, 0); + int count = mlibc::lookup_serv_by_name(serv_buf, name, iproto, 0, 0); if (count <= 0) return NULL; @@ -370,7 +391,8 @@ struct servent *getservbyname(const char *name, const char *proto) { if (strncmp(name, serv_buf[0].name.data(), serv_buf[0].name.size())) return NULL; - ret.s_aliases = reinterpret_cast(malloc((serv_buf[0].aliases.size() + 1) * sizeof(char*))); + ret.s_aliases = + reinterpret_cast(malloc((serv_buf[0].aliases.size() + 1) * sizeof(char *))); int alias_pos = 0; for (auto &buf_name : serv_buf[0].aliases) { ret.s_aliases[alias_pos] = buf_name.data(); @@ -427,7 +449,8 @@ struct servent *getservbyport(int port, const char *proto) { ret.s_name = serv_buf[0].name.data(); serv_buf[0].name.detach(); - ret.s_aliases = reinterpret_cast(malloc((serv_buf[0].aliases.size() + 1) * sizeof(char*))); + ret.s_aliases = + reinterpret_cast(malloc((serv_buf[0].aliases.size() + 1) * sizeof(char *))); int alias_pos = 0; for (auto &buf_name : serv_buf[0].aliases) { ret.s_aliases[alias_pos] = buf_name.data(); diff --git a/options/posix/generic/poll.cpp b/options/posix/generic/poll.cpp index c34e25ea73..f1ddbdd841 100644 --- a/options/posix/generic/poll.cpp +++ b/options/posix/generic/poll.cpp @@ -9,7 +9,7 @@ int poll(struct pollfd *fds, nfds_t count, int timeout) { int num_events; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_poll, -1); - if(int e = mlibc::sys_poll(fds, count, timeout, &num_events); e) { + if (int e = mlibc::sys_poll(fds, count, timeout, &num_events); e) { errno = e; return -1; } @@ -17,9 +17,11 @@ int poll(struct pollfd *fds, nfds_t count, int timeout) { } #if __MLIBC_LINUX_OPTION -int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout_ts, const sigset_t *sigmask) { +int +ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout_ts, const sigset_t *sigmask) { sigset_t origmask; - int timeout = (timeout_ts == NULL) ? -1 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000); + int timeout = + (timeout_ts == NULL) ? -1 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000); sigprocmask(SIG_SETMASK, sigmask, &origmask); int ready = poll(fds, nfds, timeout); @@ -28,4 +30,3 @@ int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout_ts, co return ready; } #endif // __MLIBC_LINUX_OPTION - diff --git a/options/posix/generic/posix-file-io.cpp b/options/posix/generic/posix-file-io.cpp index 1a4f38bd9c..419d8d535a 100644 --- a/options/posix/generic/posix-file-io.cpp +++ b/options/posix/generic/posix-file-io.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -7,7 +7,8 @@ namespace mlibc { int mem_file::reopen(const char *, const char *) { - mlibc::panicLogger() << "mlibc: freopen() on a mem_file stream is unimplemented!" << frg::endlog; + mlibc::panicLogger() << "mlibc: freopen() on a mem_file stream is unimplemented!" + << frg::endlog; return -1; } @@ -21,9 +22,12 @@ int mem_file::determine_bufmode(buffer_mode *mode) { return 0; } -memstream_mem_file::memstream_mem_file(char **ptr, size_t *sizeloc, int flags, void (*do_dispose)(abstract_file *)) -: mem_file{flags, do_dispose}, _bufloc{ptr}, _sizeloc{sizeloc} { } - +memstream_mem_file::memstream_mem_file( + char **ptr, size_t *sizeloc, int flags, void (*do_dispose)(abstract_file *) +) + : mem_file{flags, do_dispose}, + _bufloc{ptr}, + _sizeloc{sizeloc} {} int memstream_mem_file::close() { _update_ptrs(); @@ -61,30 +65,30 @@ int memstream_mem_file::io_write(const char *buffer, size_t max_size, size_t *ac int memstream_mem_file::io_seek(off_t offset, int whence, off_t *new_offset) { switch (whence) { - case SEEK_SET: - _pos = offset; - if (_pos >= 0 && size_t(_pos) >= _buffer_size()) { - _buf.resize(_pos + 1, '\0'); - _update_ptrs(); - } - *new_offset = _pos; - break; - case SEEK_CUR: - _pos += offset; - if (_pos >= 0 && size_t(_pos) >= _buffer_size()) { - _buf.resize(_pos + 1, '\0'); - _update_ptrs(); - } - *new_offset = _pos; - break; - case SEEK_END: - _pos = _buffer_size() ? _buffer_size() - 1 + offset : _buffer_size() + offset; + case SEEK_SET: + _pos = offset; + if (_pos >= 0 && size_t(_pos) >= _buffer_size()) { _buf.resize(_pos + 1, '\0'); _update_ptrs(); - *new_offset = _pos; - break; - default: - return EINVAL; + } + *new_offset = _pos; + break; + case SEEK_CUR: + _pos += offset; + if (_pos >= 0 && size_t(_pos) >= _buffer_size()) { + _buf.resize(_pos + 1, '\0'); + _update_ptrs(); + } + *new_offset = _pos; + break; + case SEEK_END: + _pos = _buffer_size() ? _buffer_size() - 1 + offset : _buffer_size() + offset; + _buf.resize(_pos + 1, '\0'); + _update_ptrs(); + *new_offset = _pos; + break; + default: + return EINVAL; } return 0; } @@ -94,18 +98,24 @@ void memstream_mem_file::_update_ptrs() { *_sizeloc = _buf.size() - 1; } -fmemopen_mem_file::fmemopen_mem_file(void *in_buf, size_t size, int flags, void (*do_dispose)(abstract_file *)) -: mem_file{flags, do_dispose}, _inBuffer{in_buf}, _inBufferSize{size} { - if(!_inBuffer) { +fmemopen_mem_file::fmemopen_mem_file( + void *in_buf, size_t size, int flags, void (*do_dispose)(abstract_file *) +) + : mem_file{flags, do_dispose}, + _inBuffer{in_buf}, + _inBufferSize{size} { + if (!_inBuffer) { _inBuffer = getAllocator().allocate(size); _needsDeallocation = true; } - if(_flags & O_APPEND) { - // the initial seek-size for append is zero if buf was NULL, or the first '\0' found, or the size - _max_size = (_needsDeallocation) ? 0 : strnlen(reinterpret_cast(_inBuffer), _inBufferSize); + if (_flags & O_APPEND) { + // the initial seek-size for append is zero if buf was NULL, or the first '\0' found, or the + // size + _max_size = + (_needsDeallocation) ? 0 : strnlen(reinterpret_cast(_inBuffer), _inBufferSize); _pos = _max_size; - } else if((_flags & O_WRONLY || _flags & O_RDWR) && _flags & O_CREAT && _flags & O_TRUNC) { + } else if ((_flags & O_WRONLY || _flags & O_RDWR) && _flags & O_CREAT && _flags & O_TRUNC) { // modes: "w", "w+" _max_size = 0; } else { @@ -114,7 +124,7 @@ fmemopen_mem_file::fmemopen_mem_file(void *in_buf, size_t size, int flags, void } int fmemopen_mem_file::close() { - if(_needsDeallocation) { + if (_needsDeallocation) { getAllocator().free(_inBuffer); } @@ -140,18 +150,18 @@ int fmemopen_mem_file::io_write(const char *buffer, size_t max_size, size_t *act _pos += bytes_write; *actual_size = bytes_write; - if(_pos > _max_size) { + if (_pos > _max_size) { _max_size = _pos; } // upon flushing, we need to put a null byte at the current position or at the end of the buffer size_t null = _pos; // a special case is if the mode is set to updating ('+'), then it always goes at the end - if(null >= _buffer_size() || _flags & O_RDWR) { + if (null >= _buffer_size() || _flags & O_RDWR) { null = _buffer_size() - 1; } - if(_buffer_size()) { + if (_buffer_size()) { _buffer()[null] = '\0'; } @@ -160,36 +170,37 @@ int fmemopen_mem_file::io_write(const char *buffer, size_t max_size, size_t *act int fmemopen_mem_file::io_seek(off_t offset, int whence, off_t *new_offset) { switch (whence) { - case SEEK_SET: - if(offset < 0 || size_t(offset) > _buffer_size()) { - return EINVAL; - } - _pos = offset; - *new_offset = _pos; - break; - case SEEK_CUR: - // seeking to negative positions or positions larger than the buffer is disallowed in fmemopen(3) - if((_pos + offset) < 0 || size_t(_pos + offset) > _buffer_size()) { - return EINVAL; - } - _pos += offset; - *new_offset = _pos; - break; - case SEEK_END: - if((_max_size + offset) < 0 || size_t(_max_size + offset) > _buffer_size()) { - return EINVAL; - } - _pos = _max_size + offset; - *new_offset = _pos; - break; - default: + case SEEK_SET: + if (offset < 0 || size_t(offset) > _buffer_size()) { return EINVAL; + } + _pos = offset; + *new_offset = _pos; + break; + case SEEK_CUR: + // seeking to negative positions or positions larger than the buffer is disallowed in + // fmemopen(3) + if ((_pos + offset) < 0 || size_t(_pos + offset) > _buffer_size()) { + return EINVAL; + } + _pos += offset; + *new_offset = _pos; + break; + case SEEK_END: + if ((_max_size + offset) < 0 || size_t(_max_size + offset) > _buffer_size()) { + return EINVAL; + } + _pos = _max_size + offset; + *new_offset = _pos; + break; + default: + return EINVAL; } return 0; } int cookie_file::close() { - if(!_funcs.close) { + if (!_funcs.close) { return 0; } @@ -197,7 +208,8 @@ int cookie_file::close() { } int cookie_file::reopen(const char *, const char *) { - mlibc::panicLogger() << "mlibc: freopen() on a cookie_file stream is unimplemented!" << frg::endlog; + mlibc::panicLogger() << "mlibc: freopen() on a cookie_file stream is unimplemented!" + << frg::endlog; return -1; } @@ -212,7 +224,7 @@ int cookie_file::determine_bufmode(buffer_mode *mode) { } int cookie_file::io_read(char *buffer, size_t max_size, size_t *actual_size) { - if(!_funcs.read) { + if (!_funcs.read) { return EOF; } @@ -222,7 +234,7 @@ int cookie_file::io_read(char *buffer, size_t max_size, size_t *actual_size) { } int cookie_file::io_write(const char *buffer, size_t max_size, size_t *actual_size) { - if(!_funcs.write) { + if (!_funcs.write) { return 0; } @@ -232,7 +244,7 @@ int cookie_file::io_write(const char *buffer, size_t max_size, size_t *actual_si } int cookie_file::io_seek(off_t offset, int whence, off_t *new_offset) { - if(!_funcs.seek) { + if (!_funcs.seek) { return ENOTSUP; } @@ -270,6 +282,6 @@ FILE *fdopen(int fd, const char *mode) { // TODO: We may need to activate line buffered mode for terminals. - return frg::construct(getAllocator(), fd, - mlibc::file_dispose_cb); + return frg::construct< + mlibc::fd_file>(getAllocator(), fd, mlibc::file_dispose_cb); } diff --git a/options/posix/generic/posix_ctype.cpp b/options/posix/generic/posix_ctype.cpp index 19f129f004..573f777a68 100644 --- a/options/posix/generic/posix_ctype.cpp +++ b/options/posix/generic/posix_ctype.cpp @@ -3,134 +3,68 @@ #include -int isalnum_l(int c, locale_t) { - return isalnum(c); -} +int isalnum_l(int c, locale_t) { return isalnum(c); } -int isalpha_l(int c, locale_t) { - return isalpha(c); -} +int isalpha_l(int c, locale_t) { return isalpha(c); } -int isblank_l(int c, locale_t) { - return isblank(c); -} +int isblank_l(int c, locale_t) { return isblank(c); } -int iscntrl_l(int c, locale_t) { - return iscntrl(c); -} +int iscntrl_l(int c, locale_t) { return iscntrl(c); } -int isdigit_l(int c, locale_t) { - return isdigit(c); -} +int isdigit_l(int c, locale_t) { return isdigit(c); } -int isgraph_l(int c, locale_t) { - return isgraph(c); -} +int isgraph_l(int c, locale_t) { return isgraph(c); } -int islower_l(int c, locale_t) { - return islower(c); -} +int islower_l(int c, locale_t) { return islower(c); } -int isprint_l(int c, locale_t) { - return isprint(c); -} +int isprint_l(int c, locale_t) { return isprint(c); } -int ispunct_l(int c, locale_t) { - return ispunct(c); -} +int ispunct_l(int c, locale_t) { return ispunct(c); } -int isspace_l(int c, locale_t) { - return isspace(c); -} +int isspace_l(int c, locale_t) { return isspace(c); } -int isupper_l(int c, locale_t) { - return isupper(c); -} +int isupper_l(int c, locale_t) { return isupper(c); } -int isxdigit_l(int c, locale_t) { - return isxdigit(c); -} +int isxdigit_l(int c, locale_t) { return isxdigit(c); } -int isascii_l(int c, locale_t) { - return isascii(c); -} +int isascii_l(int c, locale_t) { return isascii(c); } -int tolower_l(int c, locale_t) { - return tolower(c); -} +int tolower_l(int c, locale_t) { return tolower(c); } -int toupper_l(int c, locale_t) { - return toupper(c); -} +int toupper_l(int c, locale_t) { return toupper(c); } -int iswalnum_l(wint_t c, locale_t) { - return iswalnum(c); -} +int iswalnum_l(wint_t c, locale_t) { return iswalnum(c); } -int iswblank_l(wint_t c, locale_t) { - return iswblank(c); -} +int iswblank_l(wint_t c, locale_t) { return iswblank(c); } -int iswcntrl_l(wint_t c, locale_t) { - return iswcntrl(c); -} +int iswcntrl_l(wint_t c, locale_t) { return iswcntrl(c); } -int iswdigit_l(wint_t c, locale_t) { - return iswdigit(c); -} +int iswdigit_l(wint_t c, locale_t) { return iswdigit(c); } -int iswgraph_l(wint_t c, locale_t) { - return iswgraph(c); -} +int iswgraph_l(wint_t c, locale_t) { return iswgraph(c); } -int iswlower_l(wint_t c, locale_t) { - return iswlower(c); -} +int iswlower_l(wint_t c, locale_t) { return iswlower(c); } -int iswprint_l(wint_t c, locale_t) { - return iswprint(c); -} +int iswprint_l(wint_t c, locale_t) { return iswprint(c); } -int iswpunct_l(wint_t c, locale_t) { - return iswpunct(c); -} +int iswpunct_l(wint_t c, locale_t) { return iswpunct(c); } -int iswspace_l(wint_t c, locale_t) { - return iswspace(c); -} +int iswspace_l(wint_t c, locale_t) { return iswspace(c); } -int iswupper_l(wint_t c, locale_t) { - return iswupper(c); -} +int iswupper_l(wint_t c, locale_t) { return iswupper(c); } -int iswxdigit_l(wint_t c, locale_t) { - return iswxdigit(c); -} +int iswxdigit_l(wint_t c, locale_t) { return iswxdigit(c); } -int iswalpha_l(wint_t c, locale_t) { - return iswalpha(c); -} +int iswalpha_l(wint_t c, locale_t) { return iswalpha(c); } -wctype_t wctype_l(const char* p, locale_t) { - return wctype(p); -} +wctype_t wctype_l(const char *p, locale_t) { return wctype(p); } -int iswctype_l(wint_t w, wctype_t t, locale_t) { - return iswctype(w, t); -} +int iswctype_l(wint_t w, wctype_t t, locale_t) { return iswctype(w, t); } -wint_t towlower_l(wint_t c, locale_t) { - return towlower(c); -} +wint_t towlower_l(wint_t c, locale_t) { return towlower(c); } -wint_t towupper_l(wint_t c, locale_t) { - return towupper(c); -} +wint_t towupper_l(wint_t c, locale_t) { return towupper(c); } -wctrans_t wctrans_l(const char* c, locale_t) { - return wctrans(c); -} +wctrans_t wctrans_l(const char *c, locale_t) { return wctrans(c); } -wint_t towctrans_l(wint_t c, wctrans_t desc, locale_t) { - return towctrans(c, desc); -} +wint_t towctrans_l(wint_t c, wctrans_t desc, locale_t) { return towctrans(c, desc); } diff --git a/options/posix/generic/posix_locale.cpp b/options/posix/generic/posix_locale.cpp index bd8710a8fd..7d9b2bc7f8 100644 --- a/options/posix/generic/posix_locale.cpp +++ b/options/posix/generic/posix_locale.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include namespace { @@ -7,11 +7,11 @@ namespace { bool newlocale_seen = false; bool uselocale_seen = false; -} +} // namespace locale_t newlocale(int, const char *, locale_t) { // Due to all of the locale functions being stubs, the locale will not be used - if(!newlocale_seen) { + if (!newlocale_seen) { mlibc::infoLogger() << "mlibc: newlocale() is a no-op" << frg::endlog; newlocale_seen = true; } @@ -24,7 +24,7 @@ void freelocale(locale_t) { } locale_t uselocale(locale_t) { - if(!uselocale_seen) { + if (!uselocale_seen) { mlibc::infoLogger() << "mlibc: uselocale() is a no-op" << frg::endlog; uselocale_seen = true; } diff --git a/options/posix/generic/posix_signal.cpp b/options/posix/generic/posix_signal.cpp index 57652dec4f..0b16fe03c7 100644 --- a/options/posix/generic/posix_signal.cpp +++ b/options/posix/generic/posix_signal.cpp @@ -1,8 +1,8 @@ +#include #include #include #include -#include #include #include @@ -16,11 +16,11 @@ int sigsuspend(const sigset_t *sigmask) { } int pthread_sigmask(int how, const sigset_t *__restrict set, sigset_t *__restrict retrieve) { - if(!mlibc::sys_sigprocmask) { + if (!mlibc::sys_sigprocmask) { MLIBC_MISSING_SYSDEP(); return ENOSYS; } - if(int e = mlibc::sys_sigprocmask(how, set, retrieve); e) { + if (int e = mlibc::sys_sigprocmask(how, set, retrieve); e) { return e; } return 0; @@ -30,21 +30,22 @@ int pthread_kill(pthread_t thread, int sig) { auto tcb = reinterpret_cast(thread); auto pid = getpid(); - if(!mlibc::sys_tgkill) { + if (!mlibc::sys_tgkill) { MLIBC_MISSING_SYSDEP(); return ENOSYS; } - if(int e = mlibc::sys_tgkill(pid, tcb->tid, sig); e) { + if (int e = mlibc::sys_tgkill(pid, tcb->tid, sig); e) { return e; } return 0; } -int sigaction(int signum, const struct sigaction *__restrict act, struct sigaction *__restrict oldact) { +int +sigaction(int signum, const struct sigaction *__restrict act, struct sigaction *__restrict oldact) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sigaction, -1); - if(int e = mlibc::sys_sigaction(signum, act, oldact); e) { + if (int e = mlibc::sys_sigaction(signum, act, oldact); e) { errno = e; return -1; } @@ -67,7 +68,7 @@ int siginterrupt(int sig, int flag) { int kill(pid_t pid, int number) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_kill, -1); - if(int e = mlibc::sys_kill(pid, number); e) { + if (int e = mlibc::sys_kill(pid, number); e) { errno = e; return -1; } @@ -75,7 +76,7 @@ int kill(pid_t pid, int number) { } int killpg(pid_t pgrp, int sig) { - if(pgrp > 1) { + if (pgrp > 1) { return kill(-pgrp, sig); } @@ -83,7 +84,11 @@ int killpg(pid_t pgrp, int sig) { return -1; } -int sigtimedwait(const sigset_t *__restrict set, siginfo_t *__restrict info, const struct timespec *__restrict timeout) { +int sigtimedwait( + const sigset_t *__restrict set, + siginfo_t *__restrict info, + const struct timespec *__restrict timeout +) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sigtimedwait, -1); int signo; @@ -115,7 +120,7 @@ int sigwait(const sigset_t *__restrict set, int *__restrict sig) { int sigpending(sigset_t *set) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sigpending, -1); - if(int e = sysdep(set)) { + if (int e = sysdep(set)) { errno = e; return -1; } @@ -141,8 +146,8 @@ int sigaltstack(const stack_t *__restrict ss, stack_t *__restrict oss) { #if __MLIBC_GLIBC_OPTION int sigisemptyset(const sigset_t *set) { auto ptr = reinterpret_cast(set); - for(size_t i = 0; i < sizeof(sigset_t); i++) { - if(ptr[i]) { + for (size_t i = 0; i < sizeof(sigset_t); i++) { + if (ptr[i]) { return 0; } } @@ -154,4 +159,3 @@ int sigqueue(pid_t, int, const union sigval) { __ensure(!"sigqueue() not implemented"); __builtin_unreachable(); } - diff --git a/options/posix/generic/posix_stdio.cpp b/options/posix/generic/posix_stdio.cpp index 5edb1d7010..374a21dd8f 100644 --- a/options/posix/generic/posix_stdio.cpp +++ b/options/posix/generic/posix_stdio.cpp @@ -3,10 +3,10 @@ #endif #include +#include #include #include #include -#include #include #include @@ -16,18 +16,13 @@ #include struct popen_file : mlibc::fd_file { - popen_file(int fd, void (*do_dispose)(abstract_file *) = nullptr) - : fd_file(fd, do_dispose) {} + popen_file(int fd, void (*do_dispose)(abstract_file *) = nullptr) : fd_file(fd, do_dispose) {} - pid_t get_popen_pid() { - return _popen_pid; - } + pid_t get_popen_pid() { return _popen_pid; } - void set_popen_pid(pid_t new_pid) { - _popen_pid = new_pid; - } + void set_popen_pid(pid_t new_pid) { _popen_pid = new_pid; } -private: + private: // Underlying PID in case of popen() pid_t _popen_pid; }; @@ -35,8 +30,9 @@ struct popen_file : mlibc::fd_file { FILE *fmemopen(void *buf, size_t size, const char *__restrict mode) { int flags = mlibc::fd_file::parse_modestring(mode); - return frg::construct(getAllocator(), buf, size, flags, - mlibc::file_dispose_cb); + return frg::construct< + mlibc:: + fmemopen_mem_file>(getAllocator(), buf, size, flags, mlibc::file_dispose_cb); } int pclose(FILE *stream) { @@ -50,8 +46,8 @@ int pclose(FILE *stream) { fclose(file); if (mlibc::sys_waitpid(pid, &status, 0, NULL, &pid) != 0) { - errno = ECHILD; - return -1; + errno = ECHILD; + return -1; } return status; @@ -62,8 +58,11 @@ FILE *popen(const char *command, const char *typestr) { pid_t child; FILE *ret = nullptr; - MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fork && mlibc::sys_dup2 && mlibc::sys_execve && - mlibc::sys_sigprocmask && mlibc::sys_sigaction && mlibc::sys_pipe, nullptr); + MLIBC_CHECK_OR_ENOSYS( + mlibc::sys_fork && mlibc::sys_dup2 && mlibc::sys_execve && mlibc::sys_sigprocmask && + mlibc::sys_sigaction && mlibc::sys_pipe, + nullptr + ); if (typestr == NULL) { errno = EINVAL; @@ -124,9 +123,7 @@ FILE *popen(const char *command, const char *typestr) { } mlibc::sys_close(fds[child_end]); - const char *args[] = { - "sh", "-c", command, nullptr - }; + const char *args[] = {"sh", "-c", command, nullptr}; mlibc::sys_execve("/bin/sh", const_cast(args), environ); _Exit(127); @@ -134,11 +131,8 @@ FILE *popen(const char *command, const char *typestr) { // For the parent mlibc::sys_close(fds[child_end]); - ret = frg::construct( - getAllocator(), - fds[parent_end], - mlibc::file_dispose_cb - ); + ret = frg::construct< + popen_file>(getAllocator(), fds[parent_end], mlibc::file_dispose_cb); __ensure(ret); auto file = static_cast(ret); @@ -158,13 +152,14 @@ FILE *popen(const char *command, const char *typestr) { } FILE *open_memstream(char **buf, size_t *sizeloc) { - return frg::construct(getAllocator(), buf, sizeloc, O_RDWR, - mlibc::file_dispose_cb); + return frg::construct< + mlibc:: + memstream_mem_file>(getAllocator(), buf, sizeloc, O_RDWR, mlibc::file_dispose_cb); } int fseeko(FILE *file_base, off_t offset, int whence) { auto file = static_cast(file_base); - if(int e = file->seek(offset, whence); e) { + if (int e = file->seek(offset, whence); e) { errno = e; return -1; } @@ -176,7 +171,7 @@ int fseeko(FILE *file_base, off_t offset, int whence) { off_t ftello(FILE *file_base) { auto file = static_cast(file_base); off_t current_offset; - if(int e = file->tell(¤t_offset); e) { + if (int e = file->tell(¤t_offset); e) { errno = e; return -1; } @@ -213,6 +208,7 @@ char *tempnam(const char *, const char *) { FILE *fopencookie(void *cookie, const char *__restrict mode, cookie_io_functions_t funcs) { int flags = mlibc::fd_file::parse_modestring(mode); - return frg::construct(getAllocator(), cookie, flags, funcs, - mlibc::file_dispose_cb); + return frg::construct< + mlibc:: + cookie_file>(getAllocator(), cookie, flags, funcs, mlibc::file_dispose_cb); } diff --git a/options/posix/generic/posix_stdlib.cpp b/options/posix/generic/posix_stdlib.cpp index 7e645e4cac..08820fd613 100644 --- a/options/posix/generic/posix_stdlib.cpp +++ b/options/posix/generic/posix_stdlib.cpp @@ -4,12 +4,12 @@ #include #include #include -#include #include +#include #include -#include #include #include +#include #include #include @@ -18,33 +18,25 @@ #include namespace { - constexpr bool debugPathResolution = false; +constexpr bool debugPathResolution = false; } // Borrowed from musl -static uint32_t init[] = { -0x00000000,0x5851f42d,0xc0b18ccf,0xcbb5f646, -0xc7033129,0x30705b04,0x20fd5db4,0x9a8b7f78, -0x502959d8,0xab894868,0x6c0356a7,0x88cdb7ff, -0xb477d43f,0x70a3a52b,0xa8e4baf1,0xfd8341fc, -0x8ae16fd9,0x742d2f7a,0x0d1f0796,0x76035e09, -0x40f7702c,0x6fa72ca5,0xaaa84157,0x58a0df74, -0xc74a0364,0xae533cc4,0x04185faf,0x6de3b115, -0x0cab8628,0xf043bfa4,0x398150e9,0x37521657}; +static uint32_t init[] = {0x00000000, 0x5851f42d, 0xc0b18ccf, 0xcbb5f646, 0xc7033129, 0x30705b04, + 0x20fd5db4, 0x9a8b7f78, 0x502959d8, 0xab894868, 0x6c0356a7, 0x88cdb7ff, + 0xb477d43f, 0x70a3a52b, 0xa8e4baf1, 0xfd8341fc, 0x8ae16fd9, 0x742d2f7a, + 0x0d1f0796, 0x76035e09, 0x40f7702c, 0x6fa72ca5, 0xaaa84157, 0x58a0df74, + 0xc74a0364, 0xae533cc4, 0x04185faf, 0x6de3b115, 0x0cab8628, 0xf043bfa4, + 0x398150e9, 0x37521657}; static int n = 31; static int i = 3; static int j = 0; static uint32_t *x = init + 1; +static uint32_t lcg31(uint32_t x) { return (1103515245 * x + 12345) & 0x7fffffff; } -static uint32_t lcg31(uint32_t x) { - return (1103515245 * x + 12345) & 0x7fffffff; -} - -static uint64_t lcg64(uint64_t x) { - return 6364136223846793005ull * x + 1; -} +static uint64_t lcg64(uint64_t x) { return 6364136223846793005ull * x + 1; } static void *savestate(void) { x[-1] = (n << 16) | (i << 8) | j; @@ -61,15 +53,15 @@ static void loadstate(uint32_t *state) { long random(void) { long k; - if(n == 0) { + if (n == 0) { k = x[0] = lcg31(x[0]); return k; } x[i] += x[j]; k = x[i] >> 1; - if(++i == n) + if (++i == n) i = 0; - if(++j == n) + if (++j == n) j = 0; return k; @@ -78,15 +70,15 @@ long random(void) { // erand, drand and srand are borrowed from musl namespace { -unsigned short seed_48[7] = { 0, 0, 0, 0xe66d, 0xdeec, 0x5, 0xb }; +unsigned short seed_48[7] = {0, 0, 0, 0xe66d, 0xdeec, 0x5, 0xb}; uint64_t eand48_step(unsigned short *xi, unsigned short *lc) { uint64_t x = xi[0] | (xi[1] + 0U) << 16 | (xi[2] + 0ULL) << 32; uint64_t a = lc[0] | (lc[1] + 0U) << 16 | (lc[2] + 0ULL) << 32; - x = a*x + lc[3]; + x = a * x + lc[3]; xi[0] = x; - xi[1] = x>>16; - xi[2] = x>>32; + xi[1] = x >> 16; + xi[2] = x >> 32; return x & 0xffffffffffffull; } @@ -96,13 +88,11 @@ double erand48(unsigned short s[3]) { union { uint64_t u; double f; - } x = { 0x3ff0000000000000ULL | eand48_step(s, seed_48+3)<<4 }; + } x = {0x3ff0000000000000ULL | eand48_step(s, seed_48 + 3) << 4}; return x.f - 1.0; } -double drand48(void) { - return erand48(seed_48); -} +double drand48(void) { return erand48(seed_48); } unsigned short *seed48(unsigned short *s) { static unsigned short p[3]; @@ -112,11 +102,11 @@ unsigned short *seed48(unsigned short *s) { } void srand48(long int seed) { - unsigned short arr[3] = { 0x330e, (unsigned short) seed, (unsigned short) (seed>>16) }; + unsigned short arr[3] = {0x330e, (unsigned short)seed, (unsigned short)(seed >> 16)}; seed48(arr); } -long jrand48(unsigned short [3]) { +long jrand48(unsigned short[3]) { __ensure(!"Not implemented"); __builtin_unreachable(); } @@ -126,13 +116,13 @@ void srandom(unsigned int seed) { int k; uint64_t s = seed; - if(n == 0) { + if (n == 0) { x[0] = s; return; } i = n == 31 || n == 7 ? 3 : 1; j = 0; - for(k = 0; k < n; k++) { + for (k = 0; k < n; k++) { s = lcg64(s); x[k] = s >> 32; } @@ -143,16 +133,16 @@ void srandom(unsigned int seed) { char *initstate(unsigned int seed, char *state, size_t size) { void *old; - if(size < 8) + if (size < 8) return 0; old = savestate(); - if(size < 32) + if (size < 32) n = 0; - else if(size < 64) + else if (size < 64) n = 7; - else if(size < 128) + else if (size < 128) n = 15; - else if(size < 256) + else if (size < 256) n = 31; else n = 63; @@ -174,33 +164,34 @@ char *setstate(char *state) { // Path handling. // ---------------------------------------------------------------------------- - int mkostemps(char *pattern, int suffixlen, int flags) { auto n = strlen(pattern); - if(n < (6 + static_cast(suffixlen))) { + if (n < (6 + static_cast(suffixlen))) { errno = EINVAL; return -1; } flags &= ~O_WRONLY; - for(size_t i = 0; i < 6; i++) { - if(pattern[n - (6 + suffixlen) + i] == 'X') + for (size_t i = 0; i < 6; i++) { + if (pattern[n - (6 + suffixlen) + i] == 'X') continue; errno = EINVAL; return -1; } // TODO: Do an exponential search. - for(size_t i = 0; i < 999999; i++) { + for (size_t i = 0; i < 999999; i++) { char sfx = pattern[n - suffixlen]; __ensure(sprintf(pattern + (n - (6 + suffixlen)), "%06zu", i) == 6); pattern[n - suffixlen] = sfx; int fd; - if(int e = mlibc::sys_open(pattern, O_RDWR | O_CREAT | O_EXCL | flags, S_IRUSR | S_IWUSR, &fd); !e) { + if (int e = + mlibc::sys_open(pattern, O_RDWR | O_CREAT | O_EXCL | flags, S_IRUSR | S_IWUSR, &fd); + !e) { return fd; - }else if(e != EEXIST) { + } else if (e != EEXIST) { errno = e; return -1; } @@ -210,39 +201,33 @@ int mkostemps(char *pattern, int suffixlen, int flags) { return -1; } -int mkostemp(char *pattern, int flags) { - return mkostemps(pattern, flags, 0); -} +int mkostemp(char *pattern, int flags) { return mkostemps(pattern, flags, 0); } -int mkstemp(char *path) { - return mkostemp(path, 0); -} +int mkstemp(char *path) { return mkostemp(path, 0); } -int mkstemps(char *pattern, int suffixlen) { - return mkostemps(pattern, suffixlen, 0); -} +int mkstemps(char *pattern, int suffixlen) { return mkostemps(pattern, suffixlen, 0); } char *mkdtemp(char *pattern) { mlibc::infoLogger() << "mlibc mkdtemp(" << pattern << ") called" << frg::endlog; auto n = strlen(pattern); __ensure(n >= 6); - if(n < 6) { + if (n < 6) { errno = EINVAL; return NULL; } - for(size_t i = 0; i < 6; i++) { - if(pattern[n - 6 + i] == 'X') + for (size_t i = 0; i < 6; i++) { + if (pattern[n - 6 + i] == 'X') continue; errno = EINVAL; return NULL; } // TODO: Do an exponential search. - for(size_t i = 0; i < 999999; i++) { + for (size_t i = 0; i < 999999; i++) { __ensure(sprintf(pattern + (n - 6), "%06zu", i) == 6); - if(int e = mlibc::sys_mkdir(pattern, S_IRWXU); !e) { + if (int e = mlibc::sys_mkdir(pattern, S_IRWXU); !e) { return pattern; - }else if(e != EEXIST) { + } else if (e != EEXIST) { errno = e; return NULL; } @@ -253,7 +238,7 @@ char *mkdtemp(char *pattern) { } char *realpath(const char *path, char *out) { - if(debugPathResolution) + if (debugPathResolution) mlibc::infoLogger() << "mlibc realpath(): Called on '" << path << "'" << frg::endlog; frg::string_view path_view{path}; @@ -262,31 +247,31 @@ char *realpath(const char *path, char *out) { size_t ps; // If the path is relative, we have to preprend the working directory. - if(path[0] == '/') { + if (path[0] == '/') { resolv.push_back(0); ps = 1; - }else{ + } else { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getcwd, nullptr); // Try to getcwd() until the buffer is large enough. resolv.resize(128); - while(true) { + while (true) { int e = mlibc::sys_getcwd(resolv.data(), resolv.size()); - if(e == ERANGE) { + if (e == ERANGE) { resolv.resize(2 * resolv.size()); - }else if(!e) { + } else if (!e) { break; - }else{ + } else { errno = e; return nullptr; } } frg::string_view cwd_view{resolv.data()}; - if(cwd_view == "/") { + if (cwd_view == "/") { // Restore our invariant that we only store the null-terminator for the root. resolv.resize(1); resolv[0] = 0; - }else{ + } else { resolv.resize(cwd_view.size() + 1); } ps = 0; @@ -296,18 +281,18 @@ char *realpath(const char *path, char *out) { frg::small_vector lnk{getAllocator()}; size_t ls = 0; - auto process_segment = [&] (frg::string_view s_view) -> int { - if(debugPathResolution) + auto process_segment = [&](frg::string_view s_view) -> int { + if (debugPathResolution) mlibc::infoLogger() << "mlibc realpath(): resolv is '" << resolv.data() << "'" - << ", segment is " << s_view.data() - << ", size: " << s_view.size() << frg::endlog; + << ", segment is " << s_view.data() << ", size: " << s_view.size() + << frg::endlog; - if(!s_view.size() || s_view == ".") { + if (!s_view.size() || s_view == ".") { // Keep resolv invariant. return 0; - }else if(s_view == "..") { + } else if (s_view == "..") { // Remove a single segment from resolv. - if(resolv.size() > 1) { + if (resolv.size() > 1) { auto slash = strrchr(resolv.data(), '/'); __ensure(slash); // We never remove the leading sla. resolv.resize((slash - resolv.data()) + 1); @@ -324,25 +309,27 @@ char *realpath(const char *path, char *out) { resolv[rsz + s_view.size()] = 0; // stat() the path to (1) see if it exists and (2) see if it is a link. - if(!mlibc::sys_stat) { + if (!mlibc::sys_stat) { MLIBC_MISSING_SYSDEP(); return ENOSYS; } - if(debugPathResolution) - mlibc::infoLogger() << "mlibc realpath(): stat()ing '" - << resolv.data() << "'" << frg::endlog; + if (debugPathResolution) + mlibc::infoLogger() << "mlibc realpath(): stat()ing '" << resolv.data() << "'" + << frg::endlog; struct stat st; - if(int e = mlibc::sys_stat(mlibc::fsfd_target::path, - -1, resolv.data(), AT_SYMLINK_NOFOLLOW, &st); e) + if (int e = mlibc::sys_stat( + mlibc::fsfd_target::path, -1, resolv.data(), AT_SYMLINK_NOFOLLOW, &st + ); + e) return e; - if(S_ISLNK(st.st_mode)) { - if(debugPathResolution) { - mlibc::infoLogger() << "mlibc realpath(): Encountered symlink '" - << resolv.data() << "'" << frg::endlog; + if (S_ISLNK(st.st_mode)) { + if (debugPathResolution) { + mlibc::infoLogger() << "mlibc realpath(): Encountered symlink '" << resolv.data() + << "'" << frg::endlog; } - if(!mlibc::sys_readlink) { + if (!mlibc::sys_readlink) { MLIBC_MISSING_SYSDEP(); return ENOSYS; } @@ -353,25 +340,26 @@ char *realpath(const char *path, char *out) { if (int e = mlibc::sys_readlink(resolv.data(), path, 512, &sz); e) return e; - if(debugPathResolution) { - mlibc::infoLogger() << "mlibc realpath(): Symlink resolves to '" - << frg::string_view{path, static_cast(sz)} << "'" << frg::endlog; + if (debugPathResolution) { + mlibc::infoLogger() + << "mlibc realpath(): Symlink resolves to '" + << frg::string_view{path, static_cast(sz)} << "'" << frg::endlog; } if (path[0] == '/') { // Absolute path, replace resolv // Ignore any trailing '/' so all results will not have one to keep consistency. - while(sz > 1 && path[sz - 1] == '/') + while (sz > 1 && path[sz - 1] == '/') sz -= 1; resolv.resize(sz + 1); strncpy(resolv.data(), path, sz); resolv.data()[sz] = 0; - if(debugPathResolution) { + if (debugPathResolution) { mlibc::infoLogger() << "mlibc realpath(): Symlink is absolute, resolv: '" - << resolv.data() << "'" << frg::endlog; + << resolv.data() << "'" << frg::endlog; } } else { // Relative path, revert changes to resolv, prepend to lnk @@ -386,10 +374,11 @@ char *realpath(const char *path, char *out) { ls = 0; - if(debugPathResolution) { - mlibc::infoLogger() << "mlibc realpath(): Symlink is relative, resolv: '" - << resolv.data() << "' lnk: '" - << frg::string_view{lnk.data(), lnk.size()} << "'" << frg::endlog; + if (debugPathResolution) { + mlibc::infoLogger() + << "mlibc realpath(): Symlink is relative, resolv: '" << resolv.data() + << "' lnk: '" << frg::string_view{lnk.data(), lnk.size()} << "'" + << frg::endlog; } } } @@ -400,33 +389,35 @@ char *realpath(const char *path, char *out) { // Each iteration of this outer loop consumes segment of the input path. // This design avoids copying the input path into lnk; // the latter could often involve additional allocations. - while(ps < path_view.size()) { + while (ps < path_view.size()) { frg::string_view ps_view; - if(auto slash = strchr(path + ps, '/'); slash) { + if (auto slash = strchr(path + ps, '/'); slash) { ps_view = frg::string_view{path + ps, static_cast(slash - (path + ps))}; - }else{ + } else { ps_view = frg::string_view{path + ps, strlen(path) - ps}; } ps += ps_view.size() + 1; // Handle one segment from the input path. - if(int e = process_segment(ps_view); e) { + if (int e = process_segment(ps_view); e) { errno = e; return nullptr; } // This inner loop consumes segments of lnk. - while(ls < lnk.size()) { + while (ls < lnk.size()) { frg::string_view ls_view; - if(auto slash = strchr(lnk.data() + ls, '/'); slash) { - ls_view = frg::string_view{lnk.data() + ls, static_cast(slash - (lnk.data() + ls))}; - }else{ + if (auto slash = strchr(lnk.data() + ls, '/'); slash) { + ls_view = frg::string_view{ + lnk.data() + ls, static_cast(slash - (lnk.data() + ls)) + }; + } else { ls_view = frg::string_view{lnk.data() + ls, strlen(lnk.data()) - ls}; } ls += ls_view.size() + 1; // Handle one segment from the link - if(int e = process_segment(ls_view); e) { + if (int e = process_segment(ls_view); e) { errno = e; return nullptr; } @@ -437,21 +428,21 @@ char *realpath(const char *path, char *out) { ls = 0; } - if(resolv.size() == 1) { + if (resolv.size() == 1) { resolv.resize(0); resolv.push_back('/'); resolv.push_back(0); } - if(debugPathResolution) + if (debugPathResolution) mlibc::infoLogger() << "mlibc realpath(): Returns '" << resolv.data() << "'" << frg::endlog; - if(resolv.size() > PATH_MAX) { + if (resolv.size() > PATH_MAX) { errno = ENAMETOOLONG; return nullptr; } - if(!out) + if (!out) out = reinterpret_cast(getAllocator().allocate(resolv.size())); strcpy(out, resolv.data()); return out; @@ -464,7 +455,7 @@ char *realpath(const char *path, char *out) { int ptsname_r(int fd, char *buffer, size_t length) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ptsname, ENOSYS); - if(int e = sysdep(fd, buffer, length); e) + if (int e = sysdep(fd, buffer, length); e) return e; return 0; @@ -475,7 +466,7 @@ char *ptsname(int fd) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ptsname, NULL); - if(int e = sysdep(fd, buffer, 128); e) { + if (int e = sysdep(fd, buffer, 128); e) { errno = e; return NULL; } @@ -485,7 +476,7 @@ char *ptsname(int fd) { int posix_openpt(int flags) { int fd; - if(int e = mlibc::sys_open("/dev/ptmx", flags, 0, &fd); e) { + if (int e = mlibc::sys_open("/dev/ptmx", flags, 0, &fd); e) { errno = e; return -1; } @@ -496,7 +487,7 @@ int posix_openpt(int flags) { int unlockpt(int fd) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_unlockpt, -1); - if(int e = sysdep(fd); e) { + if (int e = sysdep(fd); e) { errno = e; return -1; } @@ -504,16 +495,14 @@ int unlockpt(int fd) { return 0; } -int grantpt(int) { - return 0; -} +int grantpt(int) { return 0; } -double strtod_l(const char *__restrict__ nptr, char ** __restrict__ endptr, locale_t) { +double strtod_l(const char *__restrict__ nptr, char **__restrict__ endptr, locale_t) { mlibc::infoLogger() << "mlibc: strtod_l ignores locale!" << frg::endlog; return strtod(nptr, endptr); } -long double strtold_l(const char *__restrict__, char ** __restrict__, locale_t) { +long double strtold_l(const char *__restrict__, char **__restrict__, locale_t) { __ensure(!"Not implemented"); __builtin_unreachable(); } @@ -546,7 +535,7 @@ char *secure_getenv(const char *name) { } void *reallocarray(void *ptr, size_t m, size_t n) { - if(n && m > -1 / n) { + if (n && m > -1 / n) { errno = ENOMEM; return 0; } @@ -554,6 +543,4 @@ void *reallocarray(void *ptr, size_t m, size_t n) { return realloc(ptr, m * n); } -char *canonicalize_file_name(const char *name) { - return realpath(name, NULL); -} +char *canonicalize_file_name(const char *name) { return realpath(name, NULL); } diff --git a/options/posix/generic/posix_string.cpp b/options/posix/generic/posix_string.cpp index 838b85b012..3778bb68bc 100644 --- a/options/posix/generic/posix_string.cpp +++ b/options/posix/generic/posix_string.cpp @@ -3,10 +3,10 @@ #endif #include +#include #include #include #include -#include #include @@ -14,7 +14,7 @@ char *strdup(const char *string) { auto num_bytes = strlen(string); char *new_string = (char *)malloc(num_bytes + 1); - if(!new_string) // TODO: set errno + if (!new_string) // TODO: set errno return nullptr; memcpy(new_string, string, num_bytes); @@ -25,7 +25,7 @@ char *strdup(const char *string) { char *strndup(const char *string, size_t max_size) { auto num_bytes = strnlen(string, max_size); char *new_string = (char *)malloc(num_bytes + 1); - if(!new_string) // TODO: set errno + if (!new_string) // TODO: set errno return nullptr; memcpy(new_string, string, num_bytes); @@ -56,7 +56,7 @@ char *stpncpy(char *__restrict dest, const char *__restrict src, size_t n) { size_t strnlen(const char *s, size_t n) { size_t len = 0; - while(len < n && s[len]) + while (len < n && s[len]) ++len; return len; } @@ -65,58 +65,61 @@ char *strsep(char **m, const char *del) { __ensure(m); auto tok = *m; - if(!tok) + if (!tok) return nullptr; // Replace the following delimiter by a null-terminator. // After this loop: *p is null iff we reached the end of the string. auto p = tok; - while(*p && !strchr(del, *p)) + while (*p && !strchr(del, *p)) p++; - if(*p) { + if (*p) { *p = 0; *m = p + 1; - }else{ + } else { *m = nullptr; } return tok; } char *strsignal(int sig) { - #define CASE_FOR(sigconst) case sigconst: s = #sigconst; break; +#define CASE_FOR(sigconst) \ + case sigconst: \ + s = #sigconst; \ + break; const char *s; - switch(sig) { - CASE_FOR(SIGABRT) - CASE_FOR(SIGFPE) - CASE_FOR(SIGILL) - CASE_FOR(SIGINT) - CASE_FOR(SIGSEGV) - CASE_FOR(SIGTERM) - CASE_FOR(SIGPROF) - CASE_FOR(SIGIO) - CASE_FOR(SIGPWR) - CASE_FOR(SIGALRM) - CASE_FOR(SIGBUS) - CASE_FOR(SIGCHLD) - CASE_FOR(SIGCONT) - CASE_FOR(SIGHUP) - CASE_FOR(SIGKILL) - CASE_FOR(SIGPIPE) - CASE_FOR(SIGQUIT) - CASE_FOR(SIGSTOP) - CASE_FOR(SIGTSTP) - CASE_FOR(SIGTTIN) - CASE_FOR(SIGTTOU) - CASE_FOR(SIGUSR1) - CASE_FOR(SIGUSR2) - CASE_FOR(SIGSYS) - CASE_FOR(SIGTRAP) - CASE_FOR(SIGURG) - CASE_FOR(SIGVTALRM) - CASE_FOR(SIGXCPU) - CASE_FOR(SIGXFSZ) - CASE_FOR(SIGWINCH) + switch (sig) { + CASE_FOR(SIGABRT) + CASE_FOR(SIGFPE) + CASE_FOR(SIGILL) + CASE_FOR(SIGINT) + CASE_FOR(SIGSEGV) + CASE_FOR(SIGTERM) + CASE_FOR(SIGPROF) + CASE_FOR(SIGIO) + CASE_FOR(SIGPWR) + CASE_FOR(SIGALRM) + CASE_FOR(SIGBUS) + CASE_FOR(SIGCHLD) + CASE_FOR(SIGCONT) + CASE_FOR(SIGHUP) + CASE_FOR(SIGKILL) + CASE_FOR(SIGPIPE) + CASE_FOR(SIGQUIT) + CASE_FOR(SIGSTOP) + CASE_FOR(SIGTSTP) + CASE_FOR(SIGTTIN) + CASE_FOR(SIGTTOU) + CASE_FOR(SIGUSR1) + CASE_FOR(SIGUSR2) + CASE_FOR(SIGSYS) + CASE_FOR(SIGTRAP) + CASE_FOR(SIGURG) + CASE_FOR(SIGVTALRM) + CASE_FOR(SIGXCPU) + CASE_FOR(SIGXFSZ) + CASE_FOR(SIGWINCH) default: mlibc::infoLogger() << "mlibc: Unknown signal number " << sig << frg::endlog; s = "Unknown signal number"; @@ -127,9 +130,9 @@ char *strsignal(int sig) { char *strcasestr(const char *s, const char *pattern) { size_t plen = strlen(pattern); const char *p = s; - while(*p) { + while (*p) { // Need strncasecmp() to avoid checking past the end of a successful match. - if(!strncasecmp(p, pattern, plen)) + if (!strncasecmp(p, pattern, plen)) return const_cast(p); ++p; } @@ -145,8 +148,8 @@ void *memccpy(void *__restrict, const void *__restrict, int, size_t) { void *memrchr(const void *m, int c, size_t n) { const unsigned char *s = (const unsigned char *)m; c = (unsigned char)c; - while(n--) { - if(s[n] == c) + while (n--) { + if (s[n] == c) return (void *)(s + n); } return 0; @@ -162,17 +165,18 @@ char *strerror_l(int errnum, locale_t) { size_t strlcpy(char *d, const char *s, size_t n) { char *d0 = d; - if(!n--) + if (!n--) goto finish; - for(; n && (*d=*s); n--, s++, d++); + for (; n && (*d = *s); n--, s++, d++) + ; *d = 0; finish: - return d-d0 + strlen(s); + return d - d0 + strlen(s); } size_t strlcat(char *d, const char *s, size_t n) { size_t l = strnlen(d, n); - if(l == n) { + if (l == n) { return l + strlen(s); } return l + strlcpy(d + l, s, n - l); diff --git a/options/posix/generic/posix_time.cpp b/options/posix/generic/posix_time.cpp index 68ccbc5509..0fe6da5cd7 100644 --- a/options/posix/generic/posix_time.cpp +++ b/options/posix/generic/posix_time.cpp @@ -1,8 +1,8 @@ #include -#include #include -#include +#include #include +#include #include int timer_getoverrun(timer_t) { @@ -13,7 +13,7 @@ int timer_getoverrun(timer_t) { int utimes(const char *filename, const struct timeval times[2]) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_utimensat, -1); struct timespec time[2]; - if(times == nullptr) { + if (times == nullptr) { time[0].tv_sec = UTIME_NOW; time[0].tv_nsec = UTIME_NOW; time[1].tv_sec = UTIME_NOW; @@ -41,7 +41,7 @@ int futimes(int, const struct timeval[2]) { int lutimes(const char *filename, const struct timeval tv[2]) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_utimensat, -1); struct timespec time[2]; - if(tv == nullptr) { + if (tv == nullptr) { time[0].tv_sec = UTIME_NOW; time[0].tv_nsec = UTIME_NOW; time[1].tv_sec = UTIME_NOW; diff --git a/options/posix/generic/pthread.cpp b/options/posix/generic/pthread.cpp index 87ffed11f7..5daaf77665 100644 --- a/options/posix/generic/pthread.cpp +++ b/options/posix/generic/pthread.cpp @@ -1,13 +1,13 @@ +#include +#include +#include #include #include #include #include #include -#include #include -#include -#include #include #include @@ -15,30 +15,31 @@ #include #include #include -#include #include -#include +#include #include +#include static bool enableTrace = false; struct ScopeTrace { ScopeTrace(const char *file, int line, const char *function) - : _file(file), _line(line), _function(function) { - if(!enableTrace) + : _file(file), + _line(line), + _function(function) { + if (!enableTrace) return; - mlibc::infoLogger() << "trace: Enter scope " - << _file << ":" << _line << " (in function " - << _function << ")" << frg::endlog; + mlibc::infoLogger() << "trace: Enter scope " << _file << ":" << _line << " (in function " + << _function << ")" << frg::endlog; } ~ScopeTrace() { - if(!enableTrace) + if (!enableTrace) return; mlibc::infoLogger() << "trace: Exit scope" << frg::endlog; } -private: + private: const char *_file; int _line; const char *_function; @@ -74,17 +75,14 @@ int pthread_attr_init(pthread_attr_t *attr) { return 0; } -int pthread_attr_destroy(pthread_attr_t *) { - return 0; -} +int pthread_attr_destroy(pthread_attr_t *) { return 0; } int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate) { *detachstate = attr->__mlibc_detachstate; return 0; } int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate) { - if (detachstate != PTHREAD_CREATE_DETACHED && - detachstate != PTHREAD_CREATE_JOINABLE) + if (detachstate != PTHREAD_CREATE_DETACHED && detachstate != PTHREAD_CREATE_JOINABLE) return EINVAL; attr->__mlibc_detachstate = detachstate; @@ -139,8 +137,7 @@ int pthread_attr_getscope(const pthread_attr_t *attr, int *scope) { return 0; } int pthread_attr_setscope(pthread_attr_t *attr, int scope) { - if (scope != PTHREAD_SCOPE_SYSTEM && - scope != PTHREAD_SCOPE_PROCESS) + if (scope != PTHREAD_SCOPE_SYSTEM && scope != PTHREAD_SCOPE_PROCESS) return EINVAL; if (scope == PTHREAD_SCOPE_PROCESS) return ENOTSUP; @@ -153,18 +150,21 @@ int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched) return 0; } int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched) { - if (inheritsched != PTHREAD_INHERIT_SCHED && - inheritsched != PTHREAD_EXPLICIT_SCHED) + if (inheritsched != PTHREAD_INHERIT_SCHED && inheritsched != PTHREAD_EXPLICIT_SCHED) return EINVAL; attr->__mlibc_inheritsched = inheritsched; return 0; } -int pthread_attr_getschedparam(const pthread_attr_t *__restrict attr, struct sched_param *__restrict schedparam) { +int pthread_attr_getschedparam( + const pthread_attr_t *__restrict attr, struct sched_param *__restrict schedparam +) { *schedparam = attr->__mlibc_schedparam; return 0; } -int pthread_attr_setschedparam(pthread_attr_t *__restrict attr, const struct sched_param *__restrict schedparam) { +int pthread_attr_setschedparam( + pthread_attr_t *__restrict attr, const struct sched_param *__restrict schedparam +) { // TODO: this is supposed to return EINVAL for when the schedparam doesn't make sense // for the given schedpolicy. attr->__mlibc_schedparam = *schedparam; @@ -176,16 +176,16 @@ int pthread_attr_getschedpolicy(const pthread_attr_t *__restrict attr, int *__re return 0; } int pthread_attr_setschedpolicy(pthread_attr_t *__restrict attr, int policy) { - if (policy != SCHED_FIFO && policy != SCHED_RR && - policy != SCHED_OTHER) + if (policy != SCHED_FIFO && policy != SCHED_RR && policy != SCHED_OTHER) return EINVAL; attr->__mlibc_schedpolicy = policy; return 0; } #if __MLIBC_LINUX_OPTION -int pthread_attr_getaffinity_np(const pthread_attr_t *__restrict attr, - size_t cpusetsize, cpu_set_t *__restrict cpusetp) { +int pthread_attr_getaffinity_np( + const pthread_attr_t *__restrict attr, size_t cpusetsize, cpu_set_t *__restrict cpusetp +) { if (!attr) return EINVAL; @@ -195,19 +195,19 @@ int pthread_attr_getaffinity_np(const pthread_attr_t *__restrict attr, } for (size_t cnt = cpusetsize; cnt < attr->__mlibc_cpusetsize; cnt++) - if (reinterpret_cast(attr->__mlibc_cpuset)[cnt] != '\0') + if (reinterpret_cast(attr->__mlibc_cpuset)[cnt] != '\0') return ERANGE; - auto p = memcpy(cpusetp, attr->__mlibc_cpuset, - std::min(cpusetsize, attr->__mlibc_cpusetsize)); + auto p = memcpy(cpusetp, attr->__mlibc_cpuset, std::min(cpusetsize, attr->__mlibc_cpusetsize)); if (cpusetsize > attr->__mlibc_cpusetsize) memset(p, '\0', cpusetsize - attr->__mlibc_cpusetsize); return 0; } -int pthread_attr_setaffinity_np(pthread_attr_t *__restrict attr, - size_t cpusetsize, const cpu_set_t *__restrict cpusetp) { +int pthread_attr_setaffinity_np( + pthread_attr_t *__restrict attr, size_t cpusetsize, const cpu_set_t *__restrict cpusetp +) { if (!attr) return EINVAL; @@ -222,7 +222,7 @@ int pthread_attr_setaffinity_np(pthread_attr_t *__restrict attr, if (!newp) return ENOMEM; - attr->__mlibc_cpuset = static_cast(newp); + attr->__mlibc_cpuset = static_cast(newp); attr->__mlibc_cpusetsize = cpusetsize; } @@ -230,8 +230,8 @@ int pthread_attr_setaffinity_np(pthread_attr_t *__restrict attr, return 0; } -int pthread_attr_getsigmask_np(const pthread_attr_t *__restrict attr, - sigset_t *__restrict sigmask) { +int +pthread_attr_getsigmask_np(const pthread_attr_t *__restrict attr, sigset_t *__restrict sigmask) { if (!attr) return EINVAL; @@ -244,8 +244,8 @@ int pthread_attr_getsigmask_np(const pthread_attr_t *__restrict attr, return 0; } -int pthread_attr_setsigmask_np(pthread_attr_t *__restrict attr, - const sigset_t *__restrict sigmask) { +int +pthread_attr_setsigmask_np(pthread_attr_t *__restrict attr, const sigset_t *__restrict sigmask) { if (!attr) return EINVAL; @@ -264,35 +264,36 @@ int pthread_attr_setsigmask_np(pthread_attr_t *__restrict attr, } namespace { - void get_own_stackinfo(void **stack_addr, size_t *stack_size) { - auto fp = fopen("/proc/self/maps", "r"); - if (!fp) { - mlibc::infoLogger() << "mlibc pthreads: /proc/self/maps does not exist! Producing incorrect" - " stack results!" << frg::endlog; - return; - } +void get_own_stackinfo(void **stack_addr, size_t *stack_size) { + auto fp = fopen("/proc/self/maps", "r"); + if (!fp) { + mlibc::infoLogger() << "mlibc pthreads: /proc/self/maps does not exist! Producing incorrect" + " stack results!" + << frg::endlog; + return; + } - char line[256]; - auto sp = mlibc::get_sp(); - while (fgets(line, 256, fp)) { - uintptr_t from, to; - if(sscanf(line, "%" SCNxPTR "-%" SCNxPTR, &from, &to) != 2) - continue; - if (sp < to && sp > from) { - // We need to return the lowest byte of the stack. - *stack_addr = reinterpret_cast(from); - *stack_size = to - from; - fclose(fp); - return; - } + char line[256]; + auto sp = mlibc::get_sp(); + while (fgets(line, 256, fp)) { + uintptr_t from, to; + if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR, &from, &to) != 2) + continue; + if (sp < to && sp > from) { + // We need to return the lowest byte of the stack. + *stack_addr = reinterpret_cast(from); + *stack_size = to - from; + fclose(fp); + return; } - - fclose(fp); } + + fclose(fp); } +} // namespace int pthread_getattr_np(pthread_t thread, pthread_attr_t *attr) { - auto tcb = reinterpret_cast(thread); + auto tcb = reinterpret_cast(thread); *attr = pthread_attr_t{}; if (!tcb->stackAddr || !tcb->stackSize) { @@ -310,57 +311,56 @@ int pthread_getattr_np(pthread_t thread, pthread_attr_t *attr) { int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t *mask) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getthreadaffinity, ENOSYS); - return mlibc::sys_getthreadaffinity(reinterpret_cast(thread)->tid, cpusetsize, mask); + return mlibc::sys_getthreadaffinity(reinterpret_cast(thread)->tid, cpusetsize, mask); } int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize, const cpu_set_t *mask) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setthreadaffinity, ENOSYS); - return mlibc::sys_setthreadaffinity(reinterpret_cast(thread)->tid, cpusetsize, mask); + return mlibc::sys_setthreadaffinity(reinterpret_cast(thread)->tid, cpusetsize, mask); } #endif // __MLIBC_LINUX_OPTION extern "C" Tcb *__rtld_allocateTcb(); // pthread functions. -int pthread_create(pthread_t *__restrict thread, const pthread_attr_t *__restrict attrp, - void *(*entry) (void *), void *__restrict user_arg) { +int pthread_create( + pthread_t *__restrict thread, + const pthread_attr_t *__restrict attrp, + void *(*entry)(void *), + void *__restrict user_arg +) { return mlibc::thread_create(thread, attrp, reinterpret_cast(entry), user_arg, false); } -pthread_t pthread_self(void) { - return reinterpret_cast(mlibc::get_current_tcb()); -} +pthread_t pthread_self(void) { return reinterpret_cast(mlibc::get_current_tcb()); } int pthread_equal(pthread_t t1, pthread_t t2) { - if(t1 == t2) + if (t1 == t2) return 1; return 0; } namespace { - struct key_global_info { - bool in_use; +struct key_global_info { + bool in_use; - void (*dtor)(void *); - uint64_t generation; - }; + void (*dtor)(void *); + uint64_t generation; +}; - constinit frg::array< - key_global_info, - PTHREAD_KEYS_MAX - > key_globals_{}; +constinit frg::array key_globals_{}; - FutexLock key_mutex_; -} +FutexLock key_mutex_; +} // namespace namespace mlibc { - __attribute__ ((__noreturn__)) void do_exit() { - sys_thread_exit(); - __builtin_unreachable(); - } +__attribute__((__noreturn__)) void do_exit() { + sys_thread_exit(); + __builtin_unreachable(); } +} // namespace mlibc -__attribute__ ((__noreturn__)) void pthread_exit(void *ret_val) { +__attribute__((__noreturn__)) void pthread_exit(void *ret_val) { auto self = mlibc::get_current_tcb(); if (__atomic_load_n(&self->cancelBits, __ATOMIC_RELAXED) & tcbExitingBit) @@ -401,24 +401,23 @@ __attribute__ ((__noreturn__)) void pthread_exit(void *ret_val) { mlibc::do_exit(); } -int pthread_join(pthread_t thread, void **ret) { - return mlibc::thread_join(thread, ret); -} +int pthread_join(pthread_t thread, void **ret) { return mlibc::thread_join(thread, ret); } int pthread_detach(pthread_t thread) { - auto tcb = reinterpret_cast(thread); + auto tcb = reinterpret_cast(thread); if (!__atomic_load_n(&tcb->isJoinable, __ATOMIC_RELAXED)) return EINVAL; int expected = 1; - if(!__atomic_compare_exchange_n(&tcb->isJoinable, &expected, 0, false, __ATOMIC_RELEASE, - __ATOMIC_RELAXED)) + if (!__atomic_compare_exchange_n( + &tcb->isJoinable, &expected, 0, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED + )) return EINVAL; return 0; } -void pthread_cleanup_push(void (*func) (void *), void *arg) { +void pthread_cleanup_push(void (*func)(void *), void *arg) { auto self = mlibc::get_current_tcb(); auto hand = frg::construct(getAllocator()); @@ -453,10 +452,10 @@ void pthread_cleanup_pop(int execute) { } int pthread_setname_np(pthread_t thread, const char *name) { - auto tcb = reinterpret_cast(thread); + auto tcb = reinterpret_cast(thread); auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_thread_setname, ENOSYS); - if(int e = sysdep(tcb, name); e) { + if (int e = sysdep(tcb, name); e) { return e; } @@ -464,10 +463,10 @@ int pthread_setname_np(pthread_t thread, const char *name) { } int pthread_getname_np(pthread_t thread, char *name, size_t size) { - auto tcb = reinterpret_cast(thread); + auto tcb = reinterpret_cast(thread); auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_thread_getname, ENOSYS); - if(int e = sysdep(tcb, name, size); e) { + if (int e = sysdep(tcb, name, size); e) { return e; } @@ -475,10 +474,10 @@ int pthread_getname_np(pthread_t thread, char *name, size_t size) { } int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param) { - auto tcb = reinterpret_cast(thread); + auto tcb = reinterpret_cast(thread); MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setschedparam, ENOSYS); - if(int e = mlibc::sys_setschedparam(tcb, policy, param); e) { + if (int e = mlibc::sys_setschedparam(tcb, policy, param); e) { return e; } @@ -486,80 +485,85 @@ int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param } int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param) { - auto tcb = reinterpret_cast(thread); + auto tcb = reinterpret_cast(thread); MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getschedparam, ENOSYS); - if(int e = mlibc::sys_getschedparam(tcb, policy, param); e) { + if (int e = mlibc::sys_getschedparam(tcb, policy, param); e) { return e; } return 0; } -//pthread cancel functions +// pthread cancel functions extern "C" void __mlibc_do_cancel() { - //TODO(geert): for now the same as pthread_exit() + // TODO(geert): for now the same as pthread_exit() pthread_exit(PTHREAD_CANCELED); } namespace { - void sigcancel_handler(int signal, siginfo_t *info, void *ucontext) { - ucontext_t *uctx = static_cast(ucontext); - // The function could be called from other signals, or from another - // process, in which case we should do nothing. - if (signal != SIGCANCEL || info->si_pid != getpid() || - info->si_code != SI_TKILL) - return; +void sigcancel_handler(int signal, siginfo_t *info, void *ucontext) { + ucontext_t *uctx = static_cast(ucontext); + // The function could be called from other signals, or from another + // process, in which case we should do nothing. + if (signal != SIGCANCEL || info->si_pid != getpid() || info->si_code != SI_TKILL) + return; + + auto tcb = reinterpret_cast(mlibc::get_current_tcb()); + int old_value = tcb->cancelBits; + + /* + * When a thread is marked with deferred cancellation and performs a blocking syscall, + * the spec mandates that the syscall can get interrupted before it has caused any side + * effects (e.g. before a read() has read any bytes from disk). If the syscall has + * already caused side effects it should return its partial work, and set the program + * counter just after the syscall. If the syscall hasn't caused any side effects, it + * should fail with EINTR and set the program counter to the syscall instruction. + * + * cancellable_syscall: + * test whether_a_cancel_is_queued + * je cancel + * syscall + * end_cancellable_syscall + * + * The mlibc::sys_before_cancellable_syscall sysdep should return 1 when the + * program counter is between the 'canellable_syscall' and 'end_cancellable_syscall' label. + */ + if (!(old_value & tcbCancelAsyncBit) && mlibc::sys_before_cancellable_syscall && + !mlibc::sys_before_cancellable_syscall(uctx)) + return; + + int bitmask = tcbCancelTriggerBit | tcbCancelingBit; + while (1) { + int new_value = old_value | bitmask; - auto tcb = reinterpret_cast(mlibc::get_current_tcb()); - int old_value = tcb->cancelBits; - - /* - * When a thread is marked with deferred cancellation and performs a blocking syscall, - * the spec mandates that the syscall can get interrupted before it has caused any side - * effects (e.g. before a read() has read any bytes from disk). If the syscall has - * already caused side effects it should return its partial work, and set the program - * counter just after the syscall. If the syscall hasn't caused any side effects, it - * should fail with EINTR and set the program counter to the syscall instruction. - * - * cancellable_syscall: - * test whether_a_cancel_is_queued - * je cancel - * syscall - * end_cancellable_syscall - * - * The mlibc::sys_before_cancellable_syscall sysdep should return 1 when the - * program counter is between the 'canellable_syscall' and 'end_cancellable_syscall' label. - */ - if (!(old_value & tcbCancelAsyncBit) && - mlibc::sys_before_cancellable_syscall && !mlibc::sys_before_cancellable_syscall(uctx)) + // Check if we are already cancelled or exiting + if (old_value == new_value || old_value & tcbExitingBit) return; - int bitmask = tcbCancelTriggerBit | tcbCancelingBit; - while (1) { - int new_value = old_value | bitmask; - - // Check if we are already cancelled or exiting - if (old_value == new_value || old_value & tcbExitingBit) - return; - - int current_value = old_value; - if (__atomic_compare_exchange_n(&tcb->cancelBits, ¤t_value, - new_value, true,__ATOMIC_RELAXED, __ATOMIC_RELAXED)) { - tcb->returnValue.voidPtr = PTHREAD_CANCELED; - - // Perform cancellation - __mlibc_do_cancel(); - - break; - } + int current_value = old_value; + if (__atomic_compare_exchange_n( + &tcb->cancelBits, + ¤t_value, + new_value, + true, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) { + tcb->returnValue.voidPtr = PTHREAD_CANCELED; + + // Perform cancellation + __mlibc_do_cancel(); - old_value = current_value; + break; } + + old_value = current_value; } } +} // namespace namespace mlibc { namespace { @@ -570,10 +574,10 @@ struct PthreadSignalInstaller { sa.sa_sigaction = sigcancel_handler; sa.sa_flags = SA_SIGINFO; auto e = ENOSYS; - if(sys_sigaction) + if (sys_sigaction) e = sys_sigaction(SIGCANCEL, &sa, NULL); // Opt-out of cancellation support. - if(e == ENOSYS) + if (e == ENOSYS) return; __ensure(!e); } @@ -596,17 +600,23 @@ int pthread_setcanceltype(int type, int *oldtype) { new_value |= tcbCancelAsyncBit; if (oldtype) - *oldtype = ((old_value & tcbCancelAsyncBit) - ? PTHREAD_CANCEL_ASYNCHRONOUS - : PTHREAD_CANCEL_DEFERRED); + *oldtype = + ((old_value & tcbCancelAsyncBit) ? PTHREAD_CANCEL_ASYNCHRONOUS + : PTHREAD_CANCEL_DEFERRED); // Avoid unecessary atomic op. if (old_value == new_value) break; int current_value = old_value; - if (__atomic_compare_exchange_n(&self->cancelBits, ¤t_value, - new_value, true, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) { + if (__atomic_compare_exchange_n( + &self->cancelBits, + ¤t_value, + new_value, + true, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) { if (mlibc::tcb_async_cancelled(new_value)) __mlibc_do_cancel(); @@ -631,17 +641,22 @@ int pthread_setcancelstate(int state, int *oldstate) { new_value |= tcbCancelEnableBit; if (oldstate) - *oldstate = ((old_value & tcbCancelEnableBit) - ? PTHREAD_CANCEL_ENABLE - : PTHREAD_CANCEL_DISABLE); + *oldstate = + ((old_value & tcbCancelEnableBit) ? PTHREAD_CANCEL_ENABLE : PTHREAD_CANCEL_DISABLE); // Avoid unecessary atomic op. if (old_value == new_value) break; int current_value = old_value; - if (__atomic_compare_exchange_n(&self->cancelBits, ¤t_value, - new_value, true, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) { + if (__atomic_compare_exchange_n( + &self->cancelBits, + ¤t_value, + new_value, + true, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) { if (mlibc::tcb_async_cancelled(new_value)) __mlibc_do_cancel(); @@ -688,8 +703,14 @@ int pthread_cancel(pthread_t thread) { break; int current_value = old_value; - if (__atomic_compare_exchange_n(&tcb->cancelBits, ¤t_value, - new_value, true, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) { + if (__atomic_compare_exchange_n( + &tcb->cancelBits, + ¤t_value, + new_value, + true, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) { if (mlibc::tcb_cancel_enabled(new_value)) { pid_t pid = getpid(); @@ -715,7 +736,7 @@ int pthread_cancel(pthread_t thread) { return 0; } -int pthread_atfork(void (*prepare) (void), void (*parent) (void), void (*child) (void)) { +int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)) { auto self = mlibc::get_current_tcb(); auto hand = frg::construct(getAllocator()); @@ -821,35 +842,42 @@ int pthread_setspecific(pthread_key_t key, const void *value) { static constexpr unsigned int onceComplete = 1; static constexpr unsigned int onceLocked = 2; -int pthread_once(pthread_once_t *once, void (*function) (void)) { +int pthread_once(pthread_once_t *once, void (*function)(void)) { SCOPE_TRACE(); auto expected = __atomic_load_n(&once->__mlibc_done, __ATOMIC_ACQUIRE); // fast path: the function was already run. - while(!(expected & onceComplete)) { - if(!expected) { + while (!(expected & onceComplete)) { + if (!expected) { // try to acquire the mutex. - if(!__atomic_compare_exchange_n(&once->__mlibc_done, - &expected, onceLocked, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) + if (!__atomic_compare_exchange_n( + &once->__mlibc_done, + &expected, + onceLocked, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )) continue; function(); // unlock the mutex. __atomic_exchange_n(&once->__mlibc_done, onceComplete, __ATOMIC_RELEASE); - if(int e = mlibc::sys_futex_wake((int *)&once->__mlibc_done); e) + if (int e = mlibc::sys_futex_wake((int *)&once->__mlibc_done); e) __ensure(!"sys_futex_wake() failed"); return 0; - }else{ + } else { // a different thread is currently running the initializer. __ensure(expected == onceLocked); // if the wait gets interrupted by a signal, check again. // EAGAIN will also be a retry, as it means the other thread completed // and changed the __mlibc_done variable to signal it before we actually went to sleep. - if(int e = mlibc::sys_futex_wait((int *)&once->__mlibc_done, onceLocked, nullptr); e && e != EINTR && e != EAGAIN) + if (int e = mlibc::sys_futex_wait((int *)&once->__mlibc_done, onceLocked, nullptr); + e && e != EINTR && e != EAGAIN) __ensure(!"sys_futex_wait() failed"); - expected = __atomic_load_n(&once->__mlibc_done, __ATOMIC_ACQUIRE); + expected = __atomic_load_n(&once->__mlibc_done, __ATOMIC_ACQUIRE); } } @@ -879,8 +907,8 @@ int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type) { return mlibc::thread_mutexattr_settype(attr, type); } -int pthread_mutexattr_getrobust(const pthread_mutexattr_t *__restrict attr, - int *__restrict robust) { +int +pthread_mutexattr_getrobust(const pthread_mutexattr_t *__restrict attr, int *__restrict robust) { *robust = attr->__mlibc_robust; return 0; } @@ -904,23 +932,25 @@ int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared) { return 0; } -int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *__restrict attr, - int *__restrict protocol) { +int pthread_mutexattr_getprotocol( + const pthread_mutexattr_t *__restrict attr, int *__restrict protocol +) { *protocol = attr->__mlibc_protocol; return 0; } int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol) { - if (protocol != PTHREAD_PRIO_NONE && protocol != PTHREAD_PRIO_INHERIT - && protocol != PTHREAD_PRIO_PROTECT) + if (protocol != PTHREAD_PRIO_NONE && protocol != PTHREAD_PRIO_INHERIT && + protocol != PTHREAD_PRIO_PROTECT) return EINVAL; attr->__mlibc_protocol = protocol; return 0; } -int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *__restrict attr, - int *__restrict prioceiling) { +int pthread_mutexattr_getprioceiling( + const pthread_mutexattr_t *__restrict attr, int *__restrict prioceiling +) { (void)attr; (void)prioceiling; return EINVAL; @@ -933,16 +963,14 @@ int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling) } // pthread_mutex functions -int pthread_mutex_init(pthread_mutex_t *__restrict mutex, - const pthread_mutexattr_t *__restrict attr) { +int +pthread_mutex_init(pthread_mutex_t *__restrict mutex, const pthread_mutexattr_t *__restrict attr) { SCOPE_TRACE(); return mlibc::thread_mutex_init(mutex, attr); } -int pthread_mutex_destroy(pthread_mutex_t *mutex) { - return mlibc::thread_mutex_destroy(mutex); -} +int pthread_mutex_destroy(pthread_mutex_t *mutex) { return mlibc::thread_mutex_destroy(mutex); } int pthread_mutex_lock(pthread_mutex_t *mutex) { SCOPE_TRACE(); @@ -955,18 +983,24 @@ int pthread_mutex_trylock(pthread_mutex_t *mutex) { unsigned int this_tid = mlibc::this_tid(); unsigned int expected = __atomic_load_n(&mutex->__mlibc_state, __ATOMIC_RELAXED); - if(!expected) { + if (!expected) { // Try to take the mutex here. - if(__atomic_compare_exchange_n(&mutex->__mlibc_state, - &expected, this_tid, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) { + if (__atomic_compare_exchange_n( + &mutex->__mlibc_state, + &expected, + this_tid, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )) { __ensure(!mutex->__mlibc_recursion); mutex->__mlibc_recursion = 1; return 0; } } else { // If this (recursive) mutex is already owned by us, increment the recursion level. - if((expected & mutex_owner_mask) == this_tid) { - if(!(mutex->__mlibc_flags & mutexRecursive)) { + if ((expected & mutex_owner_mask) == this_tid) { + if (!(mutex->__mlibc_flags & mutexRecursive)) { return EBUSY; } ++mutex->__mlibc_recursion; @@ -977,8 +1011,7 @@ int pthread_mutex_trylock(pthread_mutex_t *mutex) { return EBUSY; } -int pthread_mutex_timedlock(pthread_mutex_t *__restrict, - const struct timespec *__restrict) { +int pthread_mutex_timedlock(pthread_mutex_t *__restrict, const struct timespec *__restrict) { __ensure(!"Not implemented"); __builtin_unreachable(); } @@ -1009,24 +1042,24 @@ int pthread_condattr_destroy(pthread_condattr_t *attr) { return 0; } -int pthread_condattr_getclock(const pthread_condattr_t *__restrict attr, - clockid_t *__restrict clock) { +int +pthread_condattr_getclock(const pthread_condattr_t *__restrict attr, clockid_t *__restrict clock) { *clock = attr->__mlibc_clock; return 0; } int pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clock) { - if (clock != CLOCK_REALTIME && clock != CLOCK_MONOTONIC - && clock != CLOCK_MONOTONIC_RAW && clock != CLOCK_REALTIME_COARSE - && clock != CLOCK_MONOTONIC_COARSE && clock != CLOCK_BOOTTIME) + if (clock != CLOCK_REALTIME && clock != CLOCK_MONOTONIC && clock != CLOCK_MONOTONIC_RAW && + clock != CLOCK_REALTIME_COARSE && clock != CLOCK_MONOTONIC_COARSE && + clock != CLOCK_BOOTTIME) return EINVAL; attr->__mlibc_clock = clock; return 0; } -int pthread_condattr_getpshared(const pthread_condattr_t *__restrict attr, - int *__restrict pshared) { +int +pthread_condattr_getpshared(const pthread_condattr_t *__restrict attr, int *__restrict pshared) { *pshared = attr->__mlibc_pshared; return 0; } @@ -1055,8 +1088,11 @@ int pthread_cond_wait(pthread_cond_t *__restrict cond, pthread_mutex_t *__restri return pthread_cond_timedwait(cond, mutex, nullptr); } -int pthread_cond_timedwait(pthread_cond_t *__restrict cond, pthread_mutex_t *__restrict mutex, - const struct timespec *__restrict abstime) { +int pthread_cond_timedwait( + pthread_cond_t *__restrict cond, + pthread_mutex_t *__restrict mutex, + const struct timespec *__restrict abstime +) { return mlibc::thread_cond_timedwait(cond, mutex, abstime); } @@ -1081,8 +1117,9 @@ int pthread_barrierattr_init(pthread_barrierattr_t *attr) { return 0; } -int pthread_barrierattr_getpshared(const pthread_barrierattr_t *__restrict attr, - int *__restrict pshared) { +int pthread_barrierattr_getpshared( + const pthread_barrierattr_t *__restrict attr, int *__restrict pshared +) { *pshared = attr->__mlibc_pshared; return 0; } @@ -1095,12 +1132,13 @@ int pthread_barrierattr_setpshared(pthread_barrierattr_t *attr, int pshared) { return 0; } -int pthread_barrierattr_destroy(pthread_barrierattr_t *) { - return 0; -} +int pthread_barrierattr_destroy(pthread_barrierattr_t *) { return 0; } -int pthread_barrier_init(pthread_barrier_t *__restrict barrier, - const pthread_barrierattr_t *__restrict attr, unsigned count) { +int pthread_barrier_init( + pthread_barrier_t *__restrict barrier, + const pthread_barrierattr_t *__restrict attr, + unsigned count +) { if (count == 0) return EINVAL; @@ -1135,17 +1173,16 @@ int pthread_barrier_destroy(pthread_barrier_t *barrier) { int pthread_barrier_wait(pthread_barrier_t *barrier) { if (barrier->__mlibc_flags != 0) { - mlibc::panicLogger() << "mlibc: pthread_barrier_t flags were non-zero" - << frg::endlog; + mlibc::panicLogger() << "mlibc: pthread_barrier_t flags were non-zero" << frg::endlog; } // inside is incremented on entry and decremented on exit. - // This is used to synchronise with pthread_barrier_destroy, to ensure that a thread doesn't pass - // the barrier and immediately destroy its state while other threads still rely on it. + // This is used to synchronise with pthread_barrier_destroy, to ensure that a thread doesn't + // pass the barrier and immediately destroy its state while other threads still rely on it. __atomic_fetch_add(&barrier->__mlibc_inside, 1, __ATOMIC_ACQUIRE); - auto leave = [&](){ + auto leave = [&]() { unsigned inside = __atomic_sub_fetch(&barrier->__mlibc_inside, 1, __ATOMIC_RELEASE); if (inside == 0) mlibc::sys_futex_wake((int *)&barrier->__mlibc_inside); @@ -1155,7 +1192,14 @@ int pthread_barrier_wait(pthread_barrier_t *barrier) { while (true) { unsigned expected = __atomic_load_n(&barrier->__mlibc_waiting, __ATOMIC_RELAXED); - bool swapped = __atomic_compare_exchange_n(&barrier->__mlibc_waiting, &expected, expected + 1, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE); + bool swapped = __atomic_compare_exchange_n( + &barrier->__mlibc_waiting, + &expected, + expected + 1, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + ); if (swapped) { if (expected + 1 == barrier->__mlibc_count) { @@ -1172,7 +1216,8 @@ int pthread_barrier_wait(pthread_barrier_t *barrier) { while (true) { int e = mlibc::sys_futex_wait((int *)&barrier->__mlibc_seq, seq, nullptr); if (e != 0 && e != EAGAIN && e != EINTR) - mlibc::panicLogger() << "mlibc: sys_futex_wait() returned error " << e << frg::endlog; + mlibc::panicLogger() + << "mlibc: sys_futex_wait() returned error " << e << frg::endlog; unsigned newSeq = __atomic_load_n(&barrier->__mlibc_seq, __ATOMIC_ACQUIRE); if (newSeq > seq) { @@ -1189,74 +1234,83 @@ int pthread_barrier_wait(pthread_barrier_t *barrier) { // ---------------------------------------------------------------------------- namespace { - void rwlock_m_lock(pthread_rwlock_t *rw, bool excl) { - unsigned int m_expected = __atomic_load_n(&rw->__mlibc_m, __ATOMIC_RELAXED); - while(true) { - if(m_expected) { - __ensure(m_expected & mutex_owner_mask); - - // Try to set the waiters bit. - if(!(m_expected & mutex_waiters_bit)) { - unsigned int desired = m_expected | mutex_waiters_bit; - if(!__atomic_compare_exchange_n(&rw->__mlibc_m, - &m_expected, desired, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) - continue; - } - - // Wait on the futex. - mlibc::sys_futex_wait((int *)&rw->__mlibc_m, m_expected | mutex_waiters_bit, nullptr); - - // Opportunistically try to take the lock after we wake up. - m_expected = 0; - }else{ - // Try to lock the mutex. - unsigned int desired = 1; - if(excl) - desired |= mutex_excl_bit; - if(__atomic_compare_exchange_n(&rw->__mlibc_m, - &m_expected, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) - break; +void rwlock_m_lock(pthread_rwlock_t *rw, bool excl) { + unsigned int m_expected = __atomic_load_n(&rw->__mlibc_m, __ATOMIC_RELAXED); + while (true) { + if (m_expected) { + __ensure(m_expected & mutex_owner_mask); + + // Try to set the waiters bit. + if (!(m_expected & mutex_waiters_bit)) { + unsigned int desired = m_expected | mutex_waiters_bit; + if (!__atomic_compare_exchange_n( + &rw->__mlibc_m, + &m_expected, + desired, + false, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED + )) + continue; } - } - } - int rwlock_m_trylock(pthread_rwlock_t *rw, bool excl) { - unsigned int m_expected = __atomic_load_n(&rw->__mlibc_m, __ATOMIC_RELAXED); - if(!m_expected) { + // Wait on the futex. + mlibc::sys_futex_wait((int *)&rw->__mlibc_m, m_expected | mutex_waiters_bit, nullptr); + + // Opportunistically try to take the lock after we wake up. + m_expected = 0; + } else { // Try to lock the mutex. unsigned int desired = 1; - if(excl) + if (excl) desired |= mutex_excl_bit; - if(__atomic_compare_exchange_n(&rw->__mlibc_m, - &m_expected, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) - return 0; + if (__atomic_compare_exchange_n( + &rw->__mlibc_m, &m_expected, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED + )) + break; } + } +} - __ensure(m_expected & mutex_owner_mask); +int rwlock_m_trylock(pthread_rwlock_t *rw, bool excl) { + unsigned int m_expected = __atomic_load_n(&rw->__mlibc_m, __ATOMIC_RELAXED); + if (!m_expected) { + // Try to lock the mutex. + unsigned int desired = 1; + if (excl) + desired |= mutex_excl_bit; + if (__atomic_compare_exchange_n( + &rw->__mlibc_m, &m_expected, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED + )) + return 0; + } - // POSIX says that this function should never block but also that - // readers should not be blocked by readers. We implement this by returning EAGAIN - // (and not EBUSY) if a reader would block a reader. - if(!excl && !(m_expected & mutex_excl_bit)) - return EAGAIN; + __ensure(m_expected & mutex_owner_mask); - return EBUSY; - } + // POSIX says that this function should never block but also that + // readers should not be blocked by readers. We implement this by returning EAGAIN + // (and not EBUSY) if a reader would block a reader. + if (!excl && !(m_expected & mutex_excl_bit)) + return EAGAIN; - void rwlock_m_unlock(pthread_rwlock_t *rw) { - auto m = __atomic_exchange_n(&rw->__mlibc_m, 0, __ATOMIC_RELEASE); - if(m & mutex_waiters_bit) - mlibc::sys_futex_wake((int *)&rw->__mlibc_m); - } + return EBUSY; +} + +void rwlock_m_unlock(pthread_rwlock_t *rw) { + auto m = __atomic_exchange_n(&rw->__mlibc_m, 0, __ATOMIC_RELEASE); + if (m & mutex_waiters_bit) + mlibc::sys_futex_wake((int *)&rw->__mlibc_m); } +} // namespace int pthread_rwlockattr_init(pthread_rwlockattr_t *attr) { attr->__mlibc_pshared = PTHREAD_PROCESS_PRIVATE; return 0; } -int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *__restrict attr, - int *__restrict pshared) { +int pthread_rwlockattr_getpshared( + const pthread_rwlockattr_t *__restrict attr, int *__restrict pshared +) { *pshared = attr->__mlibc_pshared; return 0; } @@ -1269,11 +1323,10 @@ int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr, int pshared) { return 0; } -int pthread_rwlockattr_destroy(pthread_rwlockattr_t *) { - return 0; -} +int pthread_rwlockattr_destroy(pthread_rwlockattr_t *) { return 0; } -int pthread_rwlock_init(pthread_rwlock_t *__restrict rw, const pthread_rwlockattr_t *__restrict attr) { +int +pthread_rwlock_init(pthread_rwlock_t *__restrict rw, const pthread_rwlockattr_t *__restrict attr) { SCOPE_TRACE(); rw->__mlibc_m = 0; rw->__mlibc_rc = 0; @@ -1294,18 +1347,17 @@ int pthread_rwlock_trywrlock(pthread_rwlock_t *rw) { SCOPE_TRACE(); if (rw->__mlibc_flags != 0) { - mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" - << frg::endlog; + mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" << frg::endlog; } // Take the __mlibc_m mutex. // Will be released in pthread_rwlock_unlock(). - if(int e = rwlock_m_trylock(rw, true)) + if (int e = rwlock_m_trylock(rw, true)) return e; // Check that there are no readers. unsigned int rc_expected = __atomic_load_n(&rw->__mlibc_rc, __ATOMIC_ACQUIRE); - if(rc_expected) { + if (rc_expected) { rwlock_m_unlock(rw); return EBUSY; } @@ -1317,8 +1369,7 @@ int pthread_rwlock_wrlock(pthread_rwlock_t *rw) { SCOPE_TRACE(); if (rw->__mlibc_flags != 0) { - mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" - << frg::endlog; + mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" << frg::endlog; } // Take the __mlibc_m mutex. @@ -1327,17 +1378,23 @@ int pthread_rwlock_wrlock(pthread_rwlock_t *rw) { // Now wait until there are no more readers. unsigned int rc_expected = __atomic_load_n(&rw->__mlibc_rc, __ATOMIC_ACQUIRE); - while(true) { - if(!rc_expected) + while (true) { + if (!rc_expected) break; __ensure(rc_expected & rc_count_mask); // Try to set the waiters bit. - if(!(rc_expected & rc_waiters_bit)) { + if (!(rc_expected & rc_waiters_bit)) { unsigned int desired = rc_expected | rc_count_mask; - if(!__atomic_compare_exchange_n(&rw->__mlibc_rc, - &rc_expected, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) + if (!__atomic_compare_exchange_n( + &rw->__mlibc_rc, + &rc_expected, + desired, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )) continue; } @@ -1355,12 +1412,11 @@ int pthread_rwlock_tryrdlock(pthread_rwlock_t *rw) { SCOPE_TRACE(); if (rw->__mlibc_flags != 0) { - mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" - << frg::endlog; + mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" << frg::endlog; } // Increment the reader count while holding the __mlibc_m mutex. - if(int e = rwlock_m_trylock(rw, false); e) + if (int e = rwlock_m_trylock(rw, false); e) return e; __atomic_fetch_add(&rw->__mlibc_rc, 1, __ATOMIC_ACQUIRE); rwlock_m_unlock(rw); @@ -1372,8 +1428,7 @@ int pthread_rwlock_rdlock(pthread_rwlock_t *rw) { SCOPE_TRACE(); if (rw->__mlibc_flags != 0) { - mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" - << frg::endlog; + mlibc::panicLogger() << "mlibc: pthread_rwlock_t flags were non-zero" << frg::endlog; } // Increment the reader count while holding the __mlibc_m mutex. @@ -1388,30 +1443,42 @@ int pthread_rwlock_unlock(pthread_rwlock_t *rw) { SCOPE_TRACE(); unsigned int rc_expected = __atomic_load_n(&rw->__mlibc_rc, __ATOMIC_RELAXED); - if(!rc_expected) { + if (!rc_expected) { // We are doing a write-unlock. rwlock_m_unlock(rw); return 0; - }else{ + } else { // We are doing a read-unlock. - while(true) { + while (true) { unsigned int count = rc_expected & rc_count_mask; __ensure(count); // Try to decrement the count. - if(count == 1 && (rc_expected & rc_waiters_bit)) { + if (count == 1 && (rc_expected & rc_waiters_bit)) { unsigned int desired = 0; - if(!__atomic_compare_exchange_n(&rw->__mlibc_rc, - &rc_expected, desired, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) + if (!__atomic_compare_exchange_n( + &rw->__mlibc_rc, + &rc_expected, + desired, + false, + __ATOMIC_RELEASE, + __ATOMIC_RELAXED + )) continue; // Wake the futex. mlibc::sys_futex_wake((int *)&rw->__mlibc_rc); break; - }else{ + } else { unsigned int desired = (rc_expected & ~rc_count_mask) | (count - 1); - if(!__atomic_compare_exchange_n(&rw->__mlibc_rc, - &rc_expected, desired, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) + if (!__atomic_compare_exchange_n( + &rw->__mlibc_rc, + &rc_expected, + desired, + false, + __ATOMIC_RELEASE, + __ATOMIC_RELAXED + )) continue; break; } @@ -1422,7 +1489,6 @@ int pthread_rwlock_unlock(pthread_rwlock_t *rw) { } int pthread_getcpuclockid(pthread_t, clockid_t *) { - mlibc::infoLogger() << "mlibc: pthread_getcpuclockid() always returns ENOENT" - << frg::endlog; + mlibc::infoLogger() << "mlibc: pthread_getcpuclockid() always returns ENOENT" << frg::endlog; return ENOENT; } diff --git a/options/posix/generic/pwd.cpp b/options/posix/generic/pwd.cpp index 6ef908020c..7d923649c4 100644 --- a/options/posix/generic/pwd.cpp +++ b/options/posix/generic/pwd.cpp @@ -1,139 +1,139 @@ +#include #include #include #include #include -#include #include namespace { - FILE *global_file; // Used by setpwent/getpwent/endpwent. - - bool open_global_file() { - if(!global_file) { - global_file = fopen("/etc/passwd", "r"); - if(!global_file) { - errno = EIO; - return false; - } - } +FILE *global_file; // Used by setpwent/getpwent/endpwent. - return true; - } - - void close_global_file() { - if(global_file) { - fclose(global_file); - global_file = nullptr; +bool open_global_file() { + if (!global_file) { + global_file = fopen("/etc/passwd", "r"); + if (!global_file) { + errno = EIO; + return false; } } - bool extract_entry(frg::string_view line, passwd *entry) { - frg::string_view segments[8]; - - // Parse the line into 7 or 8 segments. - size_t s = 0; - int n; - for(n = 0; n < 7; n++) { - size_t d = line.find_first(':', s); - if(d == size_t(-1)) - break; - segments[n] = line.sub_string(s, d - s); - s = d + 1; - } - if(line.find_first(':', s) != size_t(-1)) - return false; - segments[n] = line.sub_string(s, line.size() - s); - n++; - - if(n < 7) - return false; - - // TODO: Handle strndup() failure. - auto name = strndup(segments[0].data(), segments[0].size()); - __ensure(name); - - auto passwd = strndup(segments[1].data(), segments[1].size()); - __ensure(passwd); + return true; +} - auto uid = segments[2].to_number(); - if(!uid) - return false; - auto gid = segments[3].to_number(); - if(!gid) - return false; +void close_global_file() { + if (global_file) { + fclose(global_file); + global_file = nullptr; + } +} - auto real_name = strndup(segments[4].data(), segments[4].size()); - __ensure(real_name); - auto dir = strndup(segments[5].data(), segments[5].size()); - __ensure(dir); - auto shell = strndup(segments[6].data(), segments[6].size()); - __ensure(shell); - - // Chop the newline off the end of shell - __ensure(strlen(shell) > 0); - shell[strlen(shell) - 1] = '\0'; - - entry->pw_name = name; - entry->pw_passwd = passwd; - entry->pw_uid = *uid; - entry->pw_gid = *gid; - entry->pw_dir = dir; - entry->pw_shell = shell; - entry->pw_gecos = real_name; - return true; +bool extract_entry(frg::string_view line, passwd *entry) { + frg::string_view segments[8]; + + // Parse the line into 7 or 8 segments. + size_t s = 0; + int n; + for (n = 0; n < 7; n++) { + size_t d = line.find_first(':', s); + if (d == size_t(-1)) + break; + segments[n] = line.sub_string(s, d - s); + s = d + 1; } + if (line.find_first(':', s) != size_t(-1)) + return false; + segments[n] = line.sub_string(s, line.size() - s); + n++; + + if (n < 7) + return false; + + // TODO: Handle strndup() failure. + auto name = strndup(segments[0].data(), segments[0].size()); + __ensure(name); + + auto passwd = strndup(segments[1].data(), segments[1].size()); + __ensure(passwd); + + auto uid = segments[2].to_number(); + if (!uid) + return false; + auto gid = segments[3].to_number(); + if (!gid) + return false; + + auto real_name = strndup(segments[4].data(), segments[4].size()); + __ensure(real_name); + auto dir = strndup(segments[5].data(), segments[5].size()); + __ensure(dir); + auto shell = strndup(segments[6].data(), segments[6].size()); + __ensure(shell); + + // Chop the newline off the end of shell + __ensure(strlen(shell) > 0); + shell[strlen(shell) - 1] = '\0'; + + entry->pw_name = name; + entry->pw_passwd = passwd; + entry->pw_uid = *uid; + entry->pw_gid = *gid; + entry->pw_dir = dir; + entry->pw_shell = shell; + entry->pw_gecos = real_name; + return true; +} - void copy_to_buffer(passwd *pwd, char *buffer, size_t size) { - char *pw_dir = stpcpy(buffer, pwd->pw_name) + 1; - free(pwd->pw_name); - pwd->pw_name = buffer; +void copy_to_buffer(passwd *pwd, char *buffer, size_t size) { + char *pw_dir = stpcpy(buffer, pwd->pw_name) + 1; + free(pwd->pw_name); + pwd->pw_name = buffer; - char *pw_shell = stpcpy(pw_dir, pwd->pw_dir) + 1; - free(pwd->pw_dir); - pwd->pw_dir = pw_dir; + char *pw_shell = stpcpy(pw_dir, pwd->pw_dir) + 1; + free(pwd->pw_dir); + pwd->pw_dir = pw_dir; - char *pw_passwd = stpcpy(pw_shell, pwd->pw_shell) + 1; - free(pwd->pw_shell); - pwd->pw_shell = pw_shell; + char *pw_passwd = stpcpy(pw_shell, pwd->pw_shell) + 1; + free(pwd->pw_shell); + pwd->pw_shell = pw_shell; - char *end = stpcpy(pw_passwd, pwd->pw_passwd); - __ensure(end <= buffer + size); - free(pwd->pw_passwd); - pwd->pw_passwd = pw_passwd; - } + char *end = stpcpy(pw_passwd, pwd->pw_passwd); + __ensure(end <= buffer + size); + free(pwd->pw_passwd); + pwd->pw_passwd = pw_passwd; +} - void clear_entry(passwd *entry) { - free(entry->pw_name); - free(entry->pw_dir); - free(entry->pw_passwd); - free(entry->pw_shell); - entry->pw_name = nullptr; - entry->pw_dir = nullptr; - entry->pw_passwd = nullptr; - entry->pw_shell = nullptr; - } +void clear_entry(passwd *entry) { + free(entry->pw_name); + free(entry->pw_dir); + free(entry->pw_passwd); + free(entry->pw_shell); + entry->pw_name = nullptr; + entry->pw_dir = nullptr; + entry->pw_passwd = nullptr; + entry->pw_shell = nullptr; } +} // namespace struct passwd *getpwent(void) { static passwd entry; char line[NSS_BUFLEN_PASSWD]; - if(!open_global_file()) { + if (!open_global_file()) { return nullptr; } if (fgets(line, NSS_BUFLEN_PASSWD, global_file)) { clear_entry(&entry); - if(!extract_entry(line, &entry)) { - errno = EINVAL; // I suppose this can be a valid errno? + if (!extract_entry(line, &entry)) { + errno = EINVAL; // I suppose this can be a valid errno? return nullptr; } return &entry; } - if(ferror(global_file)) { + if (ferror(global_file)) { errno = EIO; } @@ -143,22 +143,22 @@ struct passwd *getpwent(void) { struct passwd *getpwnam(const char *name) { static passwd entry; auto file = fopen("/etc/passwd", "r"); - if(!file) + if (!file) return nullptr; char line[NSS_BUFLEN_PASSWD]; - while(fgets(line, NSS_BUFLEN_PASSWD, file)) { + while (fgets(line, NSS_BUFLEN_PASSWD, file)) { clear_entry(&entry); - if(!extract_entry(line, &entry)) + if (!extract_entry(line, &entry)) continue; - if(!strcmp(entry.pw_name, name)) { + if (!strcmp(entry.pw_name, name)) { fclose(file); return &entry; } } int err = errno; - if(ferror(file)) { + if (ferror(file)) { err = EIO; } @@ -167,22 +167,24 @@ struct passwd *getpwnam(const char *name) { return nullptr; } -int getpwnam_r(const char *name, struct passwd *pwd, char *buffer, size_t size, struct passwd **result) { +int getpwnam_r( + const char *name, struct passwd *pwd, char *buffer, size_t size, struct passwd **result +) { *result = nullptr; auto file = fopen("/etc/passwd", "r"); - if(!file) { + if (!file) { return EIO; } char line[NSS_BUFLEN_PASSWD]; - while(fgets(line, NSS_BUFLEN_PASSWD, file)) { - if(!extract_entry(line, pwd)) + while (fgets(line, NSS_BUFLEN_PASSWD, file)) { + if (!extract_entry(line, pwd)) continue; - if(!strcmp(pwd->pw_name, name)) { + if (!strcmp(pwd->pw_name, name)) { fclose(file); - size_t required_size = strlen(pwd->pw_name) + strlen(pwd->pw_dir) - + strlen(pwd->pw_shell) + strlen(pwd->pw_passwd) + 4; + size_t required_size = strlen(pwd->pw_name) + strlen(pwd->pw_dir) + + strlen(pwd->pw_shell) + strlen(pwd->pw_passwd) + 4; if (size < required_size) return ERANGE; @@ -193,7 +195,7 @@ int getpwnam_r(const char *name, struct passwd *pwd, char *buffer, size_t size, } int ret = 0; - if(ferror(file)) { + if (ferror(file)) { ret = EIO; } @@ -204,22 +206,22 @@ int getpwnam_r(const char *name, struct passwd *pwd, char *buffer, size_t size, struct passwd *getpwuid(uid_t uid) { static passwd entry; auto file = fopen("/etc/passwd", "r"); - if(!file) + if (!file) return nullptr; char line[NSS_BUFLEN_PASSWD]; - while(fgets(line, NSS_BUFLEN_PASSWD, file)) { + while (fgets(line, NSS_BUFLEN_PASSWD, file)) { clear_entry(&entry); - if(!extract_entry(line, &entry)) + if (!extract_entry(line, &entry)) continue; - if(entry.pw_uid == uid) { + if (entry.pw_uid == uid) { fclose(file); return &entry; } } int err = ESRCH; - if(ferror(file)) { + if (ferror(file)) { err = EIO; } @@ -231,19 +233,19 @@ struct passwd *getpwuid(uid_t uid) { int getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer, size_t size, struct passwd **result) { *result = nullptr; auto file = fopen("/etc/passwd", "r"); - if(!file) { + if (!file) { return EIO; } char line[NSS_BUFLEN_PASSWD]; - while(fgets(line, NSS_BUFLEN_PASSWD, file)) { - if(!extract_entry(line, pwd)) + while (fgets(line, NSS_BUFLEN_PASSWD, file)) { + if (!extract_entry(line, pwd)) continue; - if(pwd->pw_uid == uid) { + if (pwd->pw_uid == uid) { fclose(file); - size_t required_size = strlen(pwd->pw_name) + strlen(pwd->pw_dir) - + strlen(pwd->pw_shell) + + strlen(pwd->pw_passwd) + 4; + size_t required_size = strlen(pwd->pw_name) + strlen(pwd->pw_dir) + + strlen(pwd->pw_shell) + +strlen(pwd->pw_passwd) + 4; if (size < required_size) return ERANGE; @@ -254,7 +256,7 @@ int getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer, size_t size, struct } int ret = 0; - if(ferror(file)) { + if (ferror(file)) { ret = EIO; } @@ -263,28 +265,37 @@ int getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer, size_t size, struct } void setpwent(void) { - if(!open_global_file()) { + if (!open_global_file()) { return; } rewind(global_file); } -void endpwent(void) { - close_global_file(); -} +void endpwent(void) { close_global_file(); } int putpwent(const struct passwd *p, FILE *f) { - auto invalid = [](const char *s) { - return s == nullptr || strchr(s, '\n') || strchr(s, ':'); - }; + auto invalid = [](const char *s) { return s == nullptr || strchr(s, '\n') || strchr(s, ':'); }; - if (p == nullptr || invalid(p->pw_name) || invalid(p->pw_passwd) || invalid(p->pw_gecos) || invalid(p->pw_dir) || invalid(p->pw_shell)) { + if (p == nullptr || invalid(p->pw_name) || invalid(p->pw_passwd) || invalid(p->pw_gecos) || + invalid(p->pw_dir) || invalid(p->pw_shell)) { errno = EINVAL; return -1; } // Taken from musl. - return fprintf(f, "%s:%s:%u:%u:%s:%s:%s\n", p->pw_name, p->pw_passwd, p->pw_uid, p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell) < 0 ? -1 : 0; + return fprintf( + f, + "%s:%s:%u:%u:%s:%s:%s\n", + p->pw_name, + p->pw_passwd, + p->pw_uid, + p->pw_gid, + p->pw_gecos, + p->pw_dir, + p->pw_shell + ) < 0 + ? -1 + : 0; } struct passwd *fgetpwent(FILE *) { diff --git a/options/posix/generic/resolv_conf.cpp b/options/posix/generic/resolv_conf.cpp index a5c3aa7c84..d5281c836e 100644 --- a/options/posix/generic/resolv_conf.cpp +++ b/options/posix/generic/resolv_conf.cpp @@ -1,7 +1,7 @@ -#include +#include #include +#include #include -#include namespace mlibc { @@ -16,7 +16,8 @@ frg::optional get_nameserver() { char *pos; if (!strchr(line, '\n') && !feof(file)) { // skip truncated lines - for (int c = getc(file); c != '\n' && c != EOF; c = getc(file)); + for (int c = getc(file); c != '\n' && c != EOF; c = getc(file)) + ; continue; } @@ -24,17 +25,18 @@ frg::optional get_nameserver() { // but we just pick the first one for now if (!strncmp(line, "nameserver", 10) && isspace(line[10])) { char *end; - for (pos = line + 11; isspace(*pos); pos++); - for (end = pos; *end && !isspace(*end); end++); + for (pos = line + 11; isspace(*pos); pos++) + ; + for (end = pos; *end && !isspace(*end); end++) + ; *end = '\0'; - ret.name = frg::string( - pos, end - pos, getAllocator()); + ret.name = frg::string(pos, end - pos, getAllocator()); break; } } fclose(file); - if(ret.name.empty()) + if (ret.name.empty()) return frg::null_opt; return ret; } diff --git a/options/posix/generic/sched.cpp b/options/posix/generic/sched.cpp index 9d75d50704..20be47f7de 100644 --- a/options/posix/generic/sched.cpp +++ b/options/posix/generic/sched.cpp @@ -8,9 +8,9 @@ #include int sched_yield(void) { - if(mlibc::sys_yield) { + if (mlibc::sys_yield) { mlibc::sys_yield(); - }else{ + } else { // Missing sched_yield() is not an error. MLIBC_MISSING_SYSDEP(); } @@ -21,7 +21,7 @@ int sched_get_priority_max(int policy) { int res = 0; auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_get_max_priority, -1); - if(int e = sysdep(policy, &res); e) { + if (int e = sysdep(policy, &res); e) { errno = e; return -1; } @@ -32,7 +32,7 @@ int sched_get_priority_min(int policy) { int res = 0; auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_get_min_priority, -1); - if(int e = sysdep(policy, &res); e) { + if (int e = sysdep(policy, &res); e) { errno = e; return -1; } diff --git a/options/posix/generic/search.cpp b/options/posix/generic/search.cpp index 7769bcc601..92deec71ed 100644 --- a/options/posix/generic/search.cpp +++ b/options/posix/generic/search.cpp @@ -1,11 +1,11 @@ #include -#include -#include -#include +#include #include #include -#include +#include +#include +#include #include struct node { @@ -15,55 +15,52 @@ struct node { }; namespace { - int height(struct node *node) { - return node ? node->h : 0; +int height(struct node *node) { return node ? node->h : 0; } + +int rotate(struct node **nodep, int side) { + struct node *node = *nodep; + struct node *x = static_cast(node->a[side]); + struct node *y = static_cast(x->a[!side]); + struct node *z = static_cast(x->a[side]); + + int height_node = node->h; + int height_y = height(y); + if (height_y > height(z)) { + // Perform double rotation + node->a[side] = y->a[!side]; + x->a[!side] = y->a[side]; + y->a[!side] = node; + y->a[side] = x; + node->h = height_y; + x->h = height_y; + y->h = height_y + 1; + } else { + // Perform single rotation + node->a[side] = y; + x->a[!side] = node; + node->h = height_y + 1; + x->h = height_y + 2; + y = x; } + *nodep = y; + return y->h - height_node; +} - int rotate(struct node **nodep, int side) { - struct node *node = *nodep; - struct node *x = static_cast(node->a[side]); - struct node *y = static_cast(x->a[!side]); - struct node *z = static_cast(x->a[side]); - - int height_node = node->h; - int height_y = height(y); - if (height_y > height(z)) { - // Perform double rotation - node->a[side] = y->a[!side]; - x->a[!side] = y->a[side]; - y->a[!side] = node; - y->a[side] = x; - node->h = height_y; - x->h = height_y; - y->h = height_y + 1; - } else { - // Perform single rotation - node->a[side] = y; - x->a[!side] = node; - node->h = height_y + 1; - x->h = height_y + 2; - y = x; - - } - *nodep = y; - return y->h - height_node; +int balance_tree(struct node **nodep) { + struct node *node = *nodep; + int height_a = height(static_cast(node->a[0])); + int height_b = height(static_cast(node->a[1])); + if (height_a - height_b < 2) { + int old = node->h; + node->h = height_a < height_b ? height_b + 1 : height_a + 1; + return node->h - old; } - int balance_tree(struct node **nodep) { - struct node *node = *nodep; - int height_a = height(static_cast(node->a[0])); - int height_b = height(static_cast(node->a[1])); - if (height_a - height_b < 2) { - int old = node->h; - node->h = height_a < height_b ? height_b + 1 : height_a + 1; - return node->h - old; - } - - return rotate(nodep, height_a < height_b); - } + return rotate(nodep, height_a < height_b); } +} // namespace -void *tsearch(const void *key, void **rootp, int(*compar)(const void *, const void *)) { +void *tsearch(const void *key, void **rootp, int (*compar)(const void *, const void *)) { if (!rootp) return NULL; @@ -81,7 +78,7 @@ void *tsearch(const void *key, void **rootp, int(*compar)(const void *, const vo n = static_cast(n->a[c > 0]); } - struct node *insert = static_cast(malloc(sizeof(struct node))); + struct node *insert = static_cast(malloc(sizeof(struct node))); if (!insert) return NULL; insert->key = key; @@ -90,28 +87,29 @@ void *tsearch(const void *key, void **rootp, int(*compar)(const void *, const vo (*nodes.top()) = insert; nodes.pop(); - while(nodes.size() && balance_tree(nodes.top())) nodes.pop(); + while (nodes.size() && balance_tree(nodes.top())) + nodes.pop(); return insert; } // This implementation is taken from musl void *tfind(const void *key, void *const *rootp, int (*compar)(const void *, const void *)) { - if(!rootp) + if (!rootp) return 0; struct node *n = (struct node *)*rootp; - for(;;) { - if(!n) + for (;;) { + if (!n) break; int c = compar(key, n->key); - if(!c) + if (!c) break; n = (struct node *)n->a[c > 0]; } return n; } -void *tdelete(const void *, void **, int(*compar)(const void *, const void *)) { +void *tdelete(const void *, void **, int (*compar)(const void *, const void *)) { (void)compar; __ensure(!"Not implemented"); __builtin_unreachable(); @@ -127,8 +125,8 @@ void tdestroy(void *root, void (*free_node)(void *)) { auto *n = static_cast(root); frg::stack nodes(getAllocator()); - while(n || !nodes.empty()) { - if(n == nullptr) { + while (n || !nodes.empty()) { + if (n == nullptr) { n = nodes.top(); nodes.pop(); free_node(const_cast(n->key)); @@ -142,8 +140,13 @@ void tdestroy(void *root, void (*free_node)(void *)) { } } -void *lsearch(const void *key, void *base, size_t *nelp, size_t width, - int (*compar)(const void *, const void *)) { +void *lsearch( + const void *key, + void *base, + size_t *nelp, + size_t width, + int (*compar)(const void *, const void *) +) { (void)key; (void)base; (void)nelp; @@ -153,8 +156,13 @@ void *lsearch(const void *key, void *base, size_t *nelp, size_t width, __builtin_unreachable(); } -void *lfind(const void *key, const void *base, size_t *nelp, - size_t width, int (*compar)(const void *, const void *)) { +void *lfind( + const void *key, + const void *base, + size_t *nelp, + size_t width, + int (*compar)(const void *, const void *) +) { (void)key; (void)base; (void)nelp; @@ -165,20 +173,16 @@ void *lfind(const void *key, const void *base, size_t *nelp, } namespace { - hsearch_data globalTable {}; +hsearch_data globalTable{}; } -int hcreate(size_t num_entries) { - return mlibc::hcreate_r(num_entries, &globalTable); -} +int hcreate(size_t num_entries) { return mlibc::hcreate_r(num_entries, &globalTable); } -void hdestroy(void) { - mlibc::hdestroy_r(&globalTable); -} +void hdestroy(void) { mlibc::hdestroy_r(&globalTable); } ENTRY *hsearch(ENTRY item, ACTION action) { ENTRY *ret; - if(mlibc::hsearch_r(item, action, &ret, &globalTable) == 0) { + if (mlibc::hsearch_r(item, action, &ret, &globalTable) == 0) { return nullptr; } return ret; diff --git a/options/posix/generic/semaphore.cpp b/options/posix/generic/semaphore.cpp index 741cd24821..dc5de63b09 100644 --- a/options/posix/generic/semaphore.cpp +++ b/options/posix/generic/semaphore.cpp @@ -1,9 +1,9 @@ -#include #include +#include #include -#include #include +#include #include static constexpr unsigned int semaphoreHasWaiters = static_cast(1 << 31); @@ -26,17 +26,21 @@ int sem_init(sem_t *sem, int pshared, unsigned int initial_count) { return 0; } -int sem_destroy(sem_t *) { - return 0; -} +int sem_destroy(sem_t *) { return 0; } int sem_wait(sem_t *sem) { unsigned int state = 0; while (1) { if (!(state & semaphoreCountMask)) { - if (__atomic_compare_exchange_n(&sem->__mlibc_count, &state, semaphoreHasWaiters, - false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)) { + if (__atomic_compare_exchange_n( + &sem->__mlibc_count, + &state, + semaphoreHasWaiters, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )) { int e = mlibc::sys_futex_wait((int *)&sem->__mlibc_count, state, nullptr); if (e == 0 || e == EAGAIN) { continue; @@ -44,20 +48,23 @@ int sem_wait(sem_t *sem) { errno = EINTR; return -1; } else { - mlibc::panicLogger() << "sys_futex_wait() failed with error code " << e << frg::endlog; + mlibc::panicLogger() + << "sys_futex_wait() failed with error code " << e << frg::endlog; } } } else { unsigned int desired = (state - 1); - if (__atomic_compare_exchange_n(&sem->__mlibc_count, &state, desired, false, - __ATOMIC_RELAXED, __ATOMIC_RELAXED)) + if (__atomic_compare_exchange_n( + &sem->__mlibc_count, &state, desired, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED + )) return 0; } } } int sem_timedwait(sem_t *sem, const struct timespec *) { - mlibc::infoLogger() << "\e[31mmlibc: sem_timedwait is implemented as sem_wait\e[0m" << frg::endlog; + mlibc::infoLogger() << "\e[31mmlibc: sem_timedwait is implemented as sem_wait\e[0m" + << frg::endlog; return sem_wait(sem); } @@ -108,7 +115,9 @@ int sem_trywait(sem_t *sem) { } auto desired = state - 1; - if (__atomic_compare_exchange_n(&sem->__mlibc_count, &state, desired, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) { + if (__atomic_compare_exchange_n( + &sem->__mlibc_count, &state, desired, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED + )) { return 0; } } diff --git a/options/posix/generic/services.cpp b/options/posix/generic/services.cpp index 8ae065633a..1b27483429 100644 --- a/options/posix/generic/services.cpp +++ b/options/posix/generic/services.cpp @@ -1,13 +1,13 @@ +#include +#include +#include #include #include +#include #include -#include -#include #include -#include +#include #include -#include -#include namespace mlibc { @@ -26,7 +26,7 @@ static int parse_rest(service_buf &buf, char *end, int proto) { return 0; } - //TODO(geert): also parse aliases. + // TODO(geert): also parse aliases. return 1; } @@ -35,18 +35,18 @@ static int lookup_serv_file_port(service_result &buf, int proto, int port) { auto file = fopen(_PATH_SERVICES, "r"); if (!file) { switch (errno) { - case ENOENT: - case ENOTDIR: - case EACCES: - return -EAI_SERVICE; - default: - return -EAI_SYSTEM; + case ENOENT: + case ENOTDIR: + case EACCES: + return -EAI_SERVICE; + default: + return -EAI_SYSTEM; } } char line_buf[129] = {0}; char *line = line_buf + 1; - while(fgets(line, 128, file)) { + while (fgets(line, 128, file)) { int name_length = 0; char *pos; // easy way to handle comments, just move the end of the line @@ -58,7 +58,8 @@ static int lookup_serv_file_port(service_result &buf, int proto, int port) { char *end = NULL; for (pos = line; *pos; pos++) { - for (; isalpha(*pos); pos++); + for (; isalpha(*pos); pos++) + ; int rport = strtoul(pos, &end, 10); if (rport != port || rport > 65535) { pos = end; @@ -68,7 +69,7 @@ static int lookup_serv_file_port(service_result &buf, int proto, int port) { // We have found the port, time to rewind to the start // of the line. for (; pos[-1]; pos--) - if(!isspace(pos[-1])) + if (!isspace(pos[-1])) name_length++; break; } @@ -79,8 +80,7 @@ static int lookup_serv_file_port(service_result &buf, int proto, int port) { if (!name_length) continue; - auto name = frg::string(pos, name_length, - getAllocator()); + auto name = frg::string(pos, name_length, getAllocator()); struct service_buf sbuf = {}; sbuf.port = port; @@ -94,23 +94,22 @@ static int lookup_serv_file_port(service_result &buf, int proto, int port) { return buf.size(); } -static int lookup_serv_file_name(service_result &buf, const char *name, - int proto) { +static int lookup_serv_file_name(service_result &buf, const char *name, int proto) { auto file = fopen(_PATH_SERVICES, "r"); if (!file) { switch (errno) { - case ENOENT: - case ENOTDIR: - case EACCES: - return -EAI_SERVICE; - default: - return -EAI_SYSTEM; + case ENOENT: + case ENOTDIR: + case EACCES: + return -EAI_SERVICE; + default: + return -EAI_SYSTEM; } } char line[128]; int name_length = strlen(name); - while(fgets(line, 128, file)) { + while (fgets(line, 128, file)) { char *pos; // easy way to handle comments, just move the end of the line // to the beginning of the comment @@ -131,7 +130,7 @@ static int lookup_serv_file_name(service_result &buf, const char *name, continue; // Skip the name at the beginning of the line. - for(pos = line; *pos && !isspace(*pos); pos++) + for (pos = line; *pos && !isspace(*pos); pos++) ; char *end = NULL; @@ -146,40 +145,37 @@ static int lookup_serv_file_name(service_result &buf, const char *name, continue; buf.push_back(sbuf); - } fclose(file); return buf.size(); } - // This function returns a negative error code, since a positive // return code means success. -int lookup_serv_by_name(service_result &buf, const char *name, int proto, - int socktype, int flags) { - switch(socktype) { - case SOCK_STREAM: - if (!proto) - proto = IPPROTO_TCP; - else if (proto != IPPROTO_TCP) - return -EAI_SERVICE; - break; - case SOCK_DGRAM: - if (!proto) - proto = IPPROTO_UDP; - else if (proto != IPPROTO_UDP) - return -EAI_SERVICE; - break; - case 0: - break; - default: - if (name) - return -EAI_SERVICE; - buf[0].port = 0; - buf[0].socktype = socktype; - buf[0].protocol = proto; - return 1; +int lookup_serv_by_name(service_result &buf, const char *name, int proto, int socktype, int flags) { + switch (socktype) { + case SOCK_STREAM: + if (!proto) + proto = IPPROTO_TCP; + else if (proto != IPPROTO_TCP) + return -EAI_SERVICE; + break; + case SOCK_DGRAM: + if (!proto) + proto = IPPROTO_UDP; + else if (proto != IPPROTO_UDP) + return -EAI_SERVICE; + break; + case 0: + break; + default: + if (name) + return -EAI_SERVICE; + buf[0].port = 0; + buf[0].socktype = socktype; + buf[0].protocol = proto; + return 1; } char *end = nullptr; diff --git a/options/posix/generic/spawn.cpp b/options/posix/generic/spawn.cpp index cf7edfcaa7..bd600975f0 100644 --- a/options/posix/generic/spawn.cpp +++ b/options/posix/generic/spawn.cpp @@ -1,14 +1,14 @@ -#include #include -#include #include -#include #include +#include #include -#include #include +#include +#include #include +#include #include #include @@ -38,9 +38,7 @@ struct fdop { static unsigned long handler_set[NSIG / (8 * sizeof(long))]; -static void __get_handler_set(sigset_t *set) { - memcpy(set, handler_set, sizeof handler_set); -} +static void __get_handler_set(sigset_t *set) { memcpy(set, handler_set, sizeof handler_set); } struct args { int p[2]; @@ -61,7 +59,7 @@ static int child(void *args_vp) { sigset_t hset; bool use_execvpe = false; - if(attr->__fn) + if (attr->__fn) use_execvpe = true; close(args->p[0]); @@ -73,15 +71,16 @@ static int child(void *args_vp) { * reduce overhead, sigaction has tracked for us which signals * potentially have a signal handler. */ __get_handler_set(&hset); - for(i = 1; i < NSIG; i++) { - if((attr->__flags & POSIX_SPAWN_SETSIGDEF) && sigismember(&attr->__def, i)) { + for (i = 1; i < NSIG; i++) { + if ((attr->__flags & POSIX_SPAWN_SETSIGDEF) && sigismember(&attr->__def, i)) { sa.sa_handler = SIG_DFL; - } else if(sigismember(&hset, i)) { + } else if (sigismember(&hset, i)) { if (i - 32 < 3) { sa.sa_handler = SIG_IGN; - } else {; + } else { + ; sigaction(i, 0, &sa); - if(sa.sa_handler == SIG_IGN) + if (sa.sa_handler == SIG_IGN) continue; sa.sa_handler = SIG_DFL; } @@ -91,76 +90,77 @@ static int child(void *args_vp) { sigaction(i, &sa, 0); } - if(attr->__flags & POSIX_SPAWN_SETSID) { - if((ret = setsid()) < 0) + if (attr->__flags & POSIX_SPAWN_SETSID) { + if ((ret = setsid()) < 0) goto fail; } - if(attr->__flags & POSIX_SPAWN_SETPGROUP) { + if (attr->__flags & POSIX_SPAWN_SETPGROUP) { mlibc::infoLogger() << "mlibc: posix_spawn: ignoring SETPGROUP" << frg::endlog; - //if((ret = setpgid(0, attr->__pgrp))) + // if((ret = setpgid(0, attr->__pgrp))) // goto fail; } - if(attr->__flags & POSIX_SPAWN_RESETIDS) { - if((ret = setgid(getgid())) || (ret = setuid(getuid())) ) + if (attr->__flags & POSIX_SPAWN_RESETIDS) { + if ((ret = setgid(getgid())) || (ret = setuid(getuid()))) goto fail; } - if(fa && fa->__actions) { + if (fa && fa->__actions) { struct fdop *op; int fd; - for(op = (struct fdop *)fa->__actions; op->next; op = op->next); - for(; op; op = op->prev) { + for (op = (struct fdop *)fa->__actions; op->next; op = op->next) + ; + for (; op; op = op->prev) { /* It's possible that a file operation would clobber * the pipe fd used for synchronizing with the * parent. To avoid that, we dup the pipe onto * an unoccupied fd. */ - if(op->fd == p) { + if (op->fd == p) { ret = dup(p); - if(ret < 0) + if (ret < 0) goto fail; close(p); p = ret; } - switch(op->cmd) { + switch (op->cmd) { case FDOP_CLOSE: close(op->fd); break; case FDOP_DUP2: fd = op->srcfd; - if(fd == p) { + if (fd == p) { ret = -EBADF; goto fail; } - if(fd != op->fd) { - if((ret = dup2(fd, op->fd)) < 0) + if (fd != op->fd) { + if ((ret = dup2(fd, op->fd)) < 0) goto fail; } else { ret = fcntl(fd, F_GETFD); ret = fcntl(fd, F_SETFD, ret & ~FD_CLOEXEC); - if(ret < 0) + if (ret < 0) goto fail; } break; case FDOP_OPEN: fd = open(op->path, op->oflag, op->mode); - if((ret = fd) < 0) + if ((ret = fd) < 0) goto fail; - if(fd != op->fd) { - if((ret = dup2(fd, op->fd)) < 0) + if (fd != op->fd) { + if ((ret = dup2(fd, op->fd)) < 0) goto fail; close(fd); } break; case FDOP_CHDIR: ret = chdir(op->path); - if(ret < 0) + if (ret < 0) goto fail; break; case FDOP_FCHDIR: ret = fchdir(op->fd); - if(ret < 0) + if (ret < 0) goto fail; break; } @@ -171,10 +171,11 @@ static int child(void *args_vp) { * to a different fd. */ fcntl(p, F_SETFD, FD_CLOEXEC); - pthread_sigmask(SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK) - ? &attr->__mask : &args->oldmask, 0); + pthread_sigmask( + SIG_SETMASK, (attr->__flags & POSIX_SPAWN_SETSIGMASK) ? &attr->__mask : &args->oldmask, 0 + ); - if(use_execvpe) + if (use_execvpe) execvpe(args->path, args->argv, args->envp); else execve(args->path, args->argv, args->envp); @@ -183,15 +184,20 @@ static int child(void *args_vp) { fail: /* Since sizeof errno < PIPE_BUF, the write is atomic. */ ret = -ret; - if(ret) - while(write(p, &ret, sizeof ret) < 0); + if (ret) + while (write(p, &ret, sizeof ret) < 0) + ; _exit(127); } -int posix_spawn(pid_t *__restrict res, const char *__restrict path, - const posix_spawn_file_actions_t *file_actions, - const posix_spawnattr_t *__restrict attrs, - char *const argv[], char *const envp[]) { +int posix_spawn( + pid_t *__restrict res, + const char *__restrict path, + const posix_spawn_file_actions_t *file_actions, + const posix_spawnattr_t *__restrict attrs, + char *const argv[], + char *const envp[] +) { pid_t pid; int ec = 0, cs; struct args args; @@ -210,26 +216,26 @@ int posix_spawn(pid_t *__restrict res, const char *__restrict path, /* The lock guards both against seeing a SIGABRT disposition change * by abort and against leaking the pipe fd to fork-without-exec. */ - //LOCK(__abort_lock); + // LOCK(__abort_lock); - if(pipe2(args.p, O_CLOEXEC)) { - //UNLOCK(__abort_lock); + if (pipe2(args.p, O_CLOEXEC)) { + // UNLOCK(__abort_lock); ec = errno; goto fail; } /* Mlibc change: We use fork + execve, as clone is not implemented. * This yields the same result in the end. */ - //pid = clone(child, stack + sizeof stack, CLONE_VM | CLONE_VFORK | SIGCHLD, &args); + // pid = clone(child, stack + sizeof stack, CLONE_VM | CLONE_VFORK | SIGCHLD, &args); pid = fork(); - if(!pid) { + if (!pid) { child(&args); } close(args.p[1]); - //UNLOCK(__abort_lock); + // UNLOCK(__abort_lock); - if(pid > 0) { - if(read(args.p[0], &ec, sizeof ec) != sizeof ec) + if (pid > 0) { + if (read(args.p[0], &ec, sizeof ec) != sizeof ec) ec = 0; else waitpid(pid, 0, 0); @@ -239,7 +245,7 @@ int posix_spawn(pid_t *__restrict res, const char *__restrict path, close(args.p[0]); - if(!ec && res) + if (!ec && res) *res = pid; fail: @@ -254,34 +260,28 @@ int posix_spawnattr_init(posix_spawnattr_t *attr) { return 0; } -int posix_spawnattr_destroy(posix_spawnattr_t *) { - return 0; -} +int posix_spawnattr_destroy(posix_spawnattr_t *) { return 0; } int posix_spawnattr_setflags(posix_spawnattr_t *attr, short flags) { - const unsigned all_flags = - POSIX_SPAWN_RESETIDS | - POSIX_SPAWN_SETPGROUP | - POSIX_SPAWN_SETSIGDEF | - POSIX_SPAWN_SETSIGMASK | - POSIX_SPAWN_SETSCHEDPARAM | - POSIX_SPAWN_SETSCHEDULER | - POSIX_SPAWN_USEVFORK | - POSIX_SPAWN_SETSID; - if(flags & ~all_flags) + const unsigned all_flags = POSIX_SPAWN_RESETIDS | POSIX_SPAWN_SETPGROUP | + POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK | + POSIX_SPAWN_SETSCHEDPARAM | POSIX_SPAWN_SETSCHEDULER | + POSIX_SPAWN_USEVFORK | POSIX_SPAWN_SETSID; + if (flags & ~all_flags) return EINVAL; attr->__flags = flags; return 0; } -int posix_spawnattr_setsigdefault(posix_spawnattr_t *__restrict attr, - const sigset_t *__restrict sigdefault) { +int posix_spawnattr_setsigdefault( + posix_spawnattr_t *__restrict attr, const sigset_t *__restrict sigdefault +) { attr->__def = *sigdefault; return 0; } -int posix_spawnattr_setschedparam(posix_spawnattr_t *__restrict, - const struct sched_param *__restrict) { +int +posix_spawnattr_setschedparam(posix_spawnattr_t *__restrict, const struct sched_param *__restrict) { __ensure(!"Not implemented"); __builtin_unreachable(); } @@ -291,8 +291,8 @@ int posix_spawnattr_setschedpolicy(posix_spawnattr_t *, int) { __builtin_unreachable(); } -int posix_spawnattr_setsigmask(posix_spawnattr_t *__restrict attr, - const sigset_t *__restrict sigmask) { +int +posix_spawnattr_setsigmask(posix_spawnattr_t *__restrict attr, const sigset_t *__restrict sigmask) { attr->__mask = *sigmask; return 0; } @@ -309,7 +309,7 @@ int posix_spawn_file_actions_init(posix_spawn_file_actions_t *file_actions) { int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *file_actions) { struct fdop *op = (struct fdop *)file_actions->__actions, *next; - while(op) { + while (op) { next = op->next; free(op); op = next; @@ -317,60 +317,68 @@ int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *file_actions) { return 0; } -int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *file_actions, - int fildes, int newfildes) { +int posix_spawn_file_actions_adddup2( + posix_spawn_file_actions_t *file_actions, int fildes, int newfildes +) { struct fdop *op = (struct fdop *)malloc(sizeof *op); - if(!op) + if (!op) return ENOMEM; op->cmd = FDOP_DUP2; op->srcfd = fildes; op->fd = newfildes; - if((op->next = (struct fdop *)file_actions->__actions)) + if ((op->next = (struct fdop *)file_actions->__actions)) op->next->prev = op; op->prev = 0; file_actions->__actions = op; return 0; } -int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *file_actions, - int fildes) { +int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *file_actions, int fildes) { struct fdop *op = (struct fdop *)malloc(sizeof *op); - if(!op) + if (!op) return ENOMEM; op->cmd = FDOP_CLOSE; op->fd = fildes; - if((op->next = (struct fdop *)file_actions->__actions)) + if ((op->next = (struct fdop *)file_actions->__actions)) op->next->prev = op; op->prev = 0; file_actions->__actions = op; return 0; } -int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *__restrict file_actions, - int fildes, const char *__restrict path, int oflag, mode_t mode) { +int posix_spawn_file_actions_addopen( + posix_spawn_file_actions_t *__restrict file_actions, + int fildes, + const char *__restrict path, + int oflag, + mode_t mode +) { struct fdop *op = (struct fdop *)malloc(sizeof *op + strlen(path) + 1); - if(!op) + if (!op) return ENOMEM; op->cmd = FDOP_OPEN; op->fd = fildes; op->oflag = oflag; op->mode = mode; strcpy(op->path, path); - if((op->next = (struct fdop *)file_actions->__actions)) + if ((op->next = (struct fdop *)file_actions->__actions)) op->next->prev = op; op->prev = 0; file_actions->__actions = op; return 0; } -int posix_spawnp(pid_t *__restrict pid, const char *__restrict file, - const posix_spawn_file_actions_t *file_actions, - const posix_spawnattr_t *__restrict attrp, - char *const argv[], char *const envp[]) { +int posix_spawnp( + pid_t *__restrict pid, + const char *__restrict file, + const posix_spawn_file_actions_t *file_actions, + const posix_spawnattr_t *__restrict attrp, + char *const argv[], + char *const envp[] +) { posix_spawnattr_t spawnp_attr = {}; - if(attrp) + if (attrp) spawnp_attr = *attrp; - spawnp_attr.__fn = (void *)execvpe; + spawnp_attr.__fn = (void *)execvpe; return posix_spawn(pid, file, file_actions, &spawnp_attr, argv, envp); } - diff --git a/options/posix/generic/strings.cpp b/options/posix/generic/strings.cpp index 524c424406..817cad3216 100644 --- a/options/posix/generic/strings.cpp +++ b/options/posix/generic/strings.cpp @@ -1,44 +1,39 @@ -#include #include +#include -#include #include +#include #include -char *index (const char *s, int c) { - return strchr(s, c); -} +char *index(const char *s, int c) { return strchr(s, c); } -char *rindex(const char *s, int c) { - return strrchr(s, c); -} +char *rindex(const char *s, int c) { return strrchr(s, c); } namespace { - template - int ffs_generic(T i) { - //Non-portably assume a byte has 8 bits; fine in all plausible cases. - for(size_t b = 0; b < sizeof(T) * 8;) - if(i & (static_cast(0x1) << b++)) - return b; - - return 0; - } +template int ffs_generic(T i) { + // Non-portably assume a byte has 8 bits; fine in all plausible cases. + for (size_t b = 0; b < sizeof(T) * 8;) + if (i & (static_cast(0x1) << b++)) + return b; + return 0; } +} // namespace + // On RISC-V, __builtin_ffs just calls into ffs, so we can't use it here. #if defined(__has_builtin) && !defined(__riscv) -# if __has_builtin(__builtin_ffs) -# define __mlibc_ffs __builtin_ffs -# endif -# if __has_builtin(__builtin_ffsl) -# define __mlibc_ffsl __builtin_ffsl -# endif -# if __has_builtin(__builtin_ffsll) -# define __mlibc_ffsll __builtin_ffsll -# endif +#if __has_builtin(__builtin_ffs) +#define __mlibc_ffs __builtin_ffs +#endif +#if __has_builtin(__builtin_ffsl) +#define __mlibc_ffsl __builtin_ffsl +#endif +#if __has_builtin(__builtin_ffsll) +#define __mlibc_ffsll __builtin_ffsll +#endif #endif int ffs(int i) { @@ -50,10 +45,10 @@ int ffs(int i) { } /* - Both ffsl() and ffsll() are glibc extensions - defined in string.h. They are however implemented - here because of similarity in logic and - shared code. + Both ffsl() and ffsll() are glibc extensions + defined in string.h. They are however implemented + here because of similarity in logic and + shared code. */ int ffsl(long i) { @@ -74,15 +69,15 @@ int ffsll(long long i) { int strcasecmp(const char *a, const char *b) { size_t i = 0; - while(true) { + while (true) { unsigned char a_byte = tolower(a[i]); unsigned char b_byte = tolower(b[i]); - if(!a_byte && !b_byte) + if (!a_byte && !b_byte) return 0; // If only one char is null, one of the following cases applies. - if(a_byte < b_byte) + if (a_byte < b_byte) return -1; - if(a_byte > b_byte) + if (a_byte > b_byte) return 1; i++; } @@ -93,15 +88,8 @@ int strncasecmp(const char *a, const char *b, size_t size) { } // Marked as obsolete in posix 2008 but used by at least tracker -int bcmp(const void *s1, const void *s2, size_t n) { - return memcmp(s1, s2, n); -} - -void bcopy(const void *s1, void *s2, size_t n) { - memmove(s2, s1, n); -} +int bcmp(const void *s1, const void *s2, size_t n) { return memcmp(s1, s2, n); } -void bzero(void *s, size_t n) { - memset(s, 0, n); -} +void bcopy(const void *s1, void *s2, size_t n) { memmove(s2, s1, n); } +void bzero(void *s, size_t n) { memset(s, 0, n); } diff --git a/options/posix/generic/sys-file.cpp b/options/posix/generic/sys-file.cpp index 8e9e0a093a..e82f7dd19e 100644 --- a/options/posix/generic/sys-file.cpp +++ b/options/posix/generic/sys-file.cpp @@ -1,13 +1,13 @@ -#include -#include #include +#include +#include #include int flock(int fd, int opt) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_flock, -1); - if(int e = mlibc::sys_flock(fd, opt); e) { + if (int e = mlibc::sys_flock(fd, opt); e) { errno = e; return -1; } @@ -15,4 +15,3 @@ int flock(int fd, int opt) { } [[gnu::alias("flock")]] int flock64(int fd, int opt); - diff --git a/options/posix/generic/sys-mman.cpp b/options/posix/generic/sys-mman.cpp index c42f3a35c1..43d597b347 100644 --- a/options/posix/generic/sys-mman.cpp +++ b/options/posix/generic/sys-mman.cpp @@ -1,17 +1,17 @@ +#include #include #include #include -#include #include -#include +#include #include #include int mprotect(void *pointer, size_t size, int prot) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_vm_protect, -1); - if(int e = mlibc::sys_vm_protect(pointer, size, prot); e) { + if (int e = mlibc::sys_vm_protect(pointer, size, prot); e) { errno = e; return -1; } @@ -20,7 +20,7 @@ int mprotect(void *pointer, size_t size, int prot) { int mlock(const void *addr, size_t len) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mlock, -1); - if(int e = mlibc::sys_mlock(addr, len); e) { + if (int e = mlibc::sys_mlock(addr, len); e) { errno = e; return -1; } @@ -29,7 +29,7 @@ int mlock(const void *addr, size_t len) { int mlockall(int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mlockall, -1); - if(int e = mlibc::sys_mlockall(flags); e) { + if (int e = mlibc::sys_mlockall(flags); e) { errno = e; return -1; } @@ -38,7 +38,7 @@ int mlockall(int flags) { int munlock(const void *addr, size_t len) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_munlock, -1); - if(int e = mlibc::sys_munlock(addr, len); e) { + if (int e = mlibc::sys_munlock(addr, len); e) { errno = e; return -1; } @@ -47,23 +47,24 @@ int munlock(const void *addr, size_t len) { int munlockall(void) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_munlockall, -1); - if(int e = mlibc::sys_munlockall(); e) { + if (int e = mlibc::sys_munlockall(); e) { errno = e; return -1; } return 0; } - int posix_madvise(void *, size_t, int) { - mlibc::infoLogger() << "\e[31m" "mlibc: posix_madvise() fails unconditionally" "\e[39m" - << frg::endlog; + mlibc::infoLogger() << "\e[31m" + "mlibc: posix_madvise() fails unconditionally" + "\e[39m" + << frg::endlog; return ENOSYS; } int msync(void *addr, size_t length, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_msync, -1); - if(int e = mlibc::sys_msync(addr, length, flags); e) { + if (int e = mlibc::sys_msync(addr, length, flags); e) { errno = e; return -1; } @@ -75,7 +76,7 @@ void *mremap(void *pointer, size_t size, size_t new_size, int flags, ...) { void *window; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_vm_remap, (void *)-1); - if(int e = mlibc::sys_vm_remap(pointer, size, new_size, &window); e) { + if (int e = mlibc::sys_vm_remap(pointer, size, new_size, &window); e) { errno = e; return (void *)-1; } @@ -89,17 +90,18 @@ int remap_file_pages(void *, size_t, int, size_t, int) { void *mmap(void *hint, size_t size, int prot, int flags, int fd, off_t offset) { void *window; - if(int e = mlibc::sys_vm_map(hint, size, prot, flags, fd, offset, &window); e) { + if (int e = mlibc::sys_vm_map(hint, size, prot, flags, fd, offset, &window); e) { errno = e; return (void *)-1; } return window; } -[[gnu::alias("mmap")]] void *mmap64(void *hint, size_t size, int prot, int flags, int fd, off64_t offset); +[[gnu::alias("mmap")]] void * +mmap64(void *hint, size_t size, int prot, int flags, int fd, off64_t offset); int munmap(void *pointer, size_t size) { - if(int e = mlibc::sys_vm_unmap(pointer, size); e) { + if (int e = mlibc::sys_vm_unmap(pointer, size); e) { errno = e; return -1; } @@ -108,29 +110,29 @@ int munmap(void *pointer, size_t size) { // The implementation of shm_open and shm_unlink is taken from musl. namespace { - char *shm_mapname(const char *name, char *buf) { - char *p; - while(*name == '/') - name++; - if(*(p = strchrnul(name, '/')) || p == name || - (p - name <= 2 && name[0] == '.' && p[-1] == '.')) { - errno = EINVAL; - return 0; - } - if(p - name > NAME_MAX) { - errno = ENAMETOOLONG; - return 0; - } - memcpy(buf, "/dev/shm/", 9); - memcpy(buf + 9, name, p - name + 1); - return buf; +char *shm_mapname(const char *name, char *buf) { + char *p; + while (*name == '/') + name++; + if (*(p = strchrnul(name, '/')) || p == name || + (p - name <= 2 && name[0] == '.' && p[-1] == '.')) { + errno = EINVAL; + return 0; + } + if (p - name > NAME_MAX) { + errno = ENAMETOOLONG; + return 0; } + memcpy(buf, "/dev/shm/", 9); + memcpy(buf + 9, name, p - name + 1); + return buf; } +} // namespace int shm_open(const char *name, int flags, mode_t mode) { int cs; char buf[NAME_MAX + 10]; - if(!(name = shm_mapname(name, buf))) + if (!(name = shm_mapname(name, buf))) return -1; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); int fd = open(name, flags | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, mode); @@ -140,7 +142,7 @@ int shm_open(const char *name, int flags, mode_t mode) { int shm_unlink(const char *name) { char buf[NAME_MAX + 10]; - if(!(name = shm_mapname(name, buf))) + if (!(name = shm_mapname(name, buf))) return -1; return unlink(name); } @@ -150,7 +152,7 @@ int memfd_create(const char *name, unsigned int flags) { int ret = -1; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_memfd_create, -1); - if(int e = mlibc::sys_memfd_create(name, flags, &ret)) { + if (int e = mlibc::sys_memfd_create(name, flags, &ret)) { errno = e; return -1; } @@ -160,7 +162,7 @@ int memfd_create(const char *name, unsigned int flags) { int madvise(void *addr, size_t length, int advice) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_madvise, -1); - if(int e = mlibc::sys_madvise(addr, length, advice)) { + if (int e = mlibc::sys_madvise(addr, length, advice)) { errno = e; return -1; } @@ -170,7 +172,7 @@ int madvise(void *addr, size_t length, int advice) { int mincore(void *addr, size_t length, unsigned char *vec) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_munlockall, -1); - if(int e = mlibc::sys_mincore(addr, length, vec); e) { + if (int e = mlibc::sys_mincore(addr, length, vec); e) { errno = e; return -1; } diff --git a/options/posix/generic/sys-resource.cpp b/options/posix/generic/sys-resource.cpp index a87f284685..60a8925ed5 100644 --- a/options/posix/generic/sys-resource.cpp +++ b/options/posix/generic/sys-resource.cpp @@ -9,7 +9,7 @@ int getpriority(int which, id_t who) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getpriority, -1); int value = 0; - if(int e = mlibc::sys_getpriority(which, who, &value); e) { + if (int e = mlibc::sys_getpriority(which, who, &value); e) { errno = e; } return value; @@ -17,7 +17,7 @@ int getpriority(int which, id_t who) { int setpriority(int which, id_t who, int prio) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setpriority, -1); - if(int e = mlibc::sys_setpriority(which, who, prio); e) { + if (int e = mlibc::sys_setpriority(which, who, prio); e) { errno = e; return -1; } @@ -26,7 +26,7 @@ int setpriority(int which, id_t who, int prio) { int getrusage(int scope, struct rusage *usage) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getrusage, -1); - if(int e = mlibc::sys_getrusage(scope, usage); e) { + if (int e = mlibc::sys_getrusage(scope, usage); e) { errno = e; return -1; } @@ -35,7 +35,7 @@ int getrusage(int scope, struct rusage *usage) { int getrlimit(int resource, struct rlimit *limit) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getrlimit, -1); - if(int e = mlibc::sys_getrlimit(resource, limit); e) { + if (int e = mlibc::sys_getrlimit(resource, limit); e) { errno = e; return -1; } @@ -46,7 +46,7 @@ int getrlimit(int resource, struct rlimit *limit) { int setrlimit(int resource, const struct rlimit *limit) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setrlimit, -1); - if(int e = mlibc::sys_setrlimit(resource, limit); e) { + if (int e = mlibc::sys_setrlimit(resource, limit); e) { errno = e; return -1; } diff --git a/options/posix/generic/sys-select.cpp b/options/posix/generic/sys-select.cpp index 8fbc468e10..2afcdcef61 100644 --- a/options/posix/generic/sys-select.cpp +++ b/options/posix/generic/sys-select.cpp @@ -1,8 +1,8 @@ +#include #include #include #include -#include #include #include @@ -21,12 +21,15 @@ void __FD_SET(int fd, fd_set *set) { __ensure(fd < FD_SETSIZE); set->fds_bits[fd / 8] |= 1 << (fd % 8); } -void __FD_ZERO(fd_set *set) { - memset(set->fds_bits, 0, sizeof(fd_set)); -} +void __FD_ZERO(fd_set *set) { memset(set->fds_bits, 0, sizeof(fd_set)); } -int select(int num_fds, fd_set *__restrict read_set, fd_set *__restrict write_set, - fd_set *__restrict except_set, struct timeval *__restrict timeout) { +int select( + int num_fds, + fd_set *__restrict read_set, + fd_set *__restrict write_set, + fd_set *__restrict except_set, + struct timeval *__restrict timeout +) { int num_events = 0; struct timespec timeouts = {}; struct timespec *timeout_ptr = NULL; @@ -36,21 +39,31 @@ int select(int num_fds, fd_set *__restrict read_set, fd_set *__restrict write_se timeout_ptr = &timeouts; } - MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pselect, -1); - if(int e = mlibc::sys_pselect(num_fds, read_set, write_set, except_set, - timeout_ptr, NULL, &num_events); e) { + MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pselect, -1); + if (int e = mlibc::sys_pselect( + num_fds, read_set, write_set, except_set, timeout_ptr, NULL, &num_events + ); + e) { errno = e; return -1; } return num_events; } -int pselect(int num_fds, fd_set *__restrict read_set, fd_set *__restrict write_set, - fd_set *__restrict except_set, const struct timespec *timeout, const sigset_t *sigmask) { +int pselect( + int num_fds, + fd_set *__restrict read_set, + fd_set *__restrict write_set, + fd_set *__restrict except_set, + const struct timespec *timeout, + const sigset_t *sigmask +) { int num_events = 0; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pselect, -1); - if(int e = mlibc::sys_pselect(num_fds, read_set, write_set, except_set, - timeout, sigmask, &num_events); e) { + if (int e = mlibc::sys_pselect( + num_fds, read_set, write_set, except_set, timeout, sigmask, &num_events + ); + e) { errno = e; return -1; } diff --git a/options/posix/generic/sys-sem.cpp b/options/posix/generic/sys-sem.cpp index ac3df69ac5..ae552cca6a 100644 --- a/options/posix/generic/sys-sem.cpp +++ b/options/posix/generic/sys-sem.cpp @@ -7,14 +7,14 @@ #include int semget(key_t key, int n, int fl) { - if(n > USHRT_MAX) { + if (n > USHRT_MAX) { errno = EINVAL; return -1; } int id = 0; auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_semget, -1); - if(int e = sysdep(key, n, fl, &id); e) { + if (int e = sysdep(key, n, fl, &id); e) { errno = e; return -1; } @@ -42,7 +42,7 @@ int semctl(int id, int num, int cmd, ...) { va_end(ap); auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_semctl, -1); - if(int e = sysdep(id, num, cmd, semun.buf, &ret); e) { + if (int e = sysdep(id, num, cmd, semun.buf, &ret); e) { errno = e; return -1; } diff --git a/options/posix/generic/sys-socket.cpp b/options/posix/generic/sys-socket.cpp index 037a994a0f..2f593fd4e5 100644 --- a/options/posix/generic/sys-socket.cpp +++ b/options/posix/generic/sys-socket.cpp @@ -11,17 +11,19 @@ int accept(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict addr_length) { int newfd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_accept, -1); - if(int e = mlibc::sys_accept(fd, &newfd, addr_ptr, addr_length, 0); e) { + if (int e = mlibc::sys_accept(fd, &newfd, addr_ptr, addr_length, 0); e) { errno = e; return -1; } return newfd; } -int accept4(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict addr_length, int flags) { +int accept4( + int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict addr_length, int flags +) { int newfd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_accept, -1); - if(int e = mlibc::sys_accept(fd, &newfd, addr_ptr, addr_length, flags); e) { + if (int e = mlibc::sys_accept(fd, &newfd, addr_ptr, addr_length, flags); e) { errno = e; return -1; } @@ -31,7 +33,7 @@ int accept4(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict int bind(int fd, const struct sockaddr *addr_ptr, socklen_t addr_len) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_bind, -1); - if(int e = mlibc::sys_bind(fd, addr_ptr, addr_len); e) { + if (int e = mlibc::sys_bind(fd, addr_ptr, addr_len); e) { errno = e; return -1; } @@ -40,7 +42,7 @@ int bind(int fd, const struct sockaddr *addr_ptr, socklen_t addr_len) { int connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_len) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_connect, -1); - if(int e = mlibc::sys_connect(fd, addr_ptr, addr_len); e) { + if (int e = mlibc::sys_connect(fd, addr_ptr, addr_len); e) { errno = e; return -1; } @@ -50,7 +52,7 @@ int connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_len) { int getpeername(int fd, struct sockaddr *addr_ptr, socklen_t *__restrict addr_length) { socklen_t actual_length; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_peername, -1); - if(int e = mlibc::sys_peername(fd, addr_ptr, *addr_length, &actual_length); e) { + if (int e = mlibc::sys_peername(fd, addr_ptr, *addr_length, &actual_length); e) { errno = e; return -1; } @@ -61,7 +63,7 @@ int getpeername(int fd, struct sockaddr *addr_ptr, socklen_t *__restrict addr_le int getsockname(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restrict addr_length) { socklen_t actual_length; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sockname, -1); - if(int e = mlibc::sys_sockname(fd, addr_ptr, *addr_length, &actual_length); e) { + if (int e = mlibc::sys_sockname(fd, addr_ptr, *addr_length, &actual_length); e) { errno = e; return -1; } @@ -69,15 +71,14 @@ int getsockname(int fd, struct sockaddr *__restrict addr_ptr, socklen_t *__restr return 0; } -int getsockopt(int fd, int layer, int number, - void *__restrict buffer, socklen_t *__restrict size) { +int getsockopt(int fd, int layer, int number, void *__restrict buffer, socklen_t *__restrict size) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getsockopt, -1); return mlibc::sys_getsockopt(fd, layer, number, buffer, size); } int listen(int fd, int backlog) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_listen, -1); - if(int e = mlibc::sys_listen(fd, backlog); e) { + if (int e = mlibc::sys_listen(fd, backlog); e) { errno = e; return -1; } @@ -88,11 +89,17 @@ ssize_t recv(int sockfd, void *__restrict buf, size_t len, int flags) { return recvfrom(sockfd, buf, len, flags, NULL, NULL); } -ssize_t recvfrom(int sockfd, void *__restrict buf, size_t len, int flags, - struct sockaddr *__restrict src_addr, socklen_t *__restrict addrlen) { - if(mlibc::sys_recvfrom) { +ssize_t recvfrom( + int sockfd, + void *__restrict buf, + size_t len, + int flags, + struct sockaddr *__restrict src_addr, + socklen_t *__restrict addrlen +) { + if (mlibc::sys_recvfrom) { ssize_t length; - if(int e = mlibc::sys_recvfrom(sockfd, buf, len, flags, src_addr, addrlen, &length); e) { + if (int e = mlibc::sys_recvfrom(sockfd, buf, len, flags, src_addr, addrlen, &length); e) { errno = e; return -1; } @@ -115,7 +122,7 @@ ssize_t recvfrom(int sockfd, void *__restrict buf, size_t len, int flags, if (ret < 0) return ret; - if(addrlen) + if (addrlen) *addrlen = hdr.msg_namelen; return ret; } @@ -123,7 +130,7 @@ ssize_t recvfrom(int sockfd, void *__restrict buf, size_t len, int flags, ssize_t recvmsg(int fd, struct msghdr *hdr, int flags) { ssize_t length; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_msg_recv, -1); - if(int e = mlibc::sys_msg_recv(fd, hdr, flags, &length); e) { + if (int e = mlibc::sys_msg_recv(fd, hdr, flags, &length); e) { errno = e; return -1; } @@ -139,11 +146,18 @@ ssize_t send(int fd, const void *buffer, size_t size, int flags) { return sendto(fd, buffer, size, flags, nullptr, 0); } -ssize_t sendto(int fd, const void *buffer, size_t size, int flags, - const struct sockaddr *sock_addr, socklen_t addr_length) { - if(mlibc::sys_sendto) { +ssize_t sendto( + int fd, + const void *buffer, + size_t size, + int flags, + const struct sockaddr *sock_addr, + socklen_t addr_length +) { + if (mlibc::sys_sendto) { ssize_t length; - if(int e = mlibc::sys_sendto(fd, buffer, size, flags, sock_addr, addr_length, &length); e) { + if (int e = mlibc::sys_sendto(fd, buffer, size, flags, sock_addr, addr_length, &length); + e) { errno = e; return -1; } @@ -164,12 +178,12 @@ ssize_t sendto(int fd, const void *buffer, size_t size, int flags, } ssize_t sendmsg(int fd, const struct msghdr *hdr, int flags) { - if(hdr->msg_iovlen > IOV_MAX) + if (hdr->msg_iovlen > IOV_MAX) return EMSGSIZE; ssize_t length; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_msg_send, -1); - if(int e = mlibc::sys_msg_send(fd, hdr, flags, &length); e) { + if (int e = mlibc::sys_msg_send(fd, hdr, flags, &length); e) { errno = e; return -1; } @@ -181,15 +195,14 @@ int sendmmsg(int, struct mmsghdr *, unsigned int, int) { __builtin_unreachable(); } -int setsockopt(int fd, int layer, int number, - const void *buffer, socklen_t size) { +int setsockopt(int fd, int layer, int number, const void *buffer, socklen_t size) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setsockopt, -1); return mlibc::sys_setsockopt(fd, layer, number, buffer, size); } int shutdown(int sockfd, int how) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_shutdown, -1); - if(int e = sysdep(sockfd, how); e) { + if (int e = sysdep(sockfd, how); e) { errno = e; return -1; } @@ -205,7 +218,7 @@ int sockatmark(int) { int socket(int family, int type, int protocol) { int fd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_socket, -1); - if(int e = mlibc::sys_socket(family, type, protocol, &fd); e) { + if (int e = mlibc::sys_socket(family, type, protocol, &fd); e) { errno = e; return -1; } @@ -214,7 +227,7 @@ int socket(int family, int type, int protocol) { int socketpair(int domain, int type, int protocol, int sv[2]) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_socketpair, -1); - if(int e = mlibc::sys_socketpair(domain, type, protocol, sv); e) { + if (int e = mlibc::sys_socketpair(domain, type, protocol, sv); e) { errno = e; return -1; } @@ -222,4 +235,3 @@ int socketpair(int domain, int type, int protocol, int sv[2]) { } // connectpair() is provided by the platform - diff --git a/options/posix/generic/sys-stat.cpp b/options/posix/generic/sys-stat.cpp index b5af81f46d..b26c409b01 100644 --- a/options/posix/generic/sys-stat.cpp +++ b/options/posix/generic/sys-stat.cpp @@ -1,6 +1,6 @@ -#include #include +#include #include #include @@ -8,7 +8,7 @@ int chmod(const char *pathname, mode_t mode) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_chmod, -1); - if(int e = mlibc::sys_chmod(pathname, mode); e) { + if (int e = mlibc::sys_chmod(pathname, mode); e) { errno = e; return -1; } @@ -17,7 +17,7 @@ int chmod(const char *pathname, mode_t mode) { int fchmod(int fd, mode_t mode) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchmod, -1); - if(int e = mlibc::sys_fchmod(fd, mode); e) { + if (int e = mlibc::sys_fchmod(fd, mode); e) { errno = e; return -1; } @@ -26,7 +26,7 @@ int fchmod(int fd, mode_t mode) { int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchmodat, -1); - if(int e = mlibc::sys_fchmodat(dirfd, pathname, mode, flags); e) { + if (int e = mlibc::sys_fchmodat(dirfd, pathname, mode, flags); e) { errno = e; return -1; } @@ -35,7 +35,7 @@ int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags) { int fstatat(int dirfd, const char *path, struct stat *result, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_stat, -1); - if(int e = mlibc::sys_stat(mlibc::fsfd_target::fd_path, dirfd, path, flags, result); e) { + if (int e = mlibc::sys_stat(mlibc::fsfd_target::fd_path, dirfd, path, flags, result); e) { errno = e; return -1; } @@ -55,7 +55,7 @@ int futimens(int fd, const struct timespec times[2]) { int mkdir(const char *path, mode_t mode) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mkdir, -1); - if(int e = mlibc::sys_mkdir(path, mode); e) { + if (int e = mlibc::sys_mkdir(path, mode); e) { errno = e; return -1; } @@ -65,16 +65,14 @@ int mkdir(const char *path, mode_t mode) { int mkdirat(int dirfd, const char *path, mode_t mode) { mlibc::infoLogger() << "\e[31mmlibc: mkdirat() ignores its mode\e[39m" << frg::endlog; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mkdirat, -1); - if(int e = mlibc::sys_mkdirat(dirfd, path, mode); e) { + if (int e = mlibc::sys_mkdirat(dirfd, path, mode); e) { errno = e; return -1; } return 0; } -int mkfifo(const char *path, mode_t mode) { - return mkfifoat(AT_FDCWD, path, mode); -} +int mkfifo(const char *path, mode_t mode) { return mkfifoat(AT_FDCWD, path, mode); } int mkfifoat(int dirfd, const char *path, mode_t mode) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mkfifoat, -1); @@ -86,9 +84,7 @@ int mkfifoat(int dirfd, const char *path, mode_t mode) { return 0; } -int mknod(const char *path, mode_t mode, dev_t dev) { - return mknodat(AT_FDCWD, path, mode, dev); -} +int mknod(const char *path, mode_t mode, dev_t dev) { return mknodat(AT_FDCWD, path, mode, dev); } int mknodat(int dirfd, const char *path, mode_t mode, dev_t dev) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_mknodat, -1); @@ -111,7 +107,7 @@ mode_t umask(mode_t mode) { } int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags) { - if(pathname == nullptr) { + if (pathname == nullptr) { errno = EINVAL; return -1; } @@ -127,7 +123,7 @@ int utimensat(int dirfd, const char *pathname, const struct timespec times[2], i int stat(const char *path, struct stat *result) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_stat, -1); - if(int e = mlibc::sys_stat(mlibc::fsfd_target::path, -1, path, 0, result); e) { + if (int e = mlibc::sys_stat(mlibc::fsfd_target::path, -1, path, 0, result); e) { errno = e; return -1; } @@ -136,8 +132,8 @@ int stat(const char *path, struct stat *result) { int lstat(const char *path, struct stat *result) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_stat, -1); - if(int e = mlibc::sys_stat(mlibc::fsfd_target::path, - -1, path, AT_SYMLINK_NOFOLLOW, result); e) { + if (int e = mlibc::sys_stat(mlibc::fsfd_target::path, -1, path, AT_SYMLINK_NOFOLLOW, result); + e) { errno = e; return -1; } @@ -148,7 +144,7 @@ int lstat(const char *path, struct stat *result) { int fstat(int fd, struct stat *result) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_stat, -1); - if(int e = mlibc::sys_stat(mlibc::fsfd_target::fd, fd, "", 0, result); e) { + if (int e = mlibc::sys_stat(mlibc::fsfd_target::fd, fd, "", 0, result); e) { errno = e; return -1; } diff --git a/options/posix/generic/sys-statvfs.cpp b/options/posix/generic/sys-statvfs.cpp index dc7e21544c..61a0e6a955 100644 --- a/options/posix/generic/sys-statvfs.cpp +++ b/options/posix/generic/sys-statvfs.cpp @@ -6,7 +6,7 @@ int statvfs(const char *path, struct statvfs *out) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_statvfs, -1); - if(int e = mlibc::sys_statvfs(path, out); e) { + if (int e = mlibc::sys_statvfs(path, out); e) { errno = e; return -1; } @@ -17,7 +17,7 @@ int statvfs(const char *path, struct statvfs *out) { int fstatvfs(int fd, struct statvfs *out) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fstatvfs, -1); - if(int e = mlibc::sys_fstatvfs(fd, out); e) { + if (int e = mlibc::sys_fstatvfs(fd, out); e) { errno = e; return -1; } @@ -25,4 +25,3 @@ int fstatvfs(int fd, struct statvfs *out) { } [[gnu::alias("fstatvfs")]] int fstatvfs64(int, struct statvfs64 *); - diff --git a/options/posix/generic/sys-time.cpp b/options/posix/generic/sys-time.cpp index 5cc0fe5282..d068e69f89 100644 --- a/options/posix/generic/sys-time.cpp +++ b/options/posix/generic/sys-time.cpp @@ -10,9 +10,9 @@ int gettimeofday(struct timeval *__restrict result, void *__restrict unused) { (void)unused; // Linux just ignores gettimeofday(). - if(result) { + if (result) { long nanos; - if(int e = mlibc::sys_clock_get(CLOCK_REALTIME, &result->tv_sec, &nanos); e) { + if (int e = mlibc::sys_clock_get(CLOCK_REALTIME, &result->tv_sec, &nanos); e) { errno = e; return -1; } @@ -29,7 +29,7 @@ int settimeofday(const struct timeval *, const struct timezone *) { void timeradd(const struct timeval *a, const struct timeval *b, struct timeval *res) { res->tv_sec = a->tv_sec + b->tv_sec; res->tv_usec = a->tv_usec + b->tv_usec; - while(res->tv_usec > 999999) { + while (res->tv_usec > 999999) { res->tv_usec -= 1000000; res->tv_sec += 1; } @@ -38,7 +38,7 @@ void timeradd(const struct timeval *a, const struct timeval *b, struct timeval * void timersub(const struct timeval *a, const struct timeval *b, struct timeval *res) { res->tv_sec = a->tv_sec - b->tv_sec; res->tv_usec = a->tv_usec - b->tv_usec; - while(res->tv_usec < 0) { + while (res->tv_usec < 0) { res->tv_usec += 1000000; res->tv_sec -= 1; } @@ -50,7 +50,7 @@ void timerclear(struct timeval *tvp) { } int timerisset(struct timeval *tvp) { - if(tvp->tv_sec != 0 || tvp->tv_usec != 0) { + if (tvp->tv_sec != 0 || tvp->tv_usec != 0) { return 1; } return 0; @@ -58,7 +58,7 @@ int timerisset(struct timeval *tvp) { int getitimer(int which, struct itimerval *curr_value) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getitimer, -1); - if(int e = mlibc::sys_getitimer(which, curr_value); e) { + if (int e = mlibc::sys_getitimer(which, curr_value); e) { errno = e; return -1; } @@ -67,7 +67,7 @@ int getitimer(int which, struct itimerval *curr_value) { int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setitimer, -1); - if(int e = mlibc::sys_setitimer(which, new_value, old_value); e) { + if (int e = mlibc::sys_setitimer(which, new_value, old_value); e) { errno = e; return -1; } @@ -76,16 +76,18 @@ int setitimer(int which, const struct itimerval *new_value, struct itimerval *ol int timer_create(clockid_t clk, struct sigevent *__restrict evp, timer_t *__restrict res) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_timer_create, -1); - if(int e = mlibc::sys_timer_create(clk, evp, res); e) { + if (int e = mlibc::sys_timer_create(clk, evp, res); e) { errno = e; return -1; } return 0; } -int timer_settime(timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old) { +int timer_settime( + timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old +) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_timer_settime, -1); - if(int e = mlibc::sys_timer_settime(t, flags, val, old); e) { + if (int e = mlibc::sys_timer_settime(t, flags, val, old); e) { errno = e; return -1; } @@ -99,7 +101,7 @@ int timer_gettime(timer_t, struct itimerspec *) { int timer_delete(timer_t t) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_timer_delete, -1); - if(int e = mlibc::sys_timer_delete(t); e) { + if (int e = mlibc::sys_timer_delete(t); e) { errno = e; return -1; } diff --git a/options/posix/generic/sys-times.cpp b/options/posix/generic/sys-times.cpp index 61b6e25393..ec9dbeeeb8 100644 --- a/options/posix/generic/sys-times.cpp +++ b/options/posix/generic/sys-times.cpp @@ -3,17 +3,16 @@ #include #include -#include #include +#include #include clock_t times(struct tms *tms) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_times, -1); clock_t ret; - if(int e = mlibc::sys_times(tms, &ret); e) { + if (int e = mlibc::sys_times(tms, &ret); e) { errno = e; return -1; } return ret; } - diff --git a/options/posix/generic/sys-uio.cpp b/options/posix/generic/sys-uio.cpp index 0f14bc03ec..b4d6f31904 100644 --- a/options/posix/generic/sys-uio.cpp +++ b/options/posix/generic/sys-uio.cpp @@ -1,16 +1,16 @@ -#include -#include #include +#include #include #include -#include +#include +#include +#include #include #include #include #include -#include ssize_t readv(int fd, const struct iovec *iovs, int iovc) { ssize_t read_bytes = 0; @@ -30,8 +30,8 @@ ssize_t writev(int fd, const struct iovec *iovs, int iovc) { ssize_t written = 0; size_t bytes = 0; - for(int i = 0; i < iovc; i++) { - if(SSIZE_MAX - bytes < iovs[i].iov_len) { + for (int i = 0; i < iovc; i++) { + if (SSIZE_MAX - bytes < iovs[i].iov_len) { errno = EINVAL; return -1; } @@ -42,13 +42,13 @@ ssize_t writev(int fd, const struct iovec *iovs, int iovc) { size_t to_copy = bytes; char *bp = buffer.data(); - for(int i = 0; i < iovc; i++) { + for (int i = 0; i < iovc; i++) { size_t copy = frg::min(iovs[i].iov_len, to_copy); bp = (char *)mempcpy((void *)bp, (void *)iovs[i].iov_base, copy); to_copy -= copy; - if(to_copy == 0) + if (to_copy == 0) break; } diff --git a/options/posix/generic/sys-utsname.cpp b/options/posix/generic/sys-utsname.cpp index 3176574cd7..500101cb77 100644 --- a/options/posix/generic/sys-utsname.cpp +++ b/options/posix/generic/sys-utsname.cpp @@ -1,11 +1,11 @@ +#include #include #include -#include #include -#include #include +#include #include int uname(struct utsname *p) { @@ -15,10 +15,9 @@ int uname(struct utsname *p) { } MLIBC_CHECK_OR_ENOSYS(mlibc::sys_uname, -1); - if(int e = mlibc::sys_uname(p); e) { + if (int e = mlibc::sys_uname(p); e) { errno = e; return -1; } return 0; } - diff --git a/options/posix/generic/sys-wait.cpp b/options/posix/generic/sys-wait.cpp index 6e7cc78c56..16f6eac60a 100644 --- a/options/posix/generic/sys-wait.cpp +++ b/options/posix/generic/sys-wait.cpp @@ -1,15 +1,15 @@ +#include #include #include -#include #include -#include #include +#include int waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { auto sysdep = MLIBC_CHECK_OR_ENOSYS(mlibc::sys_waitid, -1); - if(int e = sysdep(idtype, id, info, options); e) { + if (int e = sysdep(idtype, id, info, options); e) { errno = e; return -1; } @@ -20,31 +20,28 @@ pid_t waitpid(pid_t pid, int *status, int flags) { pid_t ret; int tmp_status = 0; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_waitpid, -1); - if(int e = mlibc::sys_waitpid(pid, &tmp_status, flags, NULL, &ret); e) { + if (int e = mlibc::sys_waitpid(pid, &tmp_status, flags, NULL, &ret); e) { errno = e; return -1; } - if(status) { + if (status) { *status = tmp_status; } return ret; } -pid_t wait(int *status) { - return waitpid(-1, status, 0); -} +pid_t wait(int *status) { return waitpid(-1, status, 0); } pid_t wait3(int *status, int options, struct rusage *rusage) { - (void) rusage; - mlibc::infoLogger() << "\e[31mmlibc: wait3() is not implemented correctly\e[39m" - << frg::endlog; + (void)rusage; + mlibc::infoLogger() << "\e[31mmlibc: wait3() is not implemented correctly\e[39m" << frg::endlog; return waitpid(-1, status, options); } pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru) { pid_t ret; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_waitpid, -1); - if(int e = mlibc::sys_waitpid(pid, status, options, ru, &ret); e) { + if (int e = mlibc::sys_waitpid(pid, status, options, ru, &ret); e) { errno = e; return -1; } diff --git a/options/posix/generic/syslog.cpp b/options/posix/generic/syslog.cpp index 3beeb12c8f..1d92242bae 100644 --- a/options/posix/generic/syslog.cpp +++ b/options/posix/generic/syslog.cpp @@ -1,19 +1,19 @@ -#include -#include -#include -#include +#include #include -#include #include #include +#include +#include #include #include -#include +#include +#include +#include #include -#include #include +#include // This syslog implementation is largely taken from musl @@ -27,28 +27,30 @@ static int log_mask = 0xff; static int use_mlibc_logger = 0; static FutexLock __syslog_lock; -static const struct sockaddr_un log_addr {AF_UNIX, "/dev/log"}; +static const struct sockaddr_un log_addr{AF_UNIX, "/dev/log"}; void closelog(void) { - frg::unique_lock holder { __syslog_lock }; + frg::unique_lock holder{__syslog_lock}; close(log_fd); log_fd = -1; } static void __openlog() { log_fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); - if(log_fd >= 0) { + if (log_fd >= 0) { int ret = connect(log_fd, (const sockaddr *)&log_addr, sizeof log_addr); - if(ret) { - mlibc::infoLogger() << "\e[31mmlibc: syslog: connect returned an error, falling back to infoLogger\e[39m" << frg::endlog; + if (ret) { + mlibc::infoLogger( + ) << "\e[31mmlibc: syslog: connect returned an error, falling back to infoLogger\e[39m" + << frg::endlog; use_mlibc_logger = 1; } } } void openlog(const char *ident, int options, int facility) { - frg::unique_lock holder { __syslog_lock }; - if(ident) { + frg::unique_lock holder{__syslog_lock}; + if (ident) { size_t n = strnlen(ident, sizeof log_ident - 1); memcpy(log_ident, ident, n); log_ident[n] = 0; @@ -58,7 +60,7 @@ void openlog(const char *ident, int options, int facility) { log_options = options; log_facility = facility; - if((options & LOG_NDELAY) && log_fd < 0) + if ((options & LOG_NDELAY) && log_fd < 0) __openlog(); } @@ -71,11 +73,11 @@ int setlogmask(int mask) { } static void _vsyslog(int priority, const char *message, va_list ap) { - auto is_lost_conn = [] (int e) { + auto is_lost_conn = [](int e) { return e == ECONNREFUSED || e == ECONNRESET || e == ENOTCONN || e == EPIPE; }; - if(!(priority & log_mask)) { + if (!(priority & log_mask)) { return; } @@ -89,16 +91,16 @@ static void _vsyslog(int priority, const char *message, va_list ap) { int hlen; int fd; - if(log_fd < 0) + if (log_fd < 0) __openlog(); - if(use_mlibc_logger) { + if (use_mlibc_logger) { vsnprintf(buf, sizeof buf, message, ap); mlibc::infoLogger() << "mlibc: syslog: " << buf << frg::endlog; return; } - if(!(priority & LOG_FACMASK)) + if (!(priority & LOG_FACMASK)) priority |= log_facility; now = time(NULL); @@ -106,28 +108,39 @@ static void _vsyslog(int priority, const char *message, va_list ap) { strftime(timebuf, sizeof timebuf, "%b %e %T", &tm); pid = (log_opt & LOG_PID) ? getpid() : 0; - l = snprintf(buf, sizeof buf, "<%d>%s %n%s%s%.0d%s: ", - priority, timebuf, &hlen, log_ident, (pid ? "[" : ""), pid, (pid ? "]" : "")); + l = snprintf( + buf, + sizeof buf, + "<%d>%s %n%s%s%.0d%s: ", + priority, + timebuf, + &hlen, + log_ident, + (pid ? "[" : ""), + pid, + (pid ? "]" : "") + ); errno = errno_save; l2 = vsnprintf(buf + l, sizeof buf - l, message, ap); - if(l2 >= 0) { - if(l2 >= (long int)(sizeof buf - l)) + if (l2 >= 0) { + if (l2 >= (long int)(sizeof buf - l)) l = sizeof buf - 1; else l += l2; - if(buf[l - 1] != '\n') + if (buf[l - 1] != '\n') buf[l++] = '\n'; - if(send(log_fd, buf, l, 0) < 0 && (!is_lost_conn(errno) - || connect(log_fd, (const sockaddr *)&log_addr, sizeof log_addr) < 0 - || send(log_fd, buf, l, 0) < 0) - && (log_opt & LOG_CONS)) { - fd = open("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC); - if(fd >= 0) { + if (send(log_fd, buf, l, 0) < 0 && + (!is_lost_conn(errno) || + connect(log_fd, (const sockaddr *)&log_addr, sizeof log_addr) < 0 || + send(log_fd, buf, l, 0) < 0) && + (log_opt & LOG_CONS)) { + fd = open("/dev/console", O_WRONLY | O_NOCTTY | O_CLOEXEC); + if (fd >= 0) { dprintf(fd, "%.*s", l - hlen, buf + hlen); close(fd); } } - if(log_opt & LOG_PERROR) + if (log_opt & LOG_PERROR) dprintf(STDERR_FILENO, "%.*s", l - hlen, buf + hlen); } } @@ -141,8 +154,10 @@ void syslog(int priority, const char *format, ...) { void vsyslog(int priority, const char *message, va_list ap) { int cs; - if(!(log_mask & LOG_MASK(priority & 7)) || (priority & ~0x3ff)) { - mlibc::infoLogger() << "\e[31mmlibc: syslog: log_mask or priority out of range, not printing anything\e[39m" << frg::endlog; + if (!(log_mask & LOG_MASK(priority & 7)) || (priority & ~0x3ff)) { + mlibc::infoLogger( + ) << "\e[31mmlibc: syslog: log_mask or priority out of range, not printing anything\e[39m" + << frg::endlog; return; } pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); diff --git a/options/posix/generic/termios.cpp b/options/posix/generic/termios.cpp index 631456aa53..b38d9d9390 100644 --- a/options/posix/generic/termios.cpp +++ b/options/posix/generic/termios.cpp @@ -1,28 +1,24 @@ #ifndef _GNU_SOURCE -# define _GNU_SOURCE +#define _GNU_SOURCE #endif #include -#include #include +#include #include #include -speed_t cfgetispeed(const struct termios *tios) { - return tios->c_cflag & CBAUD; -} +speed_t cfgetispeed(const struct termios *tios) { return tios->c_cflag & CBAUD; } -speed_t cfgetospeed(const struct termios *tios) { - return tios->c_cflag & CBAUD; -} +speed_t cfgetospeed(const struct termios *tios) { return tios->c_cflag & CBAUD; } int cfsetispeed(struct termios *termios, speed_t speed) { return speed ? cfsetospeed(termios, speed) : 0; } int cfsetospeed(struct termios *termios, speed_t speed) { - if(speed & ~CBAUD) { + if (speed & ~CBAUD) { errno = EINVAL; return -1; } @@ -45,7 +41,7 @@ void cfmakeraw(struct termios *t) { int tcdrain(int fd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_tcdrain, -1); - if(int e = mlibc::sys_tcdrain(fd); e) { + if (int e = mlibc::sys_tcdrain(fd); e) { errno = e; return -1; } @@ -54,7 +50,7 @@ int tcdrain(int fd) { int tcflow(int fd, int action) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_tcflow, -1); - if(int e = mlibc::sys_tcflow(fd, action); e) { + if (int e = mlibc::sys_tcflow(fd, action); e) { errno = e; return -1; } @@ -63,7 +59,7 @@ int tcflow(int fd, int action) { int tcflush(int fd, int queue_selector) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_tcflush, -1); - if(int e = mlibc::sys_tcflush(fd, queue_selector); e) { + if (int e = mlibc::sys_tcflush(fd, queue_selector); e) { errno = e; return -1; } @@ -72,7 +68,7 @@ int tcflush(int fd, int queue_selector) { int tcgetattr(int fd, struct termios *attr) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_tcgetattr, -1); - if(int e = mlibc::sys_tcgetattr(fd, attr); e) { + if (int e = mlibc::sys_tcgetattr(fd, attr); e) { errno = e; return -1; } @@ -81,7 +77,7 @@ int tcgetattr(int fd, struct termios *attr) { pid_t tcgetsid(int fd) { int sid; - if(ioctl(fd, TIOCGSID, &sid) < 0) { + if (ioctl(fd, TIOCGSID, &sid) < 0) { return -1; } return sid; @@ -94,10 +90,9 @@ int tcsendbreak(int, int) { int tcsetattr(int fd, int opts, const struct termios *attr) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_tcsetattr, -1); - if(int e = mlibc::sys_tcsetattr(fd, opts, attr); e) { + if (int e = mlibc::sys_tcsetattr(fd, opts, attr); e) { errno = e; return -1; } return 0; } - diff --git a/options/posix/generic/time.cpp b/options/posix/generic/time.cpp index 14193afc6e..fc97b71dbd 100644 --- a/options/posix/generic/time.cpp +++ b/options/posix/generic/time.cpp @@ -10,49 +10,71 @@ namespace { int month_to_day(int month) { - switch(month){ - case 0: return 0; - case 1: return 31; - case 2: return 59; - case 3: return 90; - case 4: return 120; - case 5: return 151; - case 6: return 181; - case 7: return 212; - case 8: return 243; - case 9: return 273; - case 10: return 304; - case 11: return 334; + switch (month) { + case 0: + return 0; + case 1: + return 31; + case 2: + return 59; + case 3: + return 90; + case 4: + return 120; + case 5: + return 151; + case 6: + return 181; + case 7: + return 212; + case 8: + return 243; + case 9: + return 273; + case 10: + return 304; + case 11: + return 334; } return -1; } -int is_leapyear(int year) { - return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); -} +int is_leapyear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } -int month_and_year_to_day_in_year(int month, int year){ +int month_and_year_to_day_in_year(int month, int year) { int day = month_to_day(month); - if(is_leapyear(year) && month < 2) + if (is_leapyear(year) && month < 2) return day + 1; return day; } int target_determination(int month) { - switch(month){ - case 0: return 3; - case 1: return 14; - case 2: return 14; - case 3: return 4; - case 4: return 9; - case 5: return 6; - case 6: return 11; - case 7: return 8; - case 8: return 5; - case 9: return 10; - case 10: return 7; - case 11: return 12; + switch (month) { + case 0: + return 3; + case 1: + return 14; + case 2: + return 14; + case 3: + return 4; + case 4: + return 9; + case 5: + return 6; + case 6: + return 11; + case 7: + return 8; + case 8: + return 5; + case 9: + return 10; + case 10: + return 7; + case 11: + return 12; } return -1; @@ -64,24 +86,24 @@ int doom_determination(int full_year) { int year = full_year % 100; - if(year % 2) + if (year % 2) year += 11; year /= 2; - if(year % 2) + if (year % 2) year += 11; return 7 - (year % 7) + anchor; } -//Determine day of week through the doomsday algorithm. +// Determine day of week through the doomsday algorithm. int day_determination(int day, int month, int year) { int doom = doom_determination(year); bool leap = is_leapyear(year); int target = target_determination(month); - if(leap && month < 2) + if (leap && month < 2) target++; int doom_dif = (day - target) % 7; @@ -104,13 +126,17 @@ struct strptime_internal_state { size_t input_index; }; -char *strptime_internal(const char *__restrict input, const char *__restrict format, - struct tm *__restrict tm, struct strptime_internal_state *__restrict state) { - auto matchLanginfoItem = [&] (int start, size_t num, int &dest, bool &flag) -> bool { - for(size_t i = start; i < (start + num); i++) { +char *strptime_internal( + const char *__restrict input, + const char *__restrict format, + struct tm *__restrict tm, + struct strptime_internal_state *__restrict state +) { + auto matchLanginfoItem = [&](int start, size_t num, int &dest, bool &flag) -> bool { + for (size_t i = start; i < (start + num); i++) { const char *mon = nl_langinfo(i); size_t len = strlen(mon); - if(mlibc::strncasecmp(&input[state->input_index], mon, len)) + if (mlibc::strncasecmp(&input[state->input_index], mon, len)) continue; state->input_index += len; dest = i - start; @@ -120,356 +146,357 @@ char *strptime_internal(const char *__restrict input, const char *__restrict for return false; }; - auto matchNumericRange = [&] (int start, int end, int &dest, bool *flag) -> bool { + auto matchNumericRange = [&](int start, int end, int &dest, bool *flag) -> bool { int product = 0, n = 0; sscanf(&input[state->input_index], "%d%n", &product, &n); - if(n == 0 || 2 < n) + if (n == 0 || 2 < n) return false; - if(product < start || product > end) + if (product < start || product > end) return false; state->input_index += n; dest = product; - if(flag) *flag = true; + if (flag) + *flag = true; return true; }; - while(isspace(input[state->input_index])) + while (isspace(input[state->input_index])) state->input_index++; - if(input[state->input_index] == '\0') + if (input[state->input_index] == '\0') return NULL; - while(format[state->format_index] != '\0'){ - if(format[state->format_index] != '%'){ - if(isspace(format[state->format_index])){ - while(isspace(input[state->input_index++])); + while (format[state->format_index] != '\0') { + if (format[state->format_index] != '%') { + if (isspace(format[state->format_index])) { + while (isspace(input[state->input_index++])) + ; state->input_index--; - } - else { - if(format[state->format_index] != input[state->input_index++]) + } else { + if (format[state->format_index] != input[state->input_index++]) return NULL; } state->format_index++; continue; } state->format_index++; - switch(format[state->format_index]){ - case '%': - if(input[state->input_index++] != '%') - return NULL; - break; - case 'a': - case 'A': { - if (!matchLanginfoItem(DAY_1, 7, tm->tm_wday, state->has_day_of_week) && \ - !matchLanginfoItem(ABDAY_1, 7, tm->tm_wday, state->has_day_of_week)) - return NULL; - break; - } - case 'b': - case 'B': - case 'h': { - if (!matchLanginfoItem(MON_1, 12, tm->tm_mon, state->has_month) && \ - !matchLanginfoItem(ABMON_1, 12, tm->tm_mon, state->has_month)) - return NULL; - break; - } - case 'c': - __ensure(!"strptime() %c directive unimplemented."); - __builtin_unreachable(); - break; - case 'C': { - int product = 0, n = 0; - sscanf(&input[state->input_index], "%d%n", &product, &n); - if(n == 0 || 2 < n) - return NULL; - state->input_index += n; - state->century = product; - state->has_century = true; - break; - } - case 'd': //`%d` and `%e` are equivalent - case 'e': { - if(!matchNumericRange(1, 31, tm->tm_mday, &state->has_day_of_month)) - return NULL; - break; - } - case 'D': { //equivalent to `%m/%d/%y` - size_t pre_fi = state->format_index; - state->format_index = 0; + switch (format[state->format_index]) { + case '%': + if (input[state->input_index++] != '%') + return NULL; + break; + case 'a': + case 'A': { + if (!matchLanginfoItem(DAY_1, 7, tm->tm_wday, state->has_day_of_week) && + !matchLanginfoItem(ABDAY_1, 7, tm->tm_wday, state->has_day_of_week)) + return NULL; + break; + } + case 'b': + case 'B': + case 'h': { + if (!matchLanginfoItem(MON_1, 12, tm->tm_mon, state->has_month) && + !matchLanginfoItem(ABMON_1, 12, tm->tm_mon, state->has_month)) + return NULL; + break; + } + case 'c': + __ensure(!"strptime() %c directive unimplemented."); + __builtin_unreachable(); + break; + case 'C': { + int product = 0, n = 0; + sscanf(&input[state->input_index], "%d%n", &product, &n); + if (n == 0 || 2 < n) + return NULL; + state->input_index += n; + state->century = product; + state->has_century = true; + break; + } + case 'd': //`%d` and `%e` are equivalent + case 'e': { + if (!matchNumericRange(1, 31, tm->tm_mday, &state->has_day_of_month)) + return NULL; + break; + } + case 'D': { // equivalent to `%m/%d/%y` + size_t pre_fi = state->format_index; + state->format_index = 0; - char *result = strptime_internal(input, "%m/%d/%y", tm, state); - if(result == NULL) - return NULL; + char *result = strptime_internal(input, "%m/%d/%y", tm, state); + if (result == NULL) + return NULL; - state->format_index = pre_fi; - break; - } - case 'H': { - if(!matchNumericRange(0, 23, tm->tm_hour, nullptr)) - return NULL; - break; - } - case 'I': { - if(!matchNumericRange(1, 12, tm->tm_hour, nullptr)) - return NULL; - break; - } - case 'j': { - if(!matchNumericRange(1, 366, tm->tm_yday, &state->has_day_of_year)) - return NULL; - tm->tm_yday--; - break; - } - case 'm': { - if(!matchNumericRange(1, 12, tm->tm_mon, &state->has_month)) - return NULL; - tm->tm_mon--; - break; - } - case 'M': { - if(!matchNumericRange(0, 59, tm->tm_min, nullptr)) - return NULL; - break; - } - case 'n': - case 't': { - size_t n = 0; - while(isspace(input[state->input_index++])) - n++; - if(n == 0) - return NULL; - state->input_index--; + state->format_index = pre_fi; + break; + } + case 'H': { + if (!matchNumericRange(0, 23, tm->tm_hour, nullptr)) + return NULL; + break; + } + case 'I': { + if (!matchNumericRange(1, 12, tm->tm_hour, nullptr)) + return NULL; + break; + } + case 'j': { + if (!matchNumericRange(1, 366, tm->tm_yday, &state->has_day_of_year)) + return NULL; + tm->tm_yday--; + break; + } + case 'm': { + if (!matchNumericRange(1, 12, tm->tm_mon, &state->has_month)) + return NULL; + tm->tm_mon--; + break; + } + case 'M': { + if (!matchNumericRange(0, 59, tm->tm_min, nullptr)) + return NULL; + break; + } + case 'n': + case 't': { + size_t n = 0; + while (isspace(input[state->input_index++])) + n++; + if (n == 0) + return NULL; + state->input_index--; + break; + } + case 'p': { + const char *meridian_str = nl_langinfo(AM_STR); + size_t len = strlen(meridian_str); + if (!mlibc::strncasecmp(&input[state->input_index], meridian_str, len)) { + tm->tm_hour %= 12; + state->input_index += len; break; } - case 'p': { - const char *meridian_str = nl_langinfo(AM_STR); - size_t len = strlen(meridian_str); - if (!mlibc::strncasecmp(&input[state->input_index], meridian_str, len)) { - tm->tm_hour %= 12; - state->input_index += len; - break; - } - meridian_str = nl_langinfo(PM_STR); - len = strlen(meridian_str); - if (!mlibc::strncasecmp(&input[state->input_index], meridian_str, len)) { - tm->tm_hour %= 12; - tm->tm_hour += 12; - state->input_index += len; - break; - } + meridian_str = nl_langinfo(PM_STR); + len = strlen(meridian_str); + if (!mlibc::strncasecmp(&input[state->input_index], meridian_str, len)) { + tm->tm_hour %= 12; + tm->tm_hour += 12; + state->input_index += len; break; } - case 'r': { //equivalent to `%I:%M:%S %p` - size_t pre_fi = state->format_index; - state->format_index = 0; + break; + } + case 'r': { // equivalent to `%I:%M:%S %p` + size_t pre_fi = state->format_index; + state->format_index = 0; - char *result = strptime_internal(input, "%I:%M:%S %p", tm, state); - if(result == NULL) - return NULL; + char *result = strptime_internal(input, "%I:%M:%S %p", tm, state); + if (result == NULL) + return NULL; - state->format_index = pre_fi; - break; - } - case 'R': { //equivalent to `%H:%M` - size_t pre_fi = state->format_index; - state->format_index = 0; + state->format_index = pre_fi; + break; + } + case 'R': { // equivalent to `%H:%M` + size_t pre_fi = state->format_index; + state->format_index = 0; - char *result = strptime_internal(input, "%H:%M", tm, state); - if(result == NULL) - return NULL; + char *result = strptime_internal(input, "%H:%M", tm, state); + if (result == NULL) + return NULL; - state->format_index = pre_fi; - break; - } - case 'S': { - if(!matchNumericRange(0, 60, tm->tm_sec, nullptr)) - return NULL; - break; - } - case 'T': { //equivalent to `%H:%M:%S` - size_t pre_fi = state->format_index; - state->format_index = 0; + state->format_index = pre_fi; + break; + } + case 'S': { + if (!matchNumericRange(0, 60, tm->tm_sec, nullptr)) + return NULL; + break; + } + case 'T': { // equivalent to `%H:%M:%S` + size_t pre_fi = state->format_index; + state->format_index = 0; - char *result = strptime_internal(input, "%H:%M:%S", tm, state); - if(result == NULL) - return NULL; + char *result = strptime_internal(input, "%H:%M:%S", tm, state); + if (result == NULL) + return NULL; - state->format_index = pre_fi; - break; - } - case 'U': - __ensure(!"strptime() %U directive unimplemented."); - __builtin_unreachable(); - break; - case 'w': { - int product = 0, n = 0; - sscanf(&input[state->input_index], "%d%n", &product, &n); - if(n == 0 || 1 < n) - return NULL; - state->input_index += n; - tm->tm_wday = product; - state->has_day_of_week = true; - break; - } - case 'W': - __ensure(!"strptime() %W directive unimplemented."); - __builtin_unreachable(); - break; - case 'x': - __ensure(!"strptime() %x directive unimplemented."); - __builtin_unreachable(); - break; - case 'X': - __ensure(!"strptime() %X directive unimplemented."); - __builtin_unreachable(); - break; - case 'y': { - int product = 0, n = 0; - sscanf(&input[state->input_index], "%d%n", &product, &n); - if(n == 0 || 2 < n) - return NULL; - if(product < 69) - product += 100; - state->input_index += n; - tm->tm_year = product; - state->has_year = true; - break; - } - case 'Y': { - int product = 0, n = 0; - sscanf(&input[state->input_index], "%d%n", &product, &n); - if(n == 0 || 4 < n) - return NULL; - state->input_index += n; - tm->tm_year = product - 1900; - state->has_year = true; - state->has_century = true; - state->full_year_given = true; - state->century = product / 100; - break; - } - case 'F': { //GNU extensions - //equivalent to `%Y-%m-%d` - size_t pre_fi = state->format_index; - state->format_index = 0; + state->format_index = pre_fi; + break; + } + case 'U': + __ensure(!"strptime() %U directive unimplemented."); + __builtin_unreachable(); + break; + case 'w': { + int product = 0, n = 0; + sscanf(&input[state->input_index], "%d%n", &product, &n); + if (n == 0 || 1 < n) + return NULL; + state->input_index += n; + tm->tm_wday = product; + state->has_day_of_week = true; + break; + } + case 'W': + __ensure(!"strptime() %W directive unimplemented."); + __builtin_unreachable(); + break; + case 'x': + __ensure(!"strptime() %x directive unimplemented."); + __builtin_unreachable(); + break; + case 'X': + __ensure(!"strptime() %X directive unimplemented."); + __builtin_unreachable(); + break; + case 'y': { + int product = 0, n = 0; + sscanf(&input[state->input_index], "%d%n", &product, &n); + if (n == 0 || 2 < n) + return NULL; + if (product < 69) + product += 100; + state->input_index += n; + tm->tm_year = product; + state->has_year = true; + break; + } + case 'Y': { + int product = 0, n = 0; + sscanf(&input[state->input_index], "%d%n", &product, &n); + if (n == 0 || 4 < n) + return NULL; + state->input_index += n; + tm->tm_year = product - 1900; + state->has_year = true; + state->has_century = true; + state->full_year_given = true; + state->century = product / 100; + break; + } + case 'F': { // GNU extensions + // equivalent to `%Y-%m-%d` + size_t pre_fi = state->format_index; + state->format_index = 0; - char *result = strptime_internal(input, "%Y-%m-%d", tm, state); - if(result == NULL) - return NULL; + char *result = strptime_internal(input, "%Y-%m-%d", tm, state); + if (result == NULL) + return NULL; - state->format_index = pre_fi; - break; - } - case 'g': - __ensure(!"strptime() %g directive unimplemented."); - __builtin_unreachable(); - break; - case 'G': - __ensure(!"strptime() %G directive unimplemented."); - __builtin_unreachable(); - break; - case 'u': { - if(!matchNumericRange(1, 7, tm->tm_wday, nullptr)) - return NULL; - tm->tm_wday--; - break; - } - case 'V': - __ensure(!"strptime() %V directive unimplemented."); - __builtin_unreachable(); - break; - case 'z': - __ensure(!"strptime() %z directive unimplemented."); - __builtin_unreachable(); - break; - case 'Z': - __ensure(!"strptime() %Z directive unimplemented."); - __builtin_unreachable(); - break; - case 's': //end of GNU extensions - __ensure(!"strptime() %s directive unimplemented."); - __builtin_unreachable(); - break; - case 'E': { //locale-dependent date & time representation - __ensure(!"strptime() %E* directives unimplemented."); - __builtin_unreachable(); - /* - state->format_index++; - switch(format[state->format_index]){ - case 'c': - break; - case 'C': - break; - case 'x': - break; - case 'X': - break; - case 'y': - break; - case 'Y': - break; - default: - return NULL; - } - */ + state->format_index = pre_fi; + break; + } + case 'g': + __ensure(!"strptime() %g directive unimplemented."); + __builtin_unreachable(); + break; + case 'G': + __ensure(!"strptime() %G directive unimplemented."); + __builtin_unreachable(); + break; + case 'u': { + if (!matchNumericRange(1, 7, tm->tm_wday, nullptr)) + return NULL; + tm->tm_wday--; + break; + } + case 'V': + __ensure(!"strptime() %V directive unimplemented."); + __builtin_unreachable(); + break; + case 'z': + __ensure(!"strptime() %z directive unimplemented."); + __builtin_unreachable(); + break; + case 'Z': + __ensure(!"strptime() %Z directive unimplemented."); + __builtin_unreachable(); + break; + case 's': // end of GNU extensions + __ensure(!"strptime() %s directive unimplemented."); + __builtin_unreachable(); + break; + case 'E': { // locale-dependent date & time representation + __ensure(!"strptime() %E* directives unimplemented."); + __builtin_unreachable(); + /* + state->format_index++; + switch(format[state->format_index]){ + case 'c': + break; + case 'C': + break; + case 'x': + break; + case 'X': + break; + case 'y': + break; + case 'Y': + break; + default: + return NULL; } - case 'O': { //locale-dependent numeric symbols - __ensure(!"strptime() %O* directives unimplemented."); - __builtin_unreachable(); - /* - state->format_index++; - switch(format[state->format_index]){ - case 'd': - case 'e': - break; - case 'H': - break; - case 'I': - break; - case 'm': - break; - case 'M': - break; - case 'S': - break; - case 'U': - break; - case 'w': - break; - case 'W': - break; - case 'y': - break; - default: - return NULL; - } - */ + */ + } + case 'O': { // locale-dependent numeric symbols + __ensure(!"strptime() %O* directives unimplemented."); + __builtin_unreachable(); + /* + state->format_index++; + switch(format[state->format_index]){ + case 'd': + case 'e': + break; + case 'H': + break; + case 'I': + break; + case 'm': + break; + case 'M': + break; + case 'S': + break; + case 'U': + break; + case 'w': + break; + case 'W': + break; + case 'y': + break; + default: + return NULL; } - default: - return NULL; + */ + } + default: + return NULL; } state->format_index++; } - return (char*)input + state->input_index; + return (char *)input + state->input_index; } -} //anonymous namespace +} // anonymous namespace -char *strptime(const char *__restrict s, const char *__restrict format, struct tm *__restrict tm){ +char *strptime(const char *__restrict s, const char *__restrict format, struct tm *__restrict tm) { struct strptime_internal_state state = {}; char *result = strptime_internal(s, format, tm, &state); - if(result == NULL) + if (result == NULL) return NULL; - if(state.has_century && !state.full_year_given){ + if (state.has_century && !state.full_year_given) { int full_year = state.century * 100; - if(state.has_year){ - //Compensate for default century-adjustment of `%j` operand - if(tm->tm_year >= 100) + if (state.has_year) { + // Compensate for default century-adjustment of `%j` operand + if (tm->tm_year >= 100) full_year += tm->tm_year - 100; else full_year += tm->tm_year; @@ -480,9 +507,9 @@ char *strptime(const char *__restrict s, const char *__restrict format, struct t state.has_year = true; } - if(state.has_month && !state.has_day_of_year){ + if (state.has_month && !state.has_day_of_year) { int day = 0; - if(state.has_year) + if (state.has_year) day = month_and_year_to_day_in_year(tm->tm_mon, tm->tm_year); else day = month_to_day(tm->tm_mon); @@ -491,11 +518,10 @@ char *strptime(const char *__restrict s, const char *__restrict format, struct t state.has_day_of_year = true; } - if(state.has_year && !state.has_day_of_week){ - if(!state.has_month && !state.has_day_of_month){ + if (state.has_year && !state.has_day_of_week) { + if (!state.has_month && !state.has_day_of_month) { tm->tm_wday = day_determination(0, 0, tm->tm_year + 1900); - } - else if(state.has_month && state.has_day_of_month){ + } else if (state.has_month && state.has_day_of_month) { tm->tm_wday = day_determination(tm->tm_mday, tm->tm_mon, tm->tm_year + 1900); } state.has_day_of_week = true; diff --git a/options/posix/generic/ucontext.cpp b/options/posix/generic/ucontext.cpp index 9413a786b9..7db5888cac 100644 --- a/options/posix/generic/ucontext.cpp +++ b/options/posix/generic/ucontext.cpp @@ -1,5 +1,5 @@ -#include #include +#include int getcontext(ucontext_t *) { __ensure(!"Not implemented!"); diff --git a/options/posix/generic/unistd.cpp b/options/posix/generic/unistd.cpp index 9801d18fab..e094e53f8b 100644 --- a/options/posix/generic/unistd.cpp +++ b/options/posix/generic/unistd.cpp @@ -1,21 +1,21 @@ -#include #include +#include +#include #include +#include #include #include +#include #include -#include -#include #include -#include -#include +#include #include #include #include +#include #include #include -#include #include namespace { @@ -28,12 +28,12 @@ unsigned int alarm(unsigned int seconds) { struct itimerval it = {}, old = {}; it.it_value.tv_sec = seconds; setitimer(ITIMER_REAL, &it, &old); - return old.it_value.tv_sec + !! old.it_value.tv_usec; + return old.it_value.tv_sec + !!old.it_value.tv_usec; } int chdir(const char *path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_chdir, -1); - if(int e = mlibc::sys_chdir(path); e) { + if (int e = mlibc::sys_chdir(path); e) { errno = e; return -1; } @@ -42,7 +42,7 @@ int chdir(const char *path) { int fchdir(int fd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchdir, -1); - if(int e = mlibc::sys_fchdir(fd); e) { + if (int e = mlibc::sys_fchdir(fd); e) { errno = e; return -1; } @@ -51,7 +51,7 @@ int fchdir(int fd) { int chown(const char *path, uid_t uid, gid_t gid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchownat, -1); - if(int e = mlibc::sys_fchownat(AT_FDCWD, path, uid, gid, 0); e) { + if (int e = mlibc::sys_fchownat(AT_FDCWD, path, uid, gid, 0); e) { errno = e; return -1; } @@ -62,24 +62,22 @@ ssize_t confstr(int name, char *buf, size_t len) { const char *str = ""; if (name == _CS_PATH) { str = "/bin:/usr/bin"; - } else if(name == _CS_GNU_LIBPTHREAD_VERSION) { + } else if (name == _CS_GNU_LIBPTHREAD_VERSION) { // We are not glibc, so we can return 0 here. return 0; - } else if(name == _CS_GNU_LIBC_VERSION) { + } else if (name == _CS_GNU_LIBC_VERSION) { // We are not glibc, so we can return 0 here. return 0; } else { - mlibc::infoLogger() << "\e[31mmlibc: confstr() request " << name << " is unimplemented\e[39m" - << frg::endlog; + mlibc::infoLogger() << "\e[31mmlibc: confstr() request " << name + << " is unimplemented\e[39m" << frg::endlog; __ensure(!"Not implemented"); } return snprintf(buf, len, "%s", str) + 1; } -void _exit(int status) { - mlibc::sys_exit(status); -} +void _exit(int status) { mlibc::sys_exit(status); } int execl(const char *path, const char *arg0, ...) { // TODO: It's a stupid idea to limit the number of arguments here. @@ -89,11 +87,11 @@ int execl(const char *path, const char *arg0, ...) { va_list args; int n = 1; va_start(args, arg0); - while(true) { + while (true) { __ensure(n < 15); auto argn = va_arg(args, const char *); argv[n++] = const_cast(argn); - if(!argn) + if (!argn) break; } va_end(args); @@ -107,7 +105,8 @@ int execle(const char *path, const char *arg0, ...) { int argc; va_list ap; va_start(ap, arg0); - for(argc = 1; va_arg(ap, const char *); argc++); + for (argc = 1; va_arg(ap, const char *); argc++) + ; va_end(ap); int i; @@ -115,7 +114,7 @@ int execle(const char *path, const char *arg0, ...) { char **envp; va_start(ap, arg0); argv[0] = (char *)arg0; - for(i = 1; i <= argc; i++) + for (i = 1; i <= argc; i++) argv[i] = va_arg(ap, char *); envp = va_arg(ap, char **); va_end(ap); @@ -127,14 +126,15 @@ int execlp(const char *file, const char *argv0, ...) { int argc; va_list ap; va_start(ap, argv0); - for(argc = 1; va_arg(ap, const char *); argc++); + for (argc = 1; va_arg(ap, const char *); argc++) + ; va_end(ap); { int i; char *argv[argc + 1]; va_start(ap, argv0); argv[0] = (char *)argv0; - for(i = 1; i < argc; i++) + for (i = 1; i < argc; i++) argv[i] = va_arg(ap, char *); argv[i] = NULL; va_end(ap); @@ -142,27 +142,21 @@ int execlp(const char *file, const char *argv0, ...) { } } -int execv(const char *path, char *const argv[]) { - return execve(path, argv, environ); -} +int execv(const char *path, char *const argv[]) { return execve(path, argv, environ); } -int execvp(const char *file, char *const argv[]) { - return execvpe(file, argv, environ); -} +int execvp(const char *file, char *const argv[]) { return execvpe(file, argv, environ); } int execvpe(const char *file, char *const argv[], char *const envp[]) { - char *null_list[] = { - nullptr - }; + char *null_list[] = {nullptr}; - if(!argv) + if (!argv) argv = null_list; - if(!envp) + if (!envp) envp = null_list; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_execve, -1); - if(strchr(file, '/')) { + if (strchr(file, '/')) { int e = mlibc::sys_execve(file, argv, envp); __ensure(e && "sys_execve() is supposed to never return with success"); errno = e; @@ -170,19 +164,19 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) { } frg::string_view dirs; - if(const char *pv = getenv("PATH"); pv) { + if (const char *pv = getenv("PATH"); pv) { dirs = pv; - }else{ + } else { dirs = "/bin:/usr/bin"; } size_t p = 0; int res = ENOENT; - while(p < dirs.size()) { + while (p < dirs.size()) { size_t s; // Offset of next colon or end of string. - if(size_t cs = dirs.find_first(':', p); cs != size_t(-1)) { + if (size_t cs = dirs.find_first(':', p); cs != size_t(-1)) { s = cs; - }else{ + } else { s = dirs.size(); } @@ -191,12 +185,12 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) { path += "/"; path += file; - if(logExecvpeTries) + if (logExecvpeTries) mlibc::infoLogger() << "mlibc: execvpe() tries '" << path.data() << "'" << frg::endlog; int e = mlibc::sys_execve(path.data(), argv, envp); __ensure(e && "sys_execve() is supposed to never return with success"); - switch(e) { + switch (e) { case ENOENT: case ENOTDIR: break; @@ -217,7 +211,7 @@ int execvpe(const char *file, char *const argv[], char *const envp[]) { int faccessat(int dirfd, const char *pathname, int mode, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_faccessat, -1); - if(int e = mlibc::sys_faccessat(dirfd, pathname, mode, flags); e) { + if (int e = mlibc::sys_faccessat(dirfd, pathname, mode, flags); e) { errno = e; return -1; } @@ -226,7 +220,7 @@ int faccessat(int dirfd, const char *pathname, int mode, int flags) { int fchown(int fd, uid_t uid, gid_t gid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchownat, -1); - if(int e = mlibc::sys_fchownat(fd, "", uid, gid, AT_EMPTY_PATH); e) { + if (int e = mlibc::sys_fchownat(fd, "", uid, gid, AT_EMPTY_PATH); e) { errno = e; return -1; } @@ -235,7 +229,7 @@ int fchown(int fd, uid_t uid, gid_t gid) { int fchownat(int fd, const char *path, uid_t uid, gid_t gid, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchownat, -1); - if(int e = mlibc::sys_fchownat(fd, path, uid, gid, flags); e) { + if (int e = mlibc::sys_fchownat(fd, path, uid, gid, flags); e) { errno = e; return -1; } @@ -244,14 +238,14 @@ int fchownat(int fd, const char *path, uid_t uid, gid_t gid, int flags) { int fdatasync(int fd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fdatasync, -1); - if(int e = mlibc::sys_fdatasync(fd); e) { + if (int e = mlibc::sys_fdatasync(fd); e) { errno = e; return -1; } return 0; } -int fexecve(int, char *const [], char *const []) { +int fexecve(int, char *const[], char *const[]) { __ensure(!"Not implemented"); __builtin_unreachable(); } @@ -263,7 +257,7 @@ long fpathconf(int, int) { int fsync(int fd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fsync, -1); - if(auto e = mlibc::sys_fsync(fd); e) { + if (auto e = mlibc::sys_fsync(fd); e) { errno = e; return -1; } @@ -272,7 +266,7 @@ int fsync(int fd) { int ftruncate(int fd, off_t size) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ftruncate, -1); - if(int e = mlibc::sys_ftruncate(fd, size); e) { + if (int e = mlibc::sys_ftruncate(fd, size); e) { errno = e; return -1; } @@ -295,7 +289,7 @@ char *getcwd(char *buffer, size_t size) { } MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getcwd, nullptr); - if(int e = mlibc::sys_getcwd(buffer, size); e) { + if (int e = mlibc::sys_getcwd(buffer, size); e) { errno = e; return NULL; } @@ -306,7 +300,7 @@ char *getcwd(char *buffer, size_t size) { int getgroups(int size, gid_t list[]) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getgroups, -1); int ret; - if(int e = mlibc::sys_getgroups(size, list, &ret); e) { + if (int e = mlibc::sys_getgroups(size, list, &ret); e) { errno = e; return -1; } @@ -320,7 +314,7 @@ long gethostid(void) { int gethostname(char *buffer, size_t bufsize) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_gethostname, -1); - if(auto e = mlibc::sys_gethostname(buffer, bufsize); e) { + if (auto e = mlibc::sys_gethostname(buffer, bufsize); e) { errno = e; return -1; } @@ -329,7 +323,7 @@ int gethostname(char *buffer, size_t bufsize) { int sethostname(const char *buffer, size_t bufsize) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_sethostname, -1); - if(auto e = mlibc::sys_sethostname(buffer, bufsize); e) { + if (auto e = mlibc::sys_sethostname(buffer, bufsize); e) { errno = e; return -1; } @@ -337,9 +331,7 @@ int sethostname(const char *buffer, size_t bufsize) { } // Code taken from musl -char *getlogin(void) { - return getenv("LOGNAME"); -} +char *getlogin(void) { return getenv("LOGNAME"); } int getlogin_r(char *, size_t) { __ensure(!"Not implemented"); @@ -367,7 +359,7 @@ int getopt(int argc, char *const argv[], const char *optstring) { return EOF; } - scan = argv[optind]+1; + scan = argv[optind] + 1; optind++; } @@ -384,7 +376,7 @@ int getopt(int argc, char *const argv[], const char *optstring) { if (*scan != '\0') { optarg = scan; scan = NULL; - } else if( optind < argc ) { + } else if (optind < argc) { optarg = argv[optind]; optind++; } else { @@ -400,24 +392,22 @@ pid_t getpgid(pid_t pid) { pid_t pgid; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getpgid, -1); - if(int e = mlibc::sys_getpgid(pid, &pgid); e) { + if (int e = mlibc::sys_getpgid(pid, &pgid); e) { errno = e; return -1; } return pgid; } -pid_t getpgrp(void) { - return getpgid(0); -} +pid_t getpgrp(void) { return getpgid(0); } pid_t getsid(pid_t pid) { - if(!mlibc::sys_getsid) { + if (!mlibc::sys_getsid) { MLIBC_MISSING_SYSDEP(); return -1; } pid_t sid; - if(int e = mlibc::sys_getsid(pid, &sid); e) { + if (int e = mlibc::sys_getsid(pid, &sid); e) { errno = e; return -1; } @@ -426,7 +416,7 @@ pid_t getsid(pid_t pid) { int lchown(const char *path, uid_t uid, gid_t gid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_fchownat, -1); - if(int e = mlibc::sys_fchownat(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW); e) { + if (int e = mlibc::sys_fchownat(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW); e) { errno = e; return -1; } @@ -435,7 +425,7 @@ int lchown(const char *path, uid_t uid, gid_t gid) { int link(const char *old_path, const char *new_path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_link, -1); - if(int e = mlibc::sys_link(old_path, new_path); e) { + if (int e = mlibc::sys_link(old_path, new_path); e) { errno = e; return -1; } @@ -444,7 +434,7 @@ int link(const char *old_path, const char *new_path) { int linkat(int olddirfd, const char *old_path, int newdirfd, const char *new_path, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_linkat, -1); - if(int e = mlibc::sys_linkat(olddirfd, old_path, newdirfd, new_path, flags); e) { + if (int e = mlibc::sys_linkat(olddirfd, old_path, newdirfd, new_path, flags); e) { errno = e; return -1; } @@ -454,29 +444,29 @@ int linkat(int olddirfd, const char *old_path, int newdirfd, const char *new_pat // Code take from musl int lockf(int fd, int op, off_t size) { struct flock l = { - .l_type = F_WRLCK, - .l_whence = SEEK_CUR, - .l_start = 0, - .l_len = size, - .l_pid = 0, + .l_type = F_WRLCK, + .l_whence = SEEK_CUR, + .l_start = 0, + .l_len = size, + .l_pid = 0, }; - switch(op) { - case F_TEST: - l.l_type = F_RDLCK; - if(fcntl(fd, F_GETLK, &l) < 0) - return -1; - if(l.l_type == F_UNLCK || l.l_pid == getpid()) - return 0; - errno = EACCES; + switch (op) { + case F_TEST: + l.l_type = F_RDLCK; + if (fcntl(fd, F_GETLK, &l) < 0) return -1; - case F_ULOCK: - l.l_type = F_UNLCK; - [[fallthrough]]; - case F_TLOCK: - return fcntl(fd, F_SETLK, &l); - case F_LOCK: - return fcntl(fd, F_SETLKW, &l); + if (l.l_type == F_UNLCK || l.l_pid == getpid()) + return 0; + errno = EACCES; + return -1; + case F_ULOCK: + l.l_type = F_UNLCK; + [[fallthrough]]; + case F_TLOCK: + return fcntl(fd, F_SETLK, &l); + case F_LOCK: + return fcntl(fd, F_SETLKW, &l); } errno = EINVAL; @@ -501,7 +491,7 @@ long pathconf(const char *, int name) { int pause(void) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pause, -1); - if(int e = mlibc::sys_pause(); e) { + if (int e = mlibc::sys_pause(); e) { errno = e; return -1; } @@ -511,7 +501,7 @@ int pause(void) { int pipe(int *fds) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pipe, -1); - if(int e = mlibc::sys_pipe(fds, 0); e) { + if (int e = mlibc::sys_pipe(fds, 0); e) { errno = e; return -1; } @@ -520,7 +510,7 @@ int pipe(int *fds) { int pipe2(int *fds, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pipe, -1); - if(int e = mlibc::sys_pipe(fds, flags); e) { + if (int e = mlibc::sys_pipe(fds, flags); e) { errno = e; return -1; } @@ -531,7 +521,7 @@ ssize_t pread(int fd, void *buf, size_t n, off_t off) { ssize_t num_read; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pread, -1); - if(int e = mlibc::sys_pread(fd, buf, n, off, &num_read); e) { + if (int e = mlibc::sys_pread(fd, buf, n, off, &num_read); e) { errno = e; return -1; } @@ -544,7 +534,7 @@ ssize_t pwrite(int fd, const void *buf, size_t n, off_t off) { ssize_t num_written; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_pwrite, -1); - if(int e = mlibc::sys_pwrite(fd, buf, n, off, &num_written); e) { + if (int e = mlibc::sys_pwrite(fd, buf, n, off, &num_written); e) { errno = e; return -1; } @@ -556,17 +546,18 @@ ssize_t pwrite(int fd, const void *buf, size_t n, off_t off) { ssize_t readlink(const char *__restrict path, char *__restrict buffer, size_t max_size) { ssize_t length; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_readlink, -1); - if(int e = mlibc::sys_readlink(path, buffer, max_size, &length); e) { + if (int e = mlibc::sys_readlink(path, buffer, max_size, &length); e) { errno = e; return -1; } return length; } -ssize_t readlinkat(int dirfd, const char *__restrict path, char *__restrict buffer, size_t max_size) { +ssize_t +readlinkat(int dirfd, const char *__restrict path, char *__restrict buffer, size_t max_size) { ssize_t length; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_readlinkat, -1); - if(int e = mlibc::sys_readlinkat(dirfd, path, buffer, max_size, &length); e) { + if (int e = mlibc::sys_readlinkat(dirfd, path, buffer, max_size, &length); e) { errno = e; return -1; } @@ -575,7 +566,7 @@ ssize_t readlinkat(int dirfd, const char *__restrict path, char *__restrict buff int rmdir(const char *path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_rmdir, -1); - if(int e = mlibc::sys_rmdir(path); e) { + if (int e = mlibc::sys_rmdir(path); e) { errno = e; return -1; } @@ -584,7 +575,7 @@ int rmdir(const char *path) { int setegid(gid_t egid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setegid, 0); - if(int e = mlibc::sys_setegid(egid); e) { + if (int e = mlibc::sys_setegid(egid); e) { errno = e; return -1; } @@ -593,7 +584,7 @@ int setegid(gid_t egid) { int seteuid(uid_t euid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_seteuid, 0); - if(int e = mlibc::sys_seteuid(euid); e) { + if (int e = mlibc::sys_seteuid(euid); e) { errno = e; return -1; } @@ -602,7 +593,7 @@ int seteuid(uid_t euid) { int setgid(gid_t gid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setgid, 0); - if(int e = mlibc::sys_setgid(gid); e) { + if (int e = mlibc::sys_setgid(gid); e) { errno = e; return -1; } @@ -611,20 +602,18 @@ int setgid(gid_t gid) { int setpgid(pid_t pid, pid_t pgid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setpgid, -1); - if(int e = mlibc::sys_setpgid(pid, pgid); e) { + if (int e = mlibc::sys_setpgid(pid, pgid); e) { errno = e; return -1; } return 0; } -pid_t setpgrp(void) { - return setpgid(0, 0); -} +pid_t setpgrp(void) { return setpgid(0, 0); } int setregid(gid_t rgid, gid_t egid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setregid, -1); - if(int e = mlibc::sys_setregid(rgid, egid); e) { + if (int e = mlibc::sys_setregid(rgid, egid); e) { errno = e; return -1; } @@ -633,7 +622,7 @@ int setregid(gid_t rgid, gid_t egid) { int setreuid(uid_t ruid, uid_t euid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setreuid, -1); - if(int e = mlibc::sys_setreuid(ruid, euid); e) { + if (int e = mlibc::sys_setreuid(ruid, euid); e) { errno = e; return -1; } @@ -641,12 +630,12 @@ int setreuid(uid_t ruid, uid_t euid) { } pid_t setsid(void) { - if(!mlibc::sys_setsid) { + if (!mlibc::sys_setsid) { MLIBC_MISSING_SYSDEP(); return -1; } pid_t sid; - if(int e = mlibc::sys_setsid(&sid); e) { + if (int e = mlibc::sys_setsid(&sid); e) { errno = e; return -1; } @@ -654,12 +643,12 @@ pid_t setsid(void) { } int setuid(uid_t uid) { - if(!mlibc::sys_setuid) { + if (!mlibc::sys_setuid) { MLIBC_MISSING_SYSDEP(); mlibc::infoLogger() << "mlibc: missing sysdep sys_setuid(). Returning 0" << frg::endlog; return 0; } - if(int e = mlibc::sys_setuid(uid); e) { + if (int e = mlibc::sys_setuid(uid); e) { errno = e; return -1; } @@ -673,7 +662,7 @@ void swab(const void *__restrict, void *__restrict, ssize_t) { int symlink(const char *target_path, const char *link_path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_symlink, -1); - if(int e = mlibc::sys_symlink(target_path, link_path); e) { + if (int e = mlibc::sys_symlink(target_path, link_path); e) { errno = e; return -1; } @@ -682,7 +671,7 @@ int symlink(const char *target_path, const char *link_path) { int symlinkat(const char *target_path, int dirfd, const char *link_path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_symlinkat, -1); - if(int e = mlibc::sys_symlinkat(target_path, dirfd, link_path); e) { + if (int e = mlibc::sys_symlinkat(target_path, dirfd, link_path); e) { errno = e; return -1; } @@ -690,7 +679,7 @@ int symlinkat(const char *target_path, int dirfd, const char *link_path) { } void sync(void) { - if(!mlibc::sys_sync) { + if (!mlibc::sys_sync) { MLIBC_MISSING_SYSDEP(); } else { mlibc::sys_sync(); @@ -698,102 +687,127 @@ void sync(void) { } long sysconf(int number) { - if(mlibc::sys_sysconf) { + if (mlibc::sys_sysconf) { long ret = 0; int e = mlibc::sys_sysconf(number, &ret); - if(e && e != EINVAL) { + if (e && e != EINVAL) { errno = e; return -1; } - if(e != EINVAL) { + if (e != EINVAL) { return ret; } } /* default return values, if not overriden by sysdep */ - switch(number) { - case _SC_ARG_MAX: - // On linux, it is defined to 2097152 in most cases, so define it to be 2097152 - return 2097152; - case _SC_PAGE_SIZE: - return mlibc::page_size; - case _SC_OPEN_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_OPEN_MAX) returns fallback value 256\e[39m" << frg::endlog; - return 256; - case _SC_PHYS_PAGES: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_PHYS_PAGES) returns fallback value 1024\e[39m" << frg::endlog; - return 1024; - case _SC_NPROCESSORS_ONLN: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_NPROCESSORS_ONLN) returns fallback value 1\e[39m" << frg::endlog; - return 1; - case _SC_GETPW_R_SIZE_MAX: - return NSS_BUFLEN_PASSWD; - case _SC_GETGR_R_SIZE_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_GETGR_R_SIZE_MAX) returns fallback value 1024\e[39m" << frg::endlog; - return 1024; - case _SC_CHILD_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_CHILD_MAX) returns fallback value 25\e[39m" << frg::endlog; - // On linux, it is defined to 25 in most cases, so define it to be 25 - return 25; - case _SC_JOB_CONTROL: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_JOB_CONTROL) returns fallback value 1\e[39m" << frg::endlog; - // If 1, job control is supported - return 1; - case _SC_CLK_TCK: - // TODO: This should be obsolete? - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_CLK_TCK) is obsolete and returns arbitrary value 1000000\e[39m" << frg::endlog; - return 1000000; - case _SC_NGROUPS_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_NGROUPS_MAX) returns fallback value 65536\e[39m" << frg::endlog; - // On linux, it is defined to 65536 in most cases, so define it to be 65536 - return 65536; - case _SC_RE_DUP_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_RE_DUP_MAX) returns fallback value RE_DUP_MAX\e[39m" << frg::endlog; - return RE_DUP_MAX; - case _SC_LINE_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_LINE_MAX) returns fallback value 2048\e[39m" << frg::endlog; - // Linux defines it as 2048. - return 2048; - case _SC_XOPEN_CRYPT: - return -1; - case _SC_NPROCESSORS_CONF: - // TODO: actually return a proper value for _SC_NPROCESSORS_CONF - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_NPROCESSORS_CONF) unconditionally returns fallback value 1\e[39m" << frg::endlog; - return 1; - case _SC_HOST_NAME_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_HOST_NAME_MAX) unconditionally returns fallback value 256\e[39m" << frg::endlog; - return 256; - case _SC_LOGIN_NAME_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_LOGIN_NAME_MAX) unconditionally returns fallback value 256\e[39m" << frg::endlog; - return 256; - case _SC_FSYNC: - return _POSIX_FSYNC; - case _SC_SAVED_IDS: - return _POSIX_SAVED_IDS; - case _SC_SYMLOOP_MAX: - mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_SYMLOOP_MAX) unconditionally returns fallback value 8\e[39m" << frg::endlog; - return 8; - default: - mlibc::infoLogger() << "\e[31mmlibc: sysconf() call is not implemented, number: " << number << "\e[39m" << frg::endlog; - errno = EINVAL; - return -1; + switch (number) { + case _SC_ARG_MAX: + // On linux, it is defined to 2097152 in most cases, so define it to be 2097152 + return 2097152; + case _SC_PAGE_SIZE: + return mlibc::page_size; + case _SC_OPEN_MAX: + mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_OPEN_MAX) returns fallback value 256\e[39m" + << frg::endlog; + return 256; + case _SC_PHYS_PAGES: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_PHYS_PAGES) returns fallback value 1024\e[39m" + << frg::endlog; + return 1024; + case _SC_NPROCESSORS_ONLN: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_NPROCESSORS_ONLN) returns fallback value 1\e[39m" + << frg::endlog; + return 1; + case _SC_GETPW_R_SIZE_MAX: + return NSS_BUFLEN_PASSWD; + case _SC_GETGR_R_SIZE_MAX: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_GETGR_R_SIZE_MAX) returns fallback value 1024\e[39m" + << frg::endlog; + return 1024; + case _SC_CHILD_MAX: + mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_CHILD_MAX) returns fallback value 25\e[39m" + << frg::endlog; + // On linux, it is defined to 25 in most cases, so define it to be 25 + return 25; + case _SC_JOB_CONTROL: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_JOB_CONTROL) returns fallback value 1\e[39m" + << frg::endlog; + // If 1, job control is supported + return 1; + case _SC_CLK_TCK: + // TODO: This should be obsolete? + mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_CLK_TCK) is obsolete and returns " + "arbitrary value 1000000\e[39m" + << frg::endlog; + return 1000000; + case _SC_NGROUPS_MAX: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_NGROUPS_MAX) returns fallback value 65536\e[39m" + << frg::endlog; + // On linux, it is defined to 65536 in most cases, so define it to be 65536 + return 65536; + case _SC_RE_DUP_MAX: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_RE_DUP_MAX) returns fallback value RE_DUP_MAX\e[39m" + << frg::endlog; + return RE_DUP_MAX; + case _SC_LINE_MAX: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_LINE_MAX) returns fallback value 2048\e[39m" + << frg::endlog; + // Linux defines it as 2048. + return 2048; + case _SC_XOPEN_CRYPT: + return -1; + case _SC_NPROCESSORS_CONF: + // TODO: actually return a proper value for _SC_NPROCESSORS_CONF + mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_NPROCESSORS_CONF) unconditionally returns " + "fallback value 1\e[39m" + << frg::endlog; + return 1; + case _SC_HOST_NAME_MAX: + mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_HOST_NAME_MAX) unconditionally returns " + "fallback value 256\e[39m" + << frg::endlog; + return 256; + case _SC_LOGIN_NAME_MAX: + mlibc::infoLogger() << "\e[31mmlibc: sysconf(_SC_LOGIN_NAME_MAX) unconditionally returns " + "fallback value 256\e[39m" + << frg::endlog; + return 256; + case _SC_FSYNC: + return _POSIX_FSYNC; + case _SC_SAVED_IDS: + return _POSIX_SAVED_IDS; + case _SC_SYMLOOP_MAX: + mlibc::infoLogger( + ) << "\e[31mmlibc: sysconf(_SC_SYMLOOP_MAX) unconditionally returns fallback value 8\e[39m" + << frg::endlog; + return 8; + default: + mlibc::infoLogger() << "\e[31mmlibc: sysconf() call is not implemented, number: " << number + << "\e[39m" << frg::endlog; + errno = EINVAL; + return -1; } } pid_t tcgetpgrp(int fd) { int pgrp; - if(ioctl(fd, TIOCGPGRP, &pgrp) < 0) { + if (ioctl(fd, TIOCGPGRP, &pgrp) < 0) { return -1; } return pgrp; } -int tcsetpgrp(int fd, pid_t pgrp) { - return ioctl(fd, TIOCSPGRP, &pgrp); -} +int tcsetpgrp(int fd, pid_t pgrp) { return ioctl(fd, TIOCSPGRP, &pgrp); } int truncate(const char *, off_t) { __ensure(!"Not implemented"); @@ -806,7 +820,7 @@ char *ttyname(int fd) { const size_t size = 128; static thread_local char buf[size]; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ttyname, nullptr); - if(int e = mlibc::sys_ttyname(fd, buf, size); e) { + if (int e = mlibc::sys_ttyname(fd, buf, size); e) { errno = e; return nullptr; } @@ -815,7 +829,7 @@ char *ttyname(int fd) { int ttyname_r(int fd, char *buf, size_t size) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_ttyname, -1); - if(int e = mlibc::sys_ttyname(fd, buf, size); e) { + if (int e = mlibc::sys_ttyname(fd, buf, size); e) { return e; } return 0; @@ -823,7 +837,7 @@ int ttyname_r(int fd, char *buf, size_t size) { int unlink(const char *path) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_unlinkat, -1); - if(int e = mlibc::sys_unlinkat(AT_FDCWD, path, 0); e) { + if (int e = mlibc::sys_unlinkat(AT_FDCWD, path, 0); e) { errno = e; return -1; } @@ -832,16 +846,14 @@ int unlink(const char *path) { int unlinkat(int fd, const char *path, int flags) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_unlinkat, -1); - if(int e = mlibc::sys_unlinkat(fd, path, flags); e) { + if (int e = mlibc::sys_unlinkat(fd, path, flags); e) { errno = e; return -1; } return 0; } -int getpagesize() { - return mlibc::page_size; -} +int getpagesize() { return mlibc::page_size; } // Code taken from musl // GLIBC extension for stdin/stdout @@ -851,7 +863,7 @@ char *getpass(const char *prompt) { ssize_t l; static char password[128]; - if((fdin = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0) { + if ((fdin = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC)) < 0) { fdin = STDIN_FILENO; fdout = STDOUT_FILENO; } else { @@ -870,8 +882,8 @@ char *getpass(const char *prompt) { dprintf(fdout, "%s", prompt); l = read(fdin, password, sizeof password); - if(l >= 0) { - if((l > 0 && password[l - 1] == '\n') || l == sizeof password) + if (l >= 0) { + if ((l > 0 && password[l - 1] == '\n') || l == sizeof password) l--; password[l] = 0; } @@ -879,7 +891,7 @@ char *getpass(const char *prompt) { tcsetattr(fdin, TCSAFLUSH, &s); dprintf(fdout, "\n"); - if(fdin != STDIN_FILENO) { + if (fdin != STDIN_FILENO) { close(fdin); } @@ -893,7 +905,7 @@ char *get_current_dir_name(void) { // This is a Linux extension pid_t gettid(void) { - if(!mlibc::sys_gettid) { + if (!mlibc::sys_gettid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_gettid()"); } @@ -902,11 +914,11 @@ pid_t gettid(void) { int getentropy(void *buffer, size_t length) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getentropy, -1); - if(length > 256) { + if (length > 256) { errno = EIO; return -1; } - if(int e = mlibc::sys_getentropy(buffer, length); e) { + if (int e = mlibc::sys_getentropy(buffer, length); e) { errno = e; return -1; } @@ -915,7 +927,7 @@ int getentropy(void *buffer, size_t length) { ssize_t write(int fd, const void *buf, size_t count) { ssize_t bytes_written; - if(int e = mlibc::sys_write(fd, buf, count, &bytes_written); e) { + if (int e = mlibc::sys_write(fd, buf, count, &bytes_written); e) { errno = e; return (ssize_t)-1; } @@ -924,7 +936,7 @@ ssize_t write(int fd, const void *buf, size_t count) { ssize_t read(int fd, void *buf, size_t count) { ssize_t bytes_read; - if(int e = mlibc::sys_read(fd, buf, count, &bytes_read); e) { + if (int e = mlibc::sys_read(fd, buf, count, &bytes_read); e) { errno = e; return (ssize_t)-1; } @@ -933,7 +945,7 @@ ssize_t read(int fd, void *buf, size_t count) { off_t lseek(int fd, off_t offset, int whence) { off_t new_offset; - if(int e = mlibc::sys_seek(fd, offset, whence, &new_offset); e) { + if (int e = mlibc::sys_seek(fd, offset, whence, &new_offset); e) { errno = e; return (off_t)-1; } @@ -942,21 +954,19 @@ off_t lseek(int fd, off_t offset, int whence) { off64_t lseek64(int fd, off64_t offset, int whence) { off64_t new_offset; - if(int e = mlibc::sys_seek(fd, offset, whence, &new_offset); e) { + if (int e = mlibc::sys_seek(fd, offset, whence, &new_offset); e) { errno = e; return (off64_t)-1; } return new_offset; } -int close(int fd) { - return mlibc::sys_close(fd); -} +int close(int fd) { return mlibc::sys_close(fd); } unsigned int sleep(unsigned int secs) { time_t seconds = secs; long nanos = 0; - if(!mlibc::sys_sleep) { + if (!mlibc::sys_sleep) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_sleep()"); } @@ -968,7 +978,7 @@ unsigned int sleep(unsigned int secs) { int usleep(useconds_t usecs) { time_t seconds = 0; long nanos = usecs * 1000; - if(!mlibc::sys_sleep) { + if (!mlibc::sys_sleep) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_sleep()"); } @@ -978,7 +988,7 @@ int usleep(useconds_t usecs) { int dup(int fd) { int newfd; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_dup, -1); - if(int e = mlibc::sys_dup(fd, 0, &newfd); e) { + if (int e = mlibc::sys_dup(fd, 0, &newfd); e) { errno = e; return -1; } @@ -987,7 +997,7 @@ int dup(int fd) { int dup2(int fd, int newfd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_dup2, -1); - if(int e = mlibc::sys_dup2(fd, 0, newfd); e) { + if (int e = mlibc::sys_dup2(fd, 0, newfd); e) { errno = e; return -1; } @@ -1008,7 +1018,7 @@ pid_t fork(void) { hand = hand->prev; } - if(int e = mlibc::sys_fork(&child); e) { + if (int e = mlibc::sys_fork(&child); e) { errno = e; return -1; } @@ -1045,13 +1055,13 @@ pid_t vfork(void) { /* deferring to fork as implementing vfork correctly requires assembly * to handle not mucking up the stack */ - if(!mlibc::sys_fork) { + if (!mlibc::sys_fork) { MLIBC_MISSING_SYSDEP(); errno = ENOSYS; return -1; } - if(int e = mlibc::sys_fork(&child); e) { + if (int e = mlibc::sys_fork(&child); e) { errno = e; return -1; } @@ -1060,13 +1070,11 @@ pid_t vfork(void) { } int execve(const char *path, char *const argv[], char *const envp[]) { - char *null_list[] = { - nullptr - }; + char *null_list[] = {nullptr}; - if(!argv) + if (!argv) argv = null_list; - if(!envp) + if (!envp) envp = null_list; MLIBC_CHECK_OR_ENOSYS(mlibc::sys_execve, -1); @@ -1077,7 +1085,7 @@ int execve(const char *path, char *const argv[], char *const envp[]) { } gid_t getgid(void) { - if(!mlibc::sys_getgid) { + if (!mlibc::sys_getgid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_getgid()"); } @@ -1085,7 +1093,7 @@ gid_t getgid(void) { } gid_t getegid(void) { - if(!mlibc::sys_getegid) { + if (!mlibc::sys_getegid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_getegid()"); } @@ -1093,7 +1101,7 @@ gid_t getegid(void) { } uid_t getuid(void) { - if(!mlibc::sys_getuid) { + if (!mlibc::sys_getuid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_getuid()"); } @@ -1101,7 +1109,7 @@ uid_t getuid(void) { } uid_t geteuid(void) { - if(!mlibc::sys_geteuid) { + if (!mlibc::sys_geteuid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_geteuid()"); } @@ -1109,7 +1117,7 @@ uid_t geteuid(void) { } pid_t getpid(void) { - if(!mlibc::sys_getpid) { + if (!mlibc::sys_getpid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_getpid()"); } @@ -1117,7 +1125,7 @@ pid_t getpid(void) { } pid_t getppid(void) { - if(!mlibc::sys_getppid) { + if (!mlibc::sys_getppid) { MLIBC_MISSING_SYSDEP(); __ensure(!"Cannot continue without sys_getppid()"); } @@ -1126,7 +1134,7 @@ pid_t getppid(void) { int access(const char *path, int mode) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_access, -1); - if(int e = mlibc::sys_access(path, mode); e) { + if (int e = mlibc::sys_access(path, mode); e) { errno = e; return -1; } @@ -1134,63 +1142,61 @@ int access(const char *path, int mode) { } namespace { - FILE *user_shell_global_file; // Used by setusershell/getusershell/endusershell. - - bool user_shell_open_global_file() { - if(!user_shell_global_file) { - user_shell_global_file = fopen("/etc/shells", "r"); - if(!user_shell_global_file) { - // if the file cannot be opened, we need to pretend one exists with - // these shells: - static char shells[] = "/bin/sh\n/bin/csh\n"; - - user_shell_global_file = fmemopen(shells, strlen(shells), "r"); - if(user_shell_global_file == nullptr) - return false; - } +FILE *user_shell_global_file; // Used by setusershell/getusershell/endusershell. + +bool user_shell_open_global_file() { + if (!user_shell_global_file) { + user_shell_global_file = fopen("/etc/shells", "r"); + if (!user_shell_global_file) { + // if the file cannot be opened, we need to pretend one exists with + // these shells: + static char shells[] = "/bin/sh\n/bin/csh\n"; + + user_shell_global_file = fmemopen(shells, strlen(shells), "r"); + if (user_shell_global_file == nullptr) + return false; } - - return true; } - void user_shell_close_global_file() { - if(user_shell_global_file) { - fclose(user_shell_global_file); - user_shell_global_file = nullptr; - } + return true; +} + +void user_shell_close_global_file() { + if (user_shell_global_file) { + fclose(user_shell_global_file); + user_shell_global_file = nullptr; } } +} // namespace char *getusershell(void) { static char shell[PATH_MAX]; - if(!user_shell_open_global_file()) + if (!user_shell_open_global_file()) return nullptr; - if (fgets(shell, PATH_MAX, user_shell_global_file)){ + if (fgets(shell, PATH_MAX, user_shell_global_file)) { shell[strcspn(shell, "\n")] = '\0'; return shell; } - if(ferror(user_shell_global_file)) + if (ferror(user_shell_global_file)) errno = EIO; return nullptr; } void setusershell(void) { - if(!user_shell_open_global_file()) + if (!user_shell_open_global_file()) return; rewind(user_shell_global_file); } -void endusershell(void) { - user_shell_close_global_file(); -} +void endusershell(void) { user_shell_close_global_file(); } int isatty(int fd) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_isatty, 0); - if(int e = mlibc::sys_isatty(fd); e) { + if (int e = mlibc::sys_isatty(fd); e) { errno = e; return 0; } @@ -1199,7 +1205,7 @@ int isatty(int fd) { int chroot(const char *ptr) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_chroot, -1); - if(int e = mlibc::sys_chroot(ptr); e) { + if (int e = mlibc::sys_chroot(ptr); e) { errno = e; return -1; } @@ -1207,42 +1213,43 @@ int chroot(const char *ptr) { } int daemon(int nochdir, int noclose) { - switch(fork()) { - case 0: break; - case -1: return -1; - default: _exit(0); + switch (fork()) { + case 0: + break; + case -1: + return -1; + default: + _exit(0); } - if(setsid() < 0) + if (setsid() < 0) return -1; - if(!nochdir && chdir("/")) + if (!nochdir && chdir("/")) return -1; - if(!noclose) { + if (!noclose) { int fd = open("/dev/null", O_RDWR); - if(fd < 0) + if (fd < 0) return -1; bool failed = false; - if(dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0) + if (dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0) failed = true; - if(fd > 2) + if (fd > 2) close(fd); - if(failed) + if (failed) return -1; } return 0; } -char *ctermid(char *s) { - return s ? strcpy(s, "/dev/tty") : const_cast("/dev/tty"); -} +char *ctermid(char *s) { return s ? strcpy(s, "/dev/tty") : const_cast("/dev/tty"); } int setresuid(uid_t ruid, uid_t euid, uid_t suid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setresuid, -1); - if(int e = mlibc::sys_setresuid(ruid, euid, suid); e) { + if (int e = mlibc::sys_setresuid(ruid, euid, suid); e) { errno = e; return -1; } @@ -1251,7 +1258,7 @@ int setresuid(uid_t ruid, uid_t euid, uid_t suid) { int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_setresgid, -1); - if(int e = mlibc::sys_setresgid(rgid, egid, sgid); e) { + if (int e = mlibc::sys_setresgid(rgid, egid, sgid); e) { errno = e; return -1; } @@ -1270,7 +1277,7 @@ int setdomainname(const char *, size_t) { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getresuid, -1); - if(int e = mlibc::sys_getresuid(ruid, euid, suid); e) { + if (int e = mlibc::sys_getresuid(ruid, euid, suid); e) { errno = e; return -1; } @@ -1279,7 +1286,7 @@ int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid) { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_getresgid, -1); - if(int e = mlibc::sys_getresgid(rgid, egid, sgid); e) { + if (int e = mlibc::sys_getresgid(rgid, egid, sgid); e) { errno = e; return -1; } @@ -1288,14 +1295,14 @@ int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid) { #if __MLIBC_BSD_OPTION void *sbrk(intptr_t increment) { - if(increment) { + if (increment) { errno = ENOMEM; return (void *)-1; } MLIBC_CHECK_OR_ENOSYS(mlibc::sys_brk, (void *)-1); void *out; - if(int e = mlibc::sys_brk(&out); e) { + if (int e = mlibc::sys_brk(&out); e) { errno = e; return (void *)-1; } diff --git a/options/posix/generic/utime.cpp b/options/posix/generic/utime.cpp index f78729fd22..de99511e03 100644 --- a/options/posix/generic/utime.cpp +++ b/options/posix/generic/utime.cpp @@ -1,7 +1,7 @@ -#include -#include #include +#include +#include #include #include @@ -9,7 +9,7 @@ int utime(const char *filename, const struct utimbuf *times) { MLIBC_CHECK_OR_ENOSYS(mlibc::sys_utimensat, -1); struct timespec time[2]; - if(times) { + if (times) { time[0].tv_sec = times->actime; time[0].tv_nsec = 0; time[1].tv_sec = times->modtime; @@ -28,4 +28,3 @@ int utime(const char *filename, const struct utimbuf *times) { return 0; } - diff --git a/options/posix/generic/wordexp.cpp b/options/posix/generic/wordexp.cpp index 8443527253..4825ae90be 100644 --- a/options/posix/generic/wordexp.cpp +++ b/options/posix/generic/wordexp.cpp @@ -28,15 +28,15 @@ * SUCH DAMAGE. */ -#include -#include -#include -#include #include -#include -#include +#include #include #include +#include +#include +#include +#include +#include #define SHELL_PATH "/bin/sh" #define SHELL_NAME "sh" @@ -46,9 +46,9 @@ static size_t we_read_fully(int fd, char *buffer, size_t len) { do { ssize_t nread = read(fd, buffer + done, len - done); - if(nread == -1 && errno == EINTR) + if (nread == -1 && errno == EINTR) continue; - if(nread <= 0) + if (nread <= 0) break; done += nread; } while (done != len); @@ -57,56 +57,63 @@ static size_t we_read_fully(int fd, char *buffer, size_t len) { } static int we_askshell(const char *words, wordexp_t *we, int flags) { - int pdes[2]; /* pipe to child */ - char bbuf[9]; /* buffer for byte count */ - char wbuf[9]; /* buffer for word count */ + int pdes[2]; /* pipe to child */ + char bbuf[9]; /* buffer for byte count */ + char wbuf[9]; /* buffer for word count */ size_t nwords = 0; /* number of words from child */ size_t nbytes = 0; /* number of bytes from child */ - size_t sofs = 0; /* offset into we->we_strings */ - size_t vofs = 0; /* offset into we->we_wordv */ - pid_t pid; /* PID of child */ - pid_t wpid; /* waitpid return value */ - int status; /* child exit status */ - int error; /* our return value */ - int serrno; /* errno to return */ - char *np, *p; /* handy pointers */ - char *nstrings; /* temporary for realloc() */ - char **new_wordv; /* temporary for realloc() */ + size_t sofs = 0; /* offset into we->we_strings */ + size_t vofs = 0; /* offset into we->we_wordv */ + pid_t pid; /* PID of child */ + pid_t wpid; /* waitpid return value */ + int status; /* child exit status */ + int error; /* our return value */ + int serrno; /* errno to return */ + char *np, *p; /* handy pointers */ + char *nstrings; /* temporary for realloc() */ + char **new_wordv; /* temporary for realloc() */ sigset_t newsigblock; sigset_t oldsigblock; const char *ifs = getenv("IFS"); serrno = errno; - if(pipe2(pdes, O_CLOEXEC) < 0) + if (pipe2(pdes, O_CLOEXEC) < 0) return WRDE_NOSPACE; (void)sigemptyset(&newsigblock); (void)sigaddset(&newsigblock, SIGCHLD); (void)sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock); - if((pid = fork()) < 0) { + if ((pid = fork()) < 0) { serrno = errno; close(pdes[0]); close(pdes[1]); (void)sigprocmask(SIG_SETMASK, &oldsigblock, NULL); errno = serrno; return WRDE_NOSPACE; - } else if(pid == 0) { + } else if (pid == 0) { /* * We are the child; make /bin/sh expand `words'. */ (void)sigprocmask(SIG_SETMASK, &oldsigblock, NULL); - if((pdes[1] != STDOUT_FILENO ? dup2(pdes[1], STDOUT_FILENO) : fcntl(pdes[1], F_SETFD, 0)) < 0) + if ((pdes[1] != STDOUT_FILENO ? dup2(pdes[1], STDOUT_FILENO) : fcntl(pdes[1], F_SETFD, 0)) < + 0) _exit(1); - execl(SHELL_PATH, SHELL_NAME, flags & WRDE_UNDEF ? "-u" : "+u", - "-c", "IFS=$1;eval \"$2\";eval \"set -- $3\";IFS=;a=\"$*\";" - "printf '%08x' \"$#\" \"${#a}\";printf '%s\\0' \"$@\"", "", - ifs != NULL ? ifs : " \t\n", - flags & WRDE_SHOWERR ? "" : "exec 2>/dev/null", - words, - (char *)NULL); + execl( + SHELL_PATH, + SHELL_NAME, + flags & WRDE_UNDEF ? "-u" : "+u", + "-c", + "IFS=$1;eval \"$2\";eval \"set -- $3\";IFS=;a=\"$*\";" + "printf '%08x' \"$#\" \"${#a}\";printf '%s\\0' \"$@\"", + "", + ifs != NULL ? ifs : " \t\n", + flags & WRDE_SHOWERR ? "" : "exec 2>/dev/null", + words, + (char *)NULL + ); _exit(1); } @@ -117,7 +124,7 @@ static int we_askshell(const char *words, wordexp_t *we, int flags) { * the expanded words separated by nulls. */ close(pdes[1]); - if(we_read_fully(pdes[0], wbuf, 8) != 8 || we_read_fully(pdes[0], bbuf, 8) != 8) { + if (we_read_fully(pdes[0], wbuf, 8) != 8 || we_read_fully(pdes[0], bbuf, 8) != 8) { error = flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX; serrno = errno; goto cleanup; @@ -133,30 +140,33 @@ static int we_askshell(const char *words, wordexp_t *we, int flags) { */ sofs = we->we_nbytes; vofs = we->we_wordc; - if((flags & (WRDE_DOOFFS|WRDE_APPEND)) == (WRDE_DOOFFS | WRDE_APPEND)) + if ((flags & (WRDE_DOOFFS | WRDE_APPEND)) == (WRDE_DOOFFS | WRDE_APPEND)) vofs += we->we_offs; we->we_wordc += nwords; we->we_nbytes += nbytes; - if((new_wordv = (char **) realloc(we->we_wordv, (we->we_wordc + 1 + (flags & WRDE_DOOFFS ? we->we_offs : 0)) * sizeof(char *))) == NULL) { + if ((new_wordv = (char **)realloc( + we->we_wordv, + (we->we_wordc + 1 + (flags & WRDE_DOOFFS ? we->we_offs : 0)) * sizeof(char *) + )) == NULL) { error = WRDE_NOSPACE; goto cleanup; } we->we_wordv = new_wordv; - if((nstrings = (char *) realloc(we->we_strings, we->we_nbytes)) == NULL) { + if ((nstrings = (char *)realloc(we->we_strings, we->we_nbytes)) == NULL) { error = WRDE_NOSPACE; goto cleanup; } - for(size_t i = 0; i < vofs; i++) { - if(we->we_wordv[i] != NULL) + for (size_t i = 0; i < vofs; i++) { + if (we->we_wordv[i] != NULL) we->we_wordv[i] += nstrings - we->we_strings; } we->we_strings = nstrings; - if(we_read_fully(pdes[0], we->we_strings + sofs, nbytes) != nbytes) { + if (we_read_fully(pdes[0], we->we_strings + sofs, nbytes) != nbytes) { error = flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX; serrno = errno; goto cleanup; @@ -168,23 +178,23 @@ static int we_askshell(const char *words, wordexp_t *we, int flags) { do { wpid = waitpid(pid, &status, 0); - } while(wpid < 0 && errno == EINTR); + } while (wpid < 0 && errno == EINTR); (void)sigprocmask(SIG_SETMASK, &oldsigblock, NULL); - if(error != 0) { + if (error != 0) { errno = serrno; return error; } - if(wpid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) + if (wpid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) return flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX; /* * Break the null-terminated expanded word strings out into * the vector. */ - if(vofs == 0 && flags & WRDE_DOOFFS) { + if (vofs == 0 && flags & WRDE_DOOFFS) { while (vofs < we->we_offs) we->we_wordv[vofs++] = NULL; } @@ -192,7 +202,7 @@ static int we_askshell(const char *words, wordexp_t *we, int flags) { p = we->we_strings + sofs; while (nwords-- != 0) { we->we_wordv[vofs++] = p; - if((np = (char *) memchr(p, '\0', nbytes)) == NULL) + if ((np = (char *)memchr(p, '\0', nbytes)) == NULL) return WRDE_NOSPACE; nbytes -= np - p + 1; @@ -209,120 +219,119 @@ static int we_askshell(const char *words, wordexp_t *we, int flags) { * special characters: |&;<>(){} * or command substitutions when WRDE_NOCMD is set in flags. */ -static int we_check(const char *words, int flags) -{ +static int we_check(const char *words, int flags) { char c; int dquote, level, quote, squote; quote = squote = dquote = 0; while ((c = *words++) != '\0') { switch (c) { - case '\\': { - if(squote == 0) - quote ^= 1; - continue; - } - case '\'': { - if(quote + dquote == 0) - squote ^= 1; - break; - } - case '"': { - if(quote + squote == 0) - dquote ^= 1; + case '\\': { + if (squote == 0) + quote ^= 1; + continue; + } + case '\'': { + if (quote + dquote == 0) + squote ^= 1; + break; + } + case '"': { + if (quote + squote == 0) + dquote ^= 1; + break; + } + case '`': { + if (quote + squote == 0 && flags & WRDE_NOCMD) + return WRDE_CMDSUB; + while ((c = *words++) != '\0' && c != '`') + if (c == '\\' && (c = *words++) == '\0') + break; + if (c == '\0') + return WRDE_SYNTAX; + break; + } + case '|': + case '&': + case ';': + case '<': + case '>': + case '{': + case '}': + case '(': + case ')': + case '\n': { + if (quote + squote + dquote == 0) + return WRDE_BADCHAR; + break; + } + case '$': { + if ((c = *words++) == '\0') break; - } - case '`': { - if(quote + squote == 0 && flags & WRDE_NOCMD) + else if (quote + squote == 0 && c == '(') { + if (flags & WRDE_NOCMD && *words != '(') return WRDE_CMDSUB; - while ((c = *words++) != '\0' && c != '`') - if(c == '\\' && (c = *words++) == '\0') + level = 1; + while ((c = *words++) != '\0') { + if (c == '\\') { + if ((c = *words++) == '\0') + break; + } else if (c == '(') + level++; + else if (c == ')' && --level == 0) break; - if(c == '\0') + } + if (c == '\0' || level != 0) return WRDE_SYNTAX; - break; - } - case '|': - case '&': - case ';': - case '<': - case '>': - case '{': - case '}': - case '(': - case ')': - case '\n': { - if(quote + squote + dquote == 0) - return WRDE_BADCHAR; - break; - } - case '$': { - if((c = *words++) == '\0') - break; - else if(quote + squote == 0 && c == '(') { - if(flags & WRDE_NOCMD && *words != '(') - return WRDE_CMDSUB; - level = 1; - while ((c = *words++) != '\0') { - if(c == '\\') { - if((c = *words++) == '\0') - break; - } else if(c == '(') - level++; - else if(c == ')' && --level == 0) + } else if (quote + squote == 0 && c == '{') { + level = 1; + while ((c = *words++) != '\0') { + if (c == '\\') { + if ((c = *words++) == '\0') break; - } - if(c == '\0' || level != 0) - return WRDE_SYNTAX; - } else if(quote + squote == 0 && c == '{') { - level = 1; - while ((c = *words++) != '\0') { - if(c == '\\') { - if((c = *words++) == '\0') - break; - } else if(c == '{') - level++; - else if(c == '}' && --level == 0) - break; - } - if(c == '\0' || level != 0) - return WRDE_SYNTAX; - } else - --words; - break; - } - default: { - break; - } + } else if (c == '{') + level++; + else if (c == '}' && --level == 0) + break; + } + if (c == '\0' || level != 0) + return WRDE_SYNTAX; + } else + --words; + break; + } + default: { + break; + } } quote = 0; } - if(quote + squote + dquote != 0) + if (quote + squote + dquote != 0) return WRDE_SYNTAX; return 0; } -int wordexp(const char * __restrict words, wordexp_t * __restrict we, int flags) { +int wordexp(const char *__restrict words, wordexp_t *__restrict we, int flags) { int error; - if(flags & WRDE_REUSE) + if (flags & WRDE_REUSE) wordfree(we); - if((flags & WRDE_APPEND) == 0) { + if ((flags & WRDE_APPEND) == 0) { we->we_wordc = 0; we->we_wordv = NULL; we->we_strings = NULL; we->we_nbytes = 0; } - if((error = we_check(words, flags)) != 0) { + if ((error = we_check(words, flags)) != 0) { wordfree(we); return error; } - if((error = we_askshell(words, we, flags)) != 0) { + if ((error = we_askshell(words, we, flags)) != 0) { wordfree(we); return error; } diff --git a/options/posix/include/arpa/inet.h b/options/posix/include/arpa/inet.h index 1ea035ca95..bee0887d21 100644 --- a/options/posix/include/arpa/inet.h +++ b/options/posix/include/arpa/inet.h @@ -29,8 +29,9 @@ int inet_aton(const char *__cp, struct in_addr *__dest); /* ---------------------------------------------------------------------------- */ /* Generic IP address manipulation. */ /* ---------------------------------------------------------------------------- */ -const char *inet_ntop(int __af, const void *__restrict __src, char *__restrict __dst, - socklen_t __size) __attribute__((__nonnull__(3))); +const char * +inet_ntop(int __af, const void *__restrict __src, char *__restrict __dst, socklen_t __size) + __attribute__((__nonnull__(3))); int inet_pton(int __af, const char *__restrict __src, void *__restrict __dst); struct in_addr inet_makeaddr(in_addr_t __net, in_addr_t __host); @@ -43,4 +44,3 @@ in_addr_t inet_netof(struct in_addr __in); #endif #endif /* _ARPA_INET_H */ - diff --git a/options/posix/include/bits/posix/posix_ctype.h b/options/posix/include/bits/posix/posix_ctype.h index 4e715fbf7a..926048a2f9 100644 --- a/options/posix/include/bits/posix/posix_ctype.h +++ b/options/posix/include/bits/posix/posix_ctype.h @@ -25,7 +25,7 @@ int isxdigit_l(int __c, locale_t __loc); int isascii_l(int __c, locale_t __loc); int tolower_l(int __c, locale_t __loc); -int toupper_l(int __c, locale_t __loc); +int toupper_l(int __c, locale_t __loc); #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/posix/include/bits/posix/posix_signal.h b/options/posix/include/bits/posix/posix_signal.h index 2d67a84363..6fe535465e 100644 --- a/options/posix/include/bits/posix/posix_signal.h +++ b/options/posix/include/bits/posix/posix_signal.h @@ -10,47 +10,47 @@ extern "C" { #include #include #include +#include #include #include -#include -#define FPE_INTDIV 1 /* integer divide by zero */ -#define FPE_INTOVF 2 /* integer overflow */ -#define FPE_FLTDIV 3 /* floating point divide by zero */ -#define FPE_FLTOVF 4 /* floating point overflow */ -#define FPE_FLTUND 5 /* floating point underflow */ -#define FPE_FLTRES 6 /* floating point inexact result */ -#define FPE_FLTINV 7 /* floating point invalid operation */ -#define FPE_FLTSUB 8 /* subscript out of range */ +#define FPE_INTDIV 1 /* integer divide by zero */ +#define FPE_INTOVF 2 /* integer overflow */ +#define FPE_FLTDIV 3 /* floating point divide by zero */ +#define FPE_FLTOVF 4 /* floating point overflow */ +#define FPE_FLTUND 5 /* floating point underflow */ +#define FPE_FLTRES 6 /* floating point inexact result */ +#define FPE_FLTINV 7 /* floating point invalid operation */ +#define FPE_FLTSUB 8 /* subscript out of range */ -#define TRAP_BRKPT 1 /* process breakpoint */ -#define TRAP_TRACE 2 /* process trace trap */ +#define TRAP_BRKPT 1 /* process breakpoint */ +#define TRAP_TRACE 2 /* process trace trap */ #if defined(__x86_64__) /* Start Glibc stuff */ struct _libc_fpxreg { - unsigned short int significand[4]; - unsigned short int exponent; - unsigned short int __glibc_reserved1[3]; + unsigned short int significand[4]; + unsigned short int exponent; + unsigned short int __glibc_reserved1[3]; }; struct _libc_xmmreg { - uint32_t element[4]; + uint32_t element[4]; }; struct _libc_fpstate { - uint16_t cwd; - int16_t swd; - uint16_t ftw; - uint16_t fop; - uint64_t rip; - uint64_t dp; - uint32_t mxcsr; - uint32_t mxcr_mask; - struct _libc_fpxreg _st[8]; - struct _libc_xmmreg _xmm[16]; - uint32_t __glibc_reserved1[24]; + uint16_t cwd; + int16_t swd; + uint16_t ftw; + uint16_t fop; + uint64_t rip; + uint64_t dp; + uint32_t mxcsr; + uint32_t mxcr_mask; + struct _libc_fpxreg _st[8]; + struct _libc_xmmreg _xmm[16]; + uint32_t __glibc_reserved1[24]; }; typedef struct _libc_fpstate *fpregset_t; @@ -59,17 +59,17 @@ typedef struct _libc_fpstate *fpregset_t; typedef unsigned long int greg_t; #endif -#define FPE_INTDIV 1 /* integer divide by zero */ -#define FPE_INTOVF 2 /* integer overflow */ -#define FPE_FLTDIV 3 /* floating point divide by zero */ -#define FPE_FLTOVF 4 /* floating point overflow */ -#define FPE_FLTUND 5 /* floating point underflow */ -#define FPE_FLTRES 6 /* floating point inexact result */ -#define FPE_FLTINV 7 /* floating point invalid operation */ -#define FPE_FLTSUB 8 /* subscript out of range */ +#define FPE_INTDIV 1 /* integer divide by zero */ +#define FPE_INTOVF 2 /* integer overflow */ +#define FPE_FLTDIV 3 /* floating point divide by zero */ +#define FPE_FLTOVF 4 /* floating point overflow */ +#define FPE_FLTUND 5 /* floating point underflow */ +#define FPE_FLTRES 6 /* floating point inexact result */ +#define FPE_FLTINV 7 /* floating point invalid operation */ +#define FPE_FLTSUB 8 /* subscript out of range */ -#define TRAP_BRKPT 1 /* process breakpoint */ -#define TRAP_TRACE 2 /* process trace trap */ +#define TRAP_BRKPT 1 /* process breakpoint */ +#define TRAP_TRACE 2 /* process trace trap */ #ifndef __MLIBC_ABI_ONLY @@ -77,11 +77,14 @@ typedef unsigned long int greg_t; int sigsuspend(const sigset_t *__sigmask); int sigprocmask(int __how, const sigset_t *__restrict __sigmask, sigset_t *__restrict __oldmask); -int pthread_sigmask(int __how, const sigset_t *__restrict __sigmask, sigset_t *__restrict __oldmask); +int +pthread_sigmask(int __how, const sigset_t *__restrict __sigmask, sigset_t *__restrict __oldmask); int pthread_kill(pthread_t __thrd, int __sig); /* functions to handle signals */ -int sigaction(int __signum, const struct sigaction *__restrict __act, struct sigaction *__restrict __oldact); +int sigaction( + int __signum, const struct sigaction *__restrict __act, struct sigaction *__restrict __oldact +); int sigpending(sigset_t *__set); int siginterrupt(int __sig, int __flag); @@ -92,7 +95,11 @@ int sigaltstack(const stack_t *__restrict __ss, stack_t *__restrict __oss); int kill(pid_t __pid, int __number); int killpg(int __pgrp, int __sig); -int sigtimedwait(const sigset_t *__restrict __set, siginfo_t *__restrict __info, const struct timespec *__restrict __timeout); +int sigtimedwait( + const sigset_t *__restrict __set, + siginfo_t *__restrict __info, + const struct timespec *__restrict __timeout +); int sigwait(const sigset_t *__restrict __set, int *__restrict __sig); int sigwaitinfo(const sigset_t *__restrict __set, siginfo_t *__restrict __info); @@ -110,4 +117,3 @@ int sigqueue(pid_t __pid, int __sig, const union sigval __value); #endif #endif /* MLIBC_POSIX_SIGNAL_H */ - diff --git a/options/posix/include/bits/posix/posix_stdio.h b/options/posix/include/bits/posix/posix_stdio.h index 360be7c626..196ac5dc5a 100644 --- a/options/posix/include/bits/posix/posix_stdio.h +++ b/options/posix/include/bits/posix/posix_stdio.h @@ -2,10 +2,10 @@ #ifndef MLIBC_POSIX_STDIO_H #define MLIBC_POSIX_STDIO_H +#include #include #include #include -#include /* MISSING: var_list */ @@ -31,8 +31,8 @@ off_t ftello(FILE *__stream); off64_t ftello64(FILE *__stream); __attribute__((format(__printf__, 2, 3))) int dprintf(int __fd, const char *__format, ...); -__attribute__((format(__printf__, 2, 0))) -int vdprintf(int __fd, const char *__format, __builtin_va_list __args); +__attribute__((format(__printf__, 2, 0))) int +vdprintf(int __fd, const char *__format, __builtin_va_list __args); char *fgetln(FILE *__stream, size_t *__size); @@ -43,10 +43,10 @@ char *tempnam(const char *__dir, const char *__pfx); #define RENAME_EXCHANGE (1 << 1) /* GNU extensions */ -typedef ssize_t (cookie_read_function_t)(void *__cookie, char *__buffer, size_t __size); -typedef ssize_t (cookie_write_function_t)(void *__cookie, const char *__buffer, size_t __size); -typedef int (cookie_seek_function_t)(void *__cookie, off_t *, int); -typedef int (cookie_close_function_t)(void *__cookie); +typedef ssize_t(cookie_read_function_t)(void *__cookie, char *__buffer, size_t __size); +typedef ssize_t(cookie_write_function_t)(void *__cookie, const char *__buffer, size_t __size); +typedef int(cookie_seek_function_t)(void *__cookie, off_t *, int); +typedef int(cookie_close_function_t)(void *__cookie); typedef struct _IO_cookie_io_functions_t { cookie_read_function_t *read; @@ -59,7 +59,9 @@ typedef struct _IO_cookie_io_functions_t { #if defined(_GNU_SOURCE) -FILE *fopencookie(void *__restrict __cookie, const char *__restrict __mode, cookie_io_functions_t __io_funcs); +FILE *fopencookie( + void *__restrict __cookie, const char *__restrict __mode, cookie_io_functions_t __io_funcs +); #endif /* defined(_GNU_SOURCE) */ @@ -72,5 +74,3 @@ FILE *fopencookie(void *__restrict __cookie, const char *__restrict __mode, cook /* MISSING: various functions and macros */ #endif /* MLIBC_POSIX_STDIO_H */ - - diff --git a/options/posix/include/bits/posix/posix_stdlib.h b/options/posix/include/bits/posix/posix_stdlib.h index f124c043b7..eae00af66c 100644 --- a/options/posix/include/bits/posix/posix_stdlib.h +++ b/options/posix/include/bits/posix/posix_stdlib.h @@ -51,13 +51,16 @@ int unlockpt(int __fd); char *ptsname(int __fd); int ptsname_r(int __fd, char *__buf, size_t __len); -double strtod_l(const char *__restrict__ __nptr, char ** __restrict__ __endptr, locale_t __loc); -long double strtold_l(const char *__restrict__ __nptr, char ** __restrict__ __endptr, locale_t __loc); +double strtod_l(const char *__restrict__ __nptr, char **__restrict__ __endptr, locale_t __loc); +long double +strtold_l(const char *__restrict__ __nptr, char **__restrict__ __endptr, locale_t __loc); float strtof_l(const char *__restrict __string, char **__restrict __end, locale_t __loc); int getloadavg(double *__loadavg, int __count); -int getsubopt(char **__restrict__ __optionp, char *const *__restrict__ __tokens, char **__restrict__ __valuep); +int getsubopt( + char **__restrict__ __optionp, char *const *__restrict__ __tokens, char **__restrict__ __valuep +); /* GNU extension */ char *secure_getenv(const char *__name); @@ -75,4 +78,3 @@ int clearenv(void); #endif #endif /* MLIBC_POSIX_STDLIB_H */ - diff --git a/options/posix/include/bits/posix/posix_string.h b/options/posix/include/bits/posix/posix_string.h index 1e2096ae10..060eb5a324 100644 --- a/options/posix/include/bits/posix/posix_string.h +++ b/options/posix/include/bits/posix/posix_string.h @@ -29,19 +29,21 @@ char *strerror_l(int __errnum, locale_t __locale); /* GNU extensions. */ #if defined(_GNU_SOURCE) char *strcasestr(const char *__s1, const char *__s2); -#define strdupa(x) ({ \ - const char *__str = (x); \ - size_t __len = strlen(__str) + 1; \ - char *__buf = alloca(__len); \ - (char *) memcpy(__buf, __str, __len); \ -}) -#define strndupa(x, y) ({ \ - const char *__str = (x); \ - size_t __len = strnlen(__str, (y)) + 1; \ - char *__buf = alloca(__len); \ - __buf[__len - 1] = '\0'; \ - (char *) memcpy(__buf, __str, __len - 1); \ -}) +#define strdupa(x) \ + ({ \ + const char *__str = (x); \ + size_t __len = strlen(__str) + 1; \ + char *__buf = alloca(__len); \ + (char *)memcpy(__buf, __str, __len); \ + }) +#define strndupa(x, y) \ + ({ \ + const char *__str = (x); \ + size_t __len = strnlen(__str, (y)) + 1; \ + char *__buf = alloca(__len); \ + __buf[__len - 1] = '\0'; \ + (char *)memcpy(__buf, __str, __len - 1); \ + }) void *memrchr(const void *__m, int __c, size_t __n); #endif /* defined(_GNU_SOURCE) */ @@ -56,4 +58,3 @@ size_t strlcat(char *__d, const char *__s, size_t __n); #endif #endif /* MLIBC_POSIX_STRING_H */ - diff --git a/options/posix/include/bits/posix/posix_wctype.h b/options/posix/include/bits/posix/posix_wctype.h index 3c4bd7aaf0..b24a3ae7d5 100644 --- a/options/posix/include/bits/posix/posix_wctype.h +++ b/options/posix/include/bits/posix/posix_wctype.h @@ -2,9 +2,9 @@ #define _POSIX_WCTYPE_H #include -#include -#include #include +#include +#include #ifdef __cplusplus extern "C" { diff --git a/options/posix/include/bits/posix/stat.h b/options/posix/include/bits/posix/stat.h index f08b760cfd..4f514d1137 100644 --- a/options/posix/include/bits/posix/stat.h +++ b/options/posix/include/bits/posix/stat.h @@ -21,4 +21,3 @@ #define st_ctime st_ctim.tv_sec #endif /* MLIBC_STAT_H */ - diff --git a/options/posix/include/bits/posix/timer_t.h b/options/posix/include/bits/posix/timer_t.h index b965f373dc..fcc22b718c 100644 --- a/options/posix/include/bits/posix/timer_t.h +++ b/options/posix/include/bits/posix/timer_t.h @@ -1,6 +1,6 @@ #ifndef _MLIBC_TIMER_T_H #define _MLIBC_TIMER_T_H -typedef void * timer_t; +typedef void *timer_t; #endif /* _MLIBC_TIMER_T_H */ diff --git a/options/posix/include/bits/posix/timeval.h b/options/posix/include/bits/posix/timeval.h index 22670a2eb9..7c8f233249 100644 --- a/options/posix/include/bits/posix/timeval.h +++ b/options/posix/include/bits/posix/timeval.h @@ -1,8 +1,8 @@ #ifndef MLIBC_TIMEVAL_H #define MLIBC_TIMEVAL_H -#include #include +#include struct timeval { time_t tv_sec; diff --git a/options/posix/include/byteswap.h b/options/posix/include/byteswap.h index 29b28382db..d7629a9b7d 100644 --- a/options/posix/include/byteswap.h +++ b/options/posix/include/byteswap.h @@ -20,4 +20,3 @@ extern "C" { #endif #endif /* _BYTESWAP_H */ - diff --git a/options/posix/include/dirent.h b/options/posix/include/dirent.h index 95d609a986..9021116862 100644 --- a/options/posix/include/dirent.h +++ b/options/posix/include/dirent.h @@ -20,11 +20,12 @@ extern "C" { #define DT_SOCK 12 #define DT_WHT 14 -#define __MLIBC_DIRENT_BODY ino_t d_ino; \ - off_t d_off; \ - unsigned short d_reclen; \ - unsigned char d_type; \ - char d_name[1024]; +#define __MLIBC_DIRENT_BODY \ + ino_t d_ino; \ + off_t d_off; \ + unsigned short d_reclen; \ + unsigned char d_type; \ + char d_name[1024]; struct dirent { __MLIBC_DIRENT_BODY @@ -59,10 +60,16 @@ DIR *fdopendir(int __fd); DIR *opendir(const char *__pathname); struct dirent *readdir(DIR *__dirp); struct dirent64 *readdir64(DIR *__dirp); -int readdir_r(DIR *__restrict __dirp, struct dirent *__restrict __entry, struct dirent **__restrict __res); +int readdir_r( + DIR *__restrict __dirp, struct dirent *__restrict __entry, struct dirent **__restrict __res +); void rewinddir(DIR *__dirp); -int scandir(const char *__pathname, struct dirent ***__res, int (*__select)(const struct dirent *__entry), - int (*__compare)(const struct dirent **__a, const struct dirent **__b)); +int scandir( + const char *__pathname, + struct dirent ***__res, + int (*__select)(const struct dirent *__entry), + int (*__compare)(const struct dirent **__a, const struct dirent **__b) +); void seekdir(DIR *__dirp, long __loc); long telldir(DIR *__dirp); int versionsort(const struct dirent **__a, const struct dirent **__b); @@ -74,4 +81,3 @@ int versionsort(const struct dirent **__a, const struct dirent **__b); #endif #endif /* _DIRENT_H */ - diff --git a/options/posix/include/dlfcn.h b/options/posix/include/dlfcn.h index 4e63279935..ea46067626 100644 --- a/options/posix/include/dlfcn.h +++ b/options/posix/include/dlfcn.h @@ -30,7 +30,8 @@ int dlclose(void *__handle); char *dlerror(void); void *dlopen(const char *__name, int __flags); void *dlsym(void *__restrict __handle, const char *__restrict __name); -void *dlvsym(void *__restrict __handle, const char *__restrict __name, const char *__restrict __version); +void * +dlvsym(void *__restrict __handle, const char *__restrict __name, const char *__restrict __version); #endif /* !__MLIBC_ABI_ONLY */ @@ -93,4 +94,3 @@ int _dl_find_object(void *__address, struct dl_find_object *__result); #endif #endif /* _DLFCN_H */ - diff --git a/options/posix/include/fcntl.h b/options/posix/include/fcntl.h index 079a6820c7..ef3d842f3f 100644 --- a/options/posix/include/fcntl.h +++ b/options/posix/include/fcntl.h @@ -3,13 +3,13 @@ #define _FCNTL_H #include -#include #include #include -#include +#include #include -#include +#include #include +#include #ifdef __cplusplus extern "C" { @@ -51,20 +51,24 @@ int posix_fallocate(int __fd, off_t __offset, off_t __size); /* This is a linux extension */ #ifdef _GNU_SOURCE struct file_handle { - unsigned int handle_bytes; - int handle_type; - unsigned char f_handle[0]; + unsigned int handle_bytes; + int handle_type; + unsigned char f_handle[0]; }; #endif #ifndef __MLIBC_ABI_ONLY #ifdef _GNU_SOURCE -int name_to_handle_at(int __dirfd, const char *__path, struct file_handle *__handle, int *__mount_id, int __flags); +int name_to_handle_at( + int __dirfd, const char *__path, struct file_handle *__handle, int *__mount_id, int __flags +); int open_by_handle_at(int __dirfd, struct file_handle *__handle, int __flags); #endif -ssize_t splice(int __fd_in, off_t *__off_in, int __fd_out, off_t *__off_out, size_t __len, unsigned int __flags); +ssize_t splice( + int __fd_in, off_t *__off_in, int __fd_out, off_t *__off_out, size_t __len, unsigned int __flags +); ssize_t vmsplice(int __fd, const struct iovec *__iov, size_t __nr_segs, unsigned int __flags); #endif /* !__MLIBC_ABI_ONLY */ @@ -85,4 +89,3 @@ ssize_t vmsplice(int __fd, const struct iovec *__iov, size_t __nr_segs, unsigned #endif #endif /* _FCNTL_H */ - diff --git a/options/posix/include/fnmatch.h b/options/posix/include/fnmatch.h index 5c5dda0dda..a8458ba466 100644 --- a/options/posix/include/fnmatch.h +++ b/options/posix/include/fnmatch.h @@ -30,4 +30,3 @@ int fnmatch(const char *__pattern, const char *__string, int __flags); #endif #endif /* _FNMATCH_H */ - diff --git a/options/posix/include/ftw.h b/options/posix/include/ftw.h index 169fa2a07b..c9088205f2 100644 --- a/options/posix/include/ftw.h +++ b/options/posix/include/ftw.h @@ -30,10 +30,16 @@ struct FTW { #ifndef __MLIBC_ABI_ONLY -int ftw(const char *__dirpath, int (*__fn)(const char *__fpath, const struct stat *__sb, int __typeflag), - int __nopenfd); -int nftw(const char *__dirpath, int (*__fn)(const char *__fpath, const struct stat *__sb, int __typeflag, - struct FTW *__ftwbuf), int __nopenfd, int __flags); +int +ftw(const char *__dirpath, + int (*__fn)(const char *__fpath, const struct stat *__sb, int __typeflag), + int __nopenfd); +int nftw( + const char *__dirpath, + int (*__fn)(const char *__fpath, const struct stat *__sb, int __typeflag, struct FTW *__ftwbuf), + int __nopenfd, + int __flags +); #endif /* !__MLIBC_ABI_ONLY */ @@ -42,4 +48,3 @@ int nftw(const char *__dirpath, int (*__fn)(const char *__fpath, const struct st #endif #endif /* _FTW_H */ - diff --git a/options/posix/include/glob.h b/options/posix/include/glob.h index 57e3219060..f04fb91167 100644 --- a/options/posix/include/glob.h +++ b/options/posix/include/glob.h @@ -35,17 +35,21 @@ typedef struct glob_t { char **gl_pathv; size_t gl_offs; int gl_flags; - void (*gl_closedir) (void *); - struct dirent *(*gl_readdir) (void *); - void *(*gl_opendir) (const char *); - int (*gl_lstat) (const char *__restrict, struct stat *__restrict); - int (*gl_stat) (const char *__restrict, struct stat *__restrict); + void (*gl_closedir)(void *); + struct dirent *(*gl_readdir)(void *); + void *(*gl_opendir)(const char *); + int (*gl_lstat)(const char *__restrict, struct stat *__restrict); + int (*gl_stat)(const char *__restrict, struct stat *__restrict); } glob_t; #ifndef __MLIBC_ABI_ONLY -int glob(const char *__restrict __pattern, int __flags, - int(*__errfunc)(const char *__epath, int __errnum), struct glob_t *__restrict __pglob); +int glob( + const char *__restrict __pattern, + int __flags, + int (*__errfunc)(const char *__epath, int __errnum), + struct glob_t *__restrict __pglob +); void globfree(struct glob_t *__pglog); #endif /* !__MLIBC_ABI_ONLY */ @@ -55,5 +59,3 @@ void globfree(struct glob_t *__pglog); #endif #endif /* _GLOB_H */ - - diff --git a/options/posix/include/grp.h b/options/posix/include/grp.h index 6b16d71170..af148093ec 100644 --- a/options/posix/include/grp.h +++ b/options/posix/include/grp.h @@ -1,9 +1,9 @@ #ifndef _GRP_H #define _GRP_H +#include #include #include -#include #ifdef __cplusplus extern "C" { @@ -21,9 +21,12 @@ struct group { void endgrent(void); struct group *getgrent(void); struct group *getgrgid(gid_t __gid); -int getgrgid_r(gid_t __gid, struct group *__grp, char *__buf, size_t __buflen, struct group **__res); +int +getgrgid_r(gid_t __gid, struct group *__grp, char *__buf, size_t __buflen, struct group **__res); struct group *getgrnam(const char *__name); -int getgrnam_r(const char *__name, struct group *__grp, char *__buf, size_t __buflen, struct group **__res); +int getgrnam_r( + const char *__name, struct group *__grp, char *__buf, size_t __buflen, struct group **__res +); void setgrent(void); int putgrent(const struct group *__grp, FILE *__stream); struct group *fgetgrent(FILE *__stream); diff --git a/options/posix/include/langinfo.h b/options/posix/include/langinfo.h index 2a5bf0feb5..a551c837a5 100644 --- a/options/posix/include/langinfo.h +++ b/options/posix/include/langinfo.h @@ -6,8 +6,8 @@ extern "C" { #endif -#include #include +#include #ifndef __MLIBC_ABI_ONLY @@ -21,4 +21,3 @@ char *nl_langinfo_l(nl_item __item, locale_t __loc); #endif #endif /* _LANGINFO_H */ - diff --git a/options/posix/include/libgen.h b/options/posix/include/libgen.h index 69ece1d092..d93d170404 100644 --- a/options/posix/include/libgen.h +++ b/options/posix/include/libgen.h @@ -8,7 +8,7 @@ extern "C" { #if defined(basename) && defined(_GNU_SOURCE) /* see: ./options/ansi/include/string.h, search for __mlibc_gnu_basename */ -# undef basename +#undef basename #endif #ifndef __MLIBC_ABI_ONLY @@ -24,5 +24,3 @@ char *dirname(char *__path); #endif #endif /* _LIBGEN_H */ - - diff --git a/options/posix/include/mlibc/lookup.hpp b/options/posix/include/mlibc/lookup.hpp index 71f84e73a9..d1bfcbad8a 100644 --- a/options/posix/include/mlibc/lookup.hpp +++ b/options/posix/include/mlibc/lookup.hpp @@ -1,28 +1,26 @@ #ifndef _MLIBC_LOOKUP #define _MLIBC_LOOKUP -#include -#include -#include +#include +#include #include #include -#include -#include #include +#include +#include +#include namespace mlibc { struct dns_addr_buf { - dns_addr_buf() - : name(getAllocator()) {} + dns_addr_buf() : name(getAllocator()) {} frg::string name; int family; uint8_t addr[16]; }; struct lookup_result { - lookup_result() - : buf(getAllocator()), aliases(getAllocator()) {} + lookup_result() : buf(getAllocator()), aliases(getAllocator()) {} frg::vector buf; frg::vector, MemoryAllocator> aliases; }; @@ -44,11 +42,13 @@ struct ai_buf { } sa; }; -int lookup_name_dns(struct lookup_result &buf, const char *name, - frg::string &canon_name); +int lookup_name_dns( + struct lookup_result &buf, const char *name, frg::string &canon_name +); int lookup_addr_dns(frg::span name, frg::array &addr, int family); -int lookup_name_hosts(struct lookup_result &buf, const char *name, - frg::string &canon_name); +int lookup_name_hosts( + struct lookup_result &buf, const char *name, frg::string &canon_name +); int lookup_addr_hosts(frg::span name, frg::array &addr, int family); int lookup_name_null(struct lookup_result &buf, int flags, int family); int lookup_name_ip(struct lookup_result &buf, const char *name, int family); diff --git a/options/posix/include/mlibc/posix-file-io.hpp b/options/posix/include/mlibc/posix-file-io.hpp index 63d6037cd1..1b49556196 100644 --- a/options/posix/include/mlibc/posix-file-io.hpp +++ b/options/posix/include/mlibc/posix-file-io.hpp @@ -3,16 +3,19 @@ #include #include -#include #include +#include namespace mlibc { struct mem_file : abstract_file { - mem_file(int flags, void (*do_dispose)(abstract_file *) = nullptr) : abstract_file{do_dispose}, _flags{flags} { }; + mem_file(int flags, void (*do_dispose)(abstract_file *) = nullptr) + : abstract_file{do_dispose}, + _flags{flags} {}; int reopen(const char *path, const char *mode) override; -protected: + + protected: int determine_type(stream_type *type) override; int determine_bufmode(buffer_mode *mode) override; @@ -26,7 +29,9 @@ struct mem_file : abstract_file { }; struct memstream_mem_file final : public mem_file { - memstream_mem_file(char **ptr, size_t *sizeloc, int flags, void (*do_dispose)(abstract_file *) = nullptr); + memstream_mem_file( + char **ptr, size_t *sizeloc, int flags, void (*do_dispose)(abstract_file *) = nullptr + ); int close() override; @@ -34,15 +39,11 @@ struct memstream_mem_file final : public mem_file { int io_write(const char *buffer, size_t max_size, size_t *actual_size) override; int io_seek(off_t offset, int whence, off_t *new_offset) override; - frg::span _buffer() override { - return {_buf.data(), _buffer_size()}; - } + frg::span _buffer() override { return {_buf.data(), _buffer_size()}; } - size_t _buffer_size() const override { - return _buf.size(); - } + size_t _buffer_size() const override { return _buf.size(); } -private: + private: void _update_ptrs(); // Where to write back buffer and size on flush and close. @@ -53,7 +54,9 @@ struct memstream_mem_file final : public mem_file { }; struct fmemopen_mem_file final : public mem_file { - fmemopen_mem_file(void *in_buf, size_t size, int flags, void (*do_dispose)(abstract_file *) = nullptr); + fmemopen_mem_file( + void *in_buf, size_t size, int flags, void (*do_dispose)(abstract_file *) = nullptr + ); int close() override; @@ -65,11 +68,9 @@ struct fmemopen_mem_file final : public mem_file { return {reinterpret_cast(_inBuffer), _buffer_size()}; } - size_t _buffer_size() const override { - return _inBufferSize; - } + size_t _buffer_size() const override { return _inBufferSize; } -private: + private: void *_inBuffer; size_t _inBufferSize; @@ -77,12 +78,21 @@ struct fmemopen_mem_file final : public mem_file { }; struct cookie_file : abstract_file { - cookie_file(void *cookie, int flags, cookie_io_functions_t funcs, void (*do_dispose)(abstract_file *) = nullptr) - : abstract_file{do_dispose}, _cookie{cookie}, _flags{flags}, _funcs{funcs} { } + cookie_file( + void *cookie, + int flags, + cookie_io_functions_t funcs, + void (*do_dispose)(abstract_file *) = nullptr + ) + : abstract_file{do_dispose}, + _cookie{cookie}, + _flags{flags}, + _funcs{funcs} {} int close() override; int reopen(const char *path, const char *mode) override; -protected: + + protected: int determine_type(stream_type *type) override; int determine_bufmode(buffer_mode *mode) override; @@ -90,7 +100,7 @@ struct cookie_file : abstract_file { int io_write(const char *buffer, size_t max_size, size_t *actual_size) override; int io_seek(off_t offset, int whence, off_t *new_offset) override; -private: + private: void *_cookie; [[maybe_unused]] int _flags; diff --git a/options/posix/include/mlibc/posix-sysdeps.hpp b/options/posix/include/mlibc/posix-sysdeps.hpp index a224474be8..69b5de9c8e 100644 --- a/options/posix/include/mlibc/posix-sysdeps.hpp +++ b/options/posix/include/mlibc/posix-sysdeps.hpp @@ -9,23 +9,22 @@ #include #include -#include -#include #include #include #include +#include #include +#include #include -#include #include -#include #include #include +#include #include #include #include +#include #include -#include #include #include #include @@ -43,8 +42,7 @@ int sys_open(const char *pathname, int flags, mode_t mode, int *fd); [[gnu::weak]] int sys_flock(int fd, int options); [[gnu::weak]] int sys_open_dir(const char *path, int *handle); -[[gnu::weak]] int sys_read_entries(int handle, void *buffer, size_t max_size, - size_t *bytes_read); +[[gnu::weak]] int sys_read_entries(int handle, void *buffer, size_t max_size, size_t *bytes_read); int sys_read(int fd, void *buf, size_t count, ssize_t *bytes_read); [[gnu::weak]] int sys_readv(int fd, const struct iovec *iovs, int iovc, ssize_t *bytes_read); @@ -63,12 +61,13 @@ int sys_close(int fd); // In contrast to the isatty() library function, the sysdep function uses return value // zero (and not one) to indicate that the file is a terminal. [[gnu::weak]] int sys_isatty(int fd); -[[gnu::weak]] int sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, - struct stat *statbuf); +[[gnu::weak]] int +sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, struct stat *statbuf); [[gnu::weak]] int sys_statvfs(const char *path, struct statvfs *out); [[gnu::weak]] int sys_fstatvfs(int fd, struct statvfs *out); [[gnu::weak]] int sys_readlink(const char *path, void *buffer, size_t max_size, ssize_t *length); -[[gnu::weak]] int sys_readlinkat(int dirfd, const char *path, void *buffer, size_t max_size, ssize_t *length); +[[gnu::weak]] int +sys_readlinkat(int dirfd, const char *path, void *buffer, size_t max_size, ssize_t *length); [[gnu::weak]] int sys_rmdir(const char *path); [[gnu::weak]] int sys_ftruncate(int fd, size_t size); [[gnu::weak]] int sys_fallocate(int fd, off_t offset, size_t size); @@ -76,9 +75,25 @@ int sys_close(int fd); [[gnu::weak]] int sys_openat(int dirfd, const char *path, int flags, mode_t mode, int *fd); [[gnu::weak]] int sys_socket(int family, int type, int protocol, int *fd); [[gnu::weak]] int sys_msg_send(int fd, const struct msghdr *hdr, int flags, ssize_t *length); -[[gnu::weak]] ssize_t sys_sendto(int fd, const void *buffer, size_t size, int flags, const struct sockaddr *sock_addr, socklen_t addr_length, ssize_t *length); +[[gnu::weak]] ssize_t sys_sendto( + int fd, + const void *buffer, + size_t size, + int flags, + const struct sockaddr *sock_addr, + socklen_t addr_length, + ssize_t *length +); [[gnu::weak]] int sys_msg_recv(int fd, struct msghdr *hdr, int flags, ssize_t *length); -[[gnu::weak]] ssize_t sys_recvfrom(int fd, void *buffer, size_t size, int flags, struct sockaddr *sock_addr, socklen_t *addr_length, ssize_t *length); +[[gnu::weak]] ssize_t sys_recvfrom( + int fd, + void *buffer, + size_t size, + int flags, + struct sockaddr *sock_addr, + socklen_t *addr_length, + ssize_t *length +); [[gnu::weak]] int sys_listen(int fd, int backlog); [[gnu::weak]] gid_t sys_getgid(); [[gnu::weak]] gid_t sys_getegid(); @@ -99,8 +114,15 @@ int sys_close(int fd); [[gnu::weak]] int sys_sleep(time_t *secs, long *nanos); [[gnu::weak]] int sys_fork(pid_t *child); [[gnu::weak]] int sys_execve(const char *path, char *const argv[], char *const envp[]); -[[gnu::weak]] int sys_pselect(int num_fds, fd_set *read_set, fd_set *write_set, - fd_set *except_set, const struct timespec *timeout, const sigset_t *sigmask, int *num_events); +[[gnu::weak]] int sys_pselect( + int num_fds, + fd_set *read_set, + fd_set *write_set, + fd_set *except_set, + const struct timespec *timeout, + const sigset_t *sigmask, + int *num_events +); [[gnu::weak]] int sys_getrusage(int scope, struct rusage *usage); [[gnu::weak]] int sys_getrlimit(int resource, struct rlimit *limit); [[gnu::weak]] int sys_setrlimit(int resource, const struct rlimit *limit); @@ -117,11 +139,13 @@ int sys_close(int fd); [[gnu::weak]] int sys_mkdir(const char *path, mode_t mode); [[gnu::weak]] int sys_mkdirat(int dirfd, const char *path, mode_t mode); [[gnu::weak]] int sys_link(const char *old_path, const char *new_path); -[[gnu::weak]] int sys_linkat(int olddirfd, const char *old_path, int newdirfd, const char *new_path, int flags); +[[gnu::weak]] int +sys_linkat(int olddirfd, const char *old_path, int newdirfd, const char *new_path, int flags); [[gnu::weak]] int sys_symlink(const char *target_path, const char *link_path); [[gnu::weak]] int sys_symlinkat(const char *target_path, int dirfd, const char *link_path); [[gnu::weak]] int sys_rename(const char *path, const char *new_path); -[[gnu::weak]] int sys_renameat(int olddirfd, const char *old_path, int newdirfd, const char *new_path); +[[gnu::weak]] int +sys_renameat(int olddirfd, const char *old_path, int newdirfd, const char *new_path); [[gnu::weak]] int sys_fcntl(int fd, int request, va_list args, int *result); [[gnu::weak]] int sys_ttyname(int fd, char *buf, size_t size); [[gnu::weak]] int sys_fadvise(int fd, off_t offset, off_t length, int advice); @@ -131,7 +155,8 @@ int sys_close(int fd); [[gnu::weak]] int sys_chmod(const char *pathname, mode_t mode); [[gnu::weak]] int sys_fchmod(int fd, mode_t mode); [[gnu::weak]] int sys_fchmodat(int fd, const char *pathname, mode_t mode, int flags); -[[gnu::weak]] int sys_utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags); +[[gnu::weak]] int +sys_utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags); [[gnu::weak]] int sys_mlock(const void *addr, size_t length); [[gnu::weak]] int sys_munlock(const void *addr, size_t length); [[gnu::weak]] int sys_mlockall(int flags); @@ -139,7 +164,8 @@ int sys_close(int fd); [[gnu::weak]] int sys_munlockall(void); [[gnu::weak]] int sys_mincore(void *addr, size_t length, unsigned char *vec); -// mlibc assumes that anonymous memory returned by sys_vm_map() is zeroed by the kernel / whatever is behind the sysdeps +// mlibc assumes that anonymous memory returned by sys_vm_map() is zeroed by the kernel / whatever +// is behind the sysdeps int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offset, void **window); [[gnu::weak]] int sys_vm_remap(void *pointer, size_t size, size_t new_size, void **window); @@ -157,26 +183,33 @@ int sys_vm_unmap(void *pointer, size_t size); [[gnu::weak]] int sys_socketpair(int domain, int type_and_flags, int proto, int *fds); [[gnu::weak]] int sys_poll(struct pollfd *fds, nfds_t count, int timeout, int *num_events); [[gnu::weak]] int sys_ioctl(int fd, unsigned long request, void *arg, int *result); -[[gnu::weak]] int sys_getsockopt(int fd, int layer, int number, - void *__restrict buffer, socklen_t *__restrict size); -[[gnu::weak]] int sys_setsockopt(int fd, int layer, int number, - const void *buffer, socklen_t size); +[[gnu::weak]] int +sys_getsockopt(int fd, int layer, int number, void *__restrict buffer, socklen_t *__restrict size); +[[gnu::weak]] int sys_setsockopt(int fd, int layer, int number, const void *buffer, socklen_t size); [[gnu::weak]] int sys_shutdown(int sockfd, int how); -[[gnu::weak]] int sys_sigprocmask(int how, const sigset_t *__restrict set, - sigset_t *__restrict retrieve); -[[gnu::weak]] int sys_sigaction(int, const struct sigaction *__restrict, - struct sigaction *__restrict); +[[gnu::weak]] int +sys_sigprocmask(int how, const sigset_t *__restrict set, sigset_t *__restrict retrieve); +[[gnu::weak]] int +sys_sigaction(int, const struct sigaction *__restrict, struct sigaction *__restrict); // NOTE: POSIX says that behavior of timeout = nullptr is unspecified. We treat this case // as an infinite timeout, making sigtimedwait(..., nullptr) equivalent to sigwaitinfo(...) -[[gnu::weak]] int sys_sigtimedwait(const sigset_t *__restrict set, siginfo_t *__restrict info, const struct timespec *__restrict timeout, int *out_signal); +[[gnu::weak]] int sys_sigtimedwait( + const sigset_t *__restrict set, + siginfo_t *__restrict info, + const struct timespec *__restrict timeout, + int *out_signal +); [[gnu::weak]] int sys_kill(int, int); -[[gnu::weak]] int sys_accept(int fd, int *newfd, struct sockaddr *addr_ptr, socklen_t *addr_length, int flags); +[[gnu::weak]] int +sys_accept(int fd, int *newfd, struct sockaddr *addr_ptr, socklen_t *addr_length, int flags); [[gnu::weak]] int sys_bind(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length); [[gnu::weak]] int sys_connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length); -[[gnu::weak]] int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, - socklen_t *actual_length); -[[gnu::weak]] int sys_peername(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, - socklen_t *actual_length); +[[gnu::weak]] int sys_sockname( + int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, socklen_t *actual_length +); +[[gnu::weak]] int sys_peername( + int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, socklen_t *actual_length +); [[gnu::weak]] int sys_gethostname(char *buffer, size_t bufsize); [[gnu::weak]] int sys_sethostname(const char *buffer, size_t bufsize); [[gnu::weak]] int sys_mkfifoat(int dirfd, const char *path, mode_t mode); @@ -187,7 +220,8 @@ int sys_vm_unmap(void *pointer, size_t size); [[gnu::weak]] int sys_before_cancellable_syscall(ucontext_t *uctx); [[gnu::weak]] int sys_tgkill(int tgid, int tid, int sig); -[[gnu::weak]] int sys_fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags); +[[gnu::weak]] int +sys_fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags); [[gnu::weak]] int sys_sigaltstack(const stack_t *ss, stack_t *oss); [[gnu::weak]] int sys_sigsuspend(const sigset_t *set); [[gnu::weak]] int sys_sigpending(sigset_t *set); @@ -197,9 +231,13 @@ int sys_vm_unmap(void *pointer, size_t size); [[gnu::weak]] int sys_msync(void *addr, size_t length, int flags); [[gnu::weak]] int sys_getitimer(int which, struct itimerval *curr_value); -[[gnu::weak]] int sys_setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value); -[[gnu::weak]] int sys_timer_create(clockid_t clk, struct sigevent *__restrict evp, timer_t *__restrict res); -[[gnu::weak]] int sys_timer_settime(timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old); +[[gnu::weak]] int +sys_setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value); +[[gnu::weak]] int +sys_timer_create(clockid_t clk, struct sigevent *__restrict evp, timer_t *__restrict res); +[[gnu::weak]] int sys_timer_settime( + timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old +); [[gnu::weak]] int sys_timer_delete(timer_t t); [[gnu::weak]] int sys_times(struct tms *tms, clock_t *out); [[gnu::weak]] int sys_uname(struct utsname *buf); @@ -236,6 +274,6 @@ int sys_vm_unmap(void *pointer, size_t size); [[gnu::weak]] int sys_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options); -} //namespace mlibc +} // namespace mlibc #endif // MLIBC_POSIX_SYSDEPS diff --git a/options/posix/include/mlibc/resolv_conf.hpp b/options/posix/include/mlibc/resolv_conf.hpp index 2a349c7825..67338f3c40 100644 --- a/options/posix/include/mlibc/resolv_conf.hpp +++ b/options/posix/include/mlibc/resolv_conf.hpp @@ -1,15 +1,14 @@ #ifndef _MLIBC_RESOLV_CONF #define _MLIBC_RESOLV_CONF -#include #include +#include #include namespace mlibc { struct nameserver_data { - nameserver_data() - : name(getAllocator()) {} + nameserver_data() : name(getAllocator()) {} frg::string name; // for in the future we can also store options here }; diff --git a/options/posix/include/mlibc/services.hpp b/options/posix/include/mlibc/services.hpp index 10dec472da..cba3b17c1b 100644 --- a/options/posix/include/mlibc/services.hpp +++ b/options/posix/include/mlibc/services.hpp @@ -2,8 +2,8 @@ #define _MLIBC_SERVICES #include -#include #include +#include #include namespace mlibc { @@ -12,9 +12,7 @@ namespace mlibc { #define SERV_MAX 2 struct service_buf { - service_buf() - : name(getAllocator()), aliases(getAllocator()) - { } + service_buf() : name(getAllocator()), aliases(getAllocator()) {} int port, protocol, socktype; frg::string name; frg::vector, MemoryAllocator> aliases; @@ -22,12 +20,10 @@ struct service_buf { using service_result = frg::small_vector; -int lookup_serv_by_name(service_result &buf, const char *name, int proto, - int socktype, int flags); +int lookup_serv_by_name(service_result &buf, const char *name, int proto, int socktype, int flags); int lookup_serv_by_port(service_result &buf, int proto, int port); - } // namespace mlibc #endif // _MLIBC_SERVICES diff --git a/options/posix/include/mqueue.h b/options/posix/include/mqueue.h index cbee138e5c..120561f5d0 100644 --- a/options/posix/include/mqueue.h +++ b/options/posix/include/mqueue.h @@ -12,7 +12,11 @@ typedef int mqd_t; #ifndef __MLIBC_ABI_ONLY int mq_getattr(mqd_t __mqdes, struct mq_attr *__attr); -int mq_setattr(mqd_t __mqdes, const struct mq_attr *__restrict__ __newattr, struct mq_attr *__restrict__ __oldattr); +int mq_setattr( + mqd_t __mqdes, + const struct mq_attr *__restrict__ __newattr, + struct mq_attr *__restrict__ __oldattr +); int mq_unlink(const char *__name); mqd_t mq_open(const char *__name, int __flags, ...); @@ -23,4 +27,3 @@ mqd_t mq_open(const char *__name, int __flags, ...); #endif #endif /* _MQUEUE_H */ - diff --git a/options/posix/include/net/if.h b/options/posix/include/net/if.h index db74c35b0d..023fe7713c 100644 --- a/options/posix/include/net/if.h +++ b/options/posix/include/net/if.h @@ -48,22 +48,22 @@ struct ifreq { } ifr_ifru; }; -#define ifr_name ifr_ifrn.ifrn_name -#define ifr_hwaddr ifr_ifru.ifru_hwaddr -#define ifr_addr ifr_ifru.ifru_addr -#define ifr_dstaddr ifr_ifru.ifru_dstaddr -#define ifr_broadaddr ifr_ifru.ifru_broadaddr -#define ifr_netmask ifr_ifru.ifru_netmask -#define ifr_flags ifr_ifru.ifru_flags -#define ifr_metric ifr_ifru.ifru_ivalue -#define ifr_mtu ifr_ifru.ifru_mtu -#define ifr_map ifr_ifru.ifru_map -#define ifr_slave ifr_ifru.ifru_slave -#define ifr_data ifr_ifru.ifru_data -#define ifr_ifindex ifr_ifru.ifru_ivalue -#define ifr_bandwidth ifr_ifru.ifru_ivalue -#define ifr_qlen ifr_ifru.ifru_ivalue -#define ifr_newname ifr_ifru.ifru_newname +#define ifr_name ifr_ifrn.ifrn_name +#define ifr_hwaddr ifr_ifru.ifru_hwaddr +#define ifr_addr ifr_ifru.ifru_addr +#define ifr_dstaddr ifr_ifru.ifru_dstaddr +#define ifr_broadaddr ifr_ifru.ifru_broadaddr +#define ifr_netmask ifr_ifru.ifru_netmask +#define ifr_flags ifr_ifru.ifru_flags +#define ifr_metric ifr_ifru.ifru_ivalue +#define ifr_mtu ifr_ifru.ifru_mtu +#define ifr_map ifr_ifru.ifru_map +#define ifr_slave ifr_ifru.ifru_slave +#define ifr_data ifr_ifru.ifru_data +#define ifr_ifindex ifr_ifru.ifru_ivalue +#define ifr_bandwidth ifr_ifru.ifru_ivalue +#define ifr_qlen ifr_ifru.ifru_ivalue +#define ifr_newname ifr_ifru.ifru_newname struct ifconf { int ifc_len; @@ -106,13 +106,12 @@ unsigned int if_nametoindex(const char *__name); #define IFF_LOWER_UP 0x10000 #define IFF_DORMANT 0x20000 #define IFF_ECHO 0x40000 -#define IFF_VOLATILE (IFF_LOOPBACK|IFF_POINTOPOINT|IFF_BROADCAST| \ - IFF_ECHO|IFF_MASTER|IFF_SLAVE|IFF_RUNNING|IFF_LOWER_UP|IFF_DORMANT) +#define IFF_VOLATILE \ + (IFF_LOOPBACK | IFF_POINTOPOINT | IFF_BROADCAST | IFF_ECHO | IFF_MASTER | IFF_SLAVE | \ + IFF_RUNNING | IFF_LOWER_UP | IFF_DORMANT) #ifdef __cplusplus } #endif #endif /* _NET_IF_H */ - - diff --git a/options/posix/include/net/if_arp.h b/options/posix/include/net/if_arp.h index 8701137026..d693e49286 100644 --- a/options/posix/include/net/if_arp.h +++ b/options/posix/include/net/if_arp.h @@ -1,9 +1,9 @@ #ifndef _NET_IF_ARP_H #define _NET_IF_ARP_H -#include -#include #include +#include +#include #define MAX_ADDR_LEN 7 @@ -102,4 +102,3 @@ struct arpreq { }; #endif /* _NET_IF_ARP_H */ - diff --git a/options/posix/include/netdb.h b/options/posix/include/netdb.h index 9f187fa735..571b9e4b99 100644 --- a/options/posix/include/netdb.h +++ b/options/posix/include/netdb.h @@ -1,11 +1,11 @@ #ifndef _NETDB_H #define _NETDB_H -#include -#include -#include -#include #include +#include +#include +#include +#include #define AI_PASSIVE 0x01 #define AI_CANONNAME 0x02 @@ -42,10 +42,10 @@ #define EAI_ADDRFAMILY 12 #define HOST_NOT_FOUND 1 -#define TRY_AGAIN 2 -#define NO_RECOVERY 3 -#define NO_DATA 4 -#define NO_ADDRESS NO_DATA +#define TRY_AGAIN 2 +#define NO_RECOVERY 3 +#define NO_DATA 4 +#define NO_ADDRESS NO_DATA #define IPPORT_RESERVED 1024 @@ -111,18 +111,43 @@ void endprotoent(void); void endservent(void); void freeaddrinfo(struct addrinfo *__info); const char *gai_strerror(int __errnum); -int getaddrinfo(const char *__restrict __node, const char *__restrict __service, - const struct addrinfo *__restrict __hints, struct addrinfo **__restrict __res); +int getaddrinfo( + const char *__restrict __node, + const char *__restrict __service, + const struct addrinfo *__restrict __hints, + struct addrinfo **__restrict __res +); struct hostent *gethostent(void); struct hostent *gethostbyname(const char *__name); struct hostent *gethostbyname2(const char *__name, int __flags); struct hostent *gethostbyaddr(const void *__addr, socklen_t __len, int __type); -int gethostbyaddr_r(const void *__restrict __addr, socklen_t __len, int __type, struct hostent *__restrict __ret, - char *__restrict __buf, size_t __buflen, struct hostent **__restrict __res, int *__restrict __h_errnump); -int gethostbyname_r(const char *__restrict __name, struct hostent *__restrict __ret, char *__restrict __buf, size_t __buflen, - struct hostent **__restrict __res, int *__restrict __h_errnump); -int getnameinfo(const struct sockaddr *__restrict __addr, socklen_t __addrlen, - char *__restrict __host, socklen_t __hostlen, char *__restrict __serv, socklen_t __servlen, int __flags); +int gethostbyaddr_r( + const void *__restrict __addr, + socklen_t __len, + int __type, + struct hostent *__restrict __ret, + char *__restrict __buf, + size_t __buflen, + struct hostent **__restrict __res, + int *__restrict __h_errnump +); +int gethostbyname_r( + const char *__restrict __name, + struct hostent *__restrict __ret, + char *__restrict __buf, + size_t __buflen, + struct hostent **__restrict __res, + int *__restrict __h_errnump +); +int getnameinfo( + const struct sockaddr *__restrict __addr, + socklen_t __addrlen, + char *__restrict __host, + socklen_t __hostlen, + char *__restrict __serv, + socklen_t __servlen, + int __flags +); struct netent *getnetbyaddr(uint32_t __net, int __type); struct netent *getnetbyname(const char *__name); struct netent *getnetent(void); diff --git a/options/posix/include/netinet/icmp6.h b/options/posix/include/netinet/icmp6.h index 91ae368b0a..73d047714f 100644 --- a/options/posix/include/netinet/icmp6.h +++ b/options/posix/include/netinet/icmp6.h @@ -5,9 +5,9 @@ extern "C" { #endif -#include #include #include +#include #if __MLIBC_GLIBC_OPTION #include @@ -47,23 +47,21 @@ struct icmp6_hdr { #define icmp6_seq icmp6_data16[1] #define icmp6_maxdelay icmp6_data16[0] -#define ICMP6_FILTER_WILLPASS(type, filterp) \ +#define ICMP6_FILTER_WILLPASS(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) & (1U << ((type) & 31))) == 0) -#define ICMP6_FILTER_WILLBLOCK(type, filterp) \ +#define ICMP6_FILTER_WILLBLOCK(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) & (1U << ((type) & 31))) != 0) -#define ICMP6_FILTER_SETPASS(type, filterp) \ +#define ICMP6_FILTER_SETPASS(type, filterp) \ ((((filterp)->icmp6_filt[(type) >> 5]) &= ~(1U << ((type) & 31)))) -#define ICMP6_FILTER_SETBLOCK(type, filterp) \ - ((((filterp)->icmp6_filt[(type) >> 5]) |= (1U << ((type) & 31)))) +#define ICMP6_FILTER_SETBLOCK(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> 5]) |= (1U << ((type) & 31)))) -#define ICMP6_FILTER_SETPASSALL(filterp) \ - memset (filterp, 0, sizeof (struct icmp6_filter)); +#define ICMP6_FILTER_SETPASSALL(filterp) memset(filterp, 0, sizeof(struct icmp6_filter)); -#define ICMP6_FILTER_SETBLOCKALL(filterp) \ - memset (filterp, 0xFF, sizeof (struct icmp6_filter)); +#define ICMP6_FILTER_SETBLOCKALL(filterp) memset(filterp, 0xFF, sizeof(struct icmp6_filter)); #define ND_ROUTER_SOLICIT 133 #define ND_ROUTER_ADVERT 134 @@ -161,4 +159,3 @@ struct nd_redirect { #endif #endif /* _NETINET_ICMP6_H */ - diff --git a/options/posix/include/netinet/if_ether.h b/options/posix/include/netinet/if_ether.h index e79abc3d62..875820adeb 100644 --- a/options/posix/include/netinet/if_ether.h +++ b/options/posix/include/netinet/if_ether.h @@ -105,6 +105,6 @@ struct ether_arp { #define arp_pro ea_hdr.ar_pro #define arp_hln ea_hdr.ar_hln #define arp_pln ea_hdr.ar_pln -#define arp_op ea_hdr.ar_op +#define arp_op ea_hdr.ar_op #endif /*_NETINET_IF_ETHER_H */ diff --git a/options/posix/include/netinet/in.h b/options/posix/include/netinet/in.h index 5dee2bd513..4825deab71 100644 --- a/options/posix/include/netinet/in.h +++ b/options/posix/include/netinet/in.h @@ -2,15 +2,15 @@ #ifndef _NETINET_IN_H #define _NETINET_IN_H -#include -#include /* struct sockaddr */ -#include #include +#include #include #include +#include +#include /* struct sockaddr */ #if __MLIBC_GLIBC_OPTION - #include +#include #endif /*__MLIBC_GLIBC_OPTION */ #ifdef __cplusplus @@ -29,66 +29,52 @@ uint16_t ntohs(uint16_t __x); #endif /* !__MLIBC_ABI_ONLY */ -#define IN6_IS_ADDR_UNSPECIFIED(a) ({ \ - uint32_t *_a = (uint32_t *)(((struct in6_addr *) a)->s6_addr); \ - !_a[0] && \ - !_a[1] && \ - !_a[2] && \ - !_a[3]; \ -}) -#define IN6_IS_ADDR_LOOPBACK(a) ({ \ - uint32_t *_a = (uint32_t *)(((struct in6_addr *) a)->s6_addr); \ - !_a[0] && \ - !_a[1] && \ - !_a[2] && \ - _a[3] == htonl(0x0001); \ -}) -#define IN6_IS_ADDR_MULTICAST(a) (((const uint8_t *) (a))[0] == 0xff) -#define IN6_IS_ADDR_LINKLOCAL(a) ({ \ - uint32_t *_a = (uint32_t *)(((struct in6_addr *) a)->s6_addr); \ - (_a[0] & htonl(0xffc00000)) == htonl(0xfe800000); \ -}) -#define IN6_IS_ADDR_SITELOCAL(a) ({ \ - uint32_t *_a = (uint32_t *)(((struct in6_addr *) a)->s6_addr); \ - (_a[0] & htonl(0xffc00000)) == htonl(0xfec00000); \ -}) -#define IN6_IS_ADDR_V4MAPPED(a) ({ \ - uint32_t *_a = (uint32_t *)(((struct in6_addr *) a)->s6_addr); \ - !_a[0] && \ - !_a[1] && \ - _a[2] == htonl(0xffff); \ -}) -#define __ARE_4_BYTE_EQUAL(a, b) \ - ((a)[0] == (b)[0] && (a)[1] == (b)[1] && (a)[2] == (b)[2] && \ - (a)[3] == (b)[3]) -#define IN6_ARE_ADDR_EQUAL(a, b) \ - __ARE_4_BYTE_EQUAL((const uint32_t *)(a), (const uint32_t *)(b)) - -#define IN6_IS_ADDR_V4COMPAT(a) ({ \ - uint32_t *_a = (uint32_t *)(((struct in6_addr *) a)->s6_addr); \ - uint8_t *_a8 = (uint8_t *)(((struct in6_addr *) a)->s6_addr); \ - !_a[0] && !_a[1] && !_a[2] && (_a8[15] > 1); \ -}) -#define IN6_IS_ADDR_MC_NODELOCAL(a) ({ \ - (IN6_IS_ADDR_MULTICAST(a) && \ - ((((const uint8_t *)(a))[1] & 0xf) == 0x1)); \ -}) -#define IN6_IS_ADDR_MC_LINKLOCAL(a) ({ \ - (IN6_IS_ADDR_MULTICAST(a) && \ - ((((const uint8_t *)(a))[1] & 0xf) == 0x2)); \ -}) -#define IN6_IS_ADDR_MC_SITELOCAL(a) ({ \ - (IN6_IS_ADDR_MULTICAST(a) && \ - ((((const uint8_t *)(a))[1] & 0xf) == 0x5)); \ -}) -#define IN6_IS_ADDR_MC_ORGLOCAL(a) ({ \ - (IN6_IS_ADDR_MULTICAST(a) && \ - ((((const uint8_t *)(a))[1] & 0xf) == 0x8)); \ -}) -#define IN6_IS_ADDR_MC_GLOBAL(a) ({ \ - (IN6_IS_ADDR_MULTICAST(a) && \ - ((((const uint8_t *)(a))[1] & 0xf) == 0xe)); \ -}) +#define IN6_IS_ADDR_UNSPECIFIED(a) \ + ({ \ + uint32_t *_a = (uint32_t *)(((struct in6_addr *)a)->s6_addr); \ + !_a[0] && !_a[1] && !_a[2] && !_a[3]; \ + }) +#define IN6_IS_ADDR_LOOPBACK(a) \ + ({ \ + uint32_t *_a = (uint32_t *)(((struct in6_addr *)a)->s6_addr); \ + !_a[0] && !_a[1] && !_a[2] && _a[3] == htonl(0x0001); \ + }) +#define IN6_IS_ADDR_MULTICAST(a) (((const uint8_t *)(a))[0] == 0xff) +#define IN6_IS_ADDR_LINKLOCAL(a) \ + ({ \ + uint32_t *_a = (uint32_t *)(((struct in6_addr *)a)->s6_addr); \ + (_a[0] & htonl(0xffc00000)) == htonl(0xfe800000); \ + }) +#define IN6_IS_ADDR_SITELOCAL(a) \ + ({ \ + uint32_t *_a = (uint32_t *)(((struct in6_addr *)a)->s6_addr); \ + (_a[0] & htonl(0xffc00000)) == htonl(0xfec00000); \ + }) +#define IN6_IS_ADDR_V4MAPPED(a) \ + ({ \ + uint32_t *_a = (uint32_t *)(((struct in6_addr *)a)->s6_addr); \ + !_a[0] && !_a[1] && _a[2] == htonl(0xffff); \ + }) +#define __ARE_4_BYTE_EQUAL(a, b) \ + ((a)[0] == (b)[0] && (a)[1] == (b)[1] && (a)[2] == (b)[2] && (a)[3] == (b)[3]) +#define IN6_ARE_ADDR_EQUAL(a, b) __ARE_4_BYTE_EQUAL((const uint32_t *)(a), (const uint32_t *)(b)) + +#define IN6_IS_ADDR_V4COMPAT(a) \ + ({ \ + uint32_t *_a = (uint32_t *)(((struct in6_addr *)a)->s6_addr); \ + uint8_t *_a8 = (uint8_t *)(((struct in6_addr *)a)->s6_addr); \ + !_a[0] && !_a[1] && !_a[2] && (_a8[15] > 1); \ + }) +#define IN6_IS_ADDR_MC_NODELOCAL(a) \ + ({ (IN6_IS_ADDR_MULTICAST(a) && ((((const uint8_t *)(a))[1] & 0xf) == 0x1)); }) +#define IN6_IS_ADDR_MC_LINKLOCAL(a) \ + ({ (IN6_IS_ADDR_MULTICAST(a) && ((((const uint8_t *)(a))[1] & 0xf) == 0x2)); }) +#define IN6_IS_ADDR_MC_SITELOCAL(a) \ + ({ (IN6_IS_ADDR_MULTICAST(a) && ((((const uint8_t *)(a))[1] & 0xf) == 0x5)); }) +#define IN6_IS_ADDR_MC_ORGLOCAL(a) \ + ({ (IN6_IS_ADDR_MULTICAST(a) && ((((const uint8_t *)(a))[1] & 0xf) == 0x8)); }) +#define IN6_IS_ADDR_MC_GLOBAL(a) \ + ({ (IN6_IS_ADDR_MULTICAST(a) && ((((const uint8_t *)(a))[1] & 0xf) == 0xe)); }) #define IN_CLASSA(a) ((((in_addr_t)(a)) & 0x80000000) == 0) #define IN_CLASSA_NET 0xff000000 @@ -119,4 +105,3 @@ uint16_t ntohs(uint16_t __x); #endif #endif /* _NETINET_IN_H */ - diff --git a/options/posix/include/netinet/ip.h b/options/posix/include/netinet/ip.h index fcb11f6c6d..59bb84044f 100644 --- a/options/posix/include/netinet/ip.h +++ b/options/posix/include/netinet/ip.h @@ -6,8 +6,8 @@ extern "C" { #endif -#include #include +#include #define IPTOS_TOS_MASK 0x1E #define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK) @@ -24,12 +24,12 @@ extern "C" { struct ip { #if __BYTE_ORDER == __LITTLE_ENDIAN - unsigned int ip_hl:4; - unsigned int ip_v:4; + unsigned int ip_hl : 4; + unsigned int ip_v : 4; #endif #if __BYTE_ORDER == __BIG_ENDIAN - unsigned int ip_v:4; - unsigned int ip_hl:4; + unsigned int ip_v : 4; + unsigned int ip_hl : 4; #endif uint8_t ip_tos; unsigned short ip_len; @@ -49,13 +49,13 @@ struct ip { struct iphdr { #if __BYTE_ORDER == __LITTLE_ENDIAN - unsigned int ihl:4; - unsigned int version:4; + unsigned int ihl : 4; + unsigned int version : 4; #elif __BYTE_ORDER == __BIG_ENDIAN - unsigned int version:4; - unsigned int ihl:4; + unsigned int version : 4; + unsigned int ihl : 4; #else -# error "Please fix " +#error "Please fix " #endif uint8_t tos; uint16_t tot_len; @@ -73,4 +73,3 @@ struct iphdr { #endif #endif /* _NETINET_IP_H */ - diff --git a/options/posix/include/netinet/ip6.h b/options/posix/include/netinet/ip6.h index e097acae38..2767a629b1 100644 --- a/options/posix/include/netinet/ip6.h +++ b/options/posix/include/netinet/ip6.h @@ -12,8 +12,8 @@ struct ip6_hdr { struct ip6_hdrctl { uint32_t ip6_un1_flow; uint16_t ip6_un1_plen; - uint8_t ip6_un1_nxt; - uint8_t ip6_un1_hlim; + uint8_t ip6_un1_nxt; + uint8_t ip6_un1_hlim; } ip6_un1; uint8_t ip6_un2_vfc; } ip6_ctlun; diff --git a/options/posix/include/netinet/ip_icmp.h b/options/posix/include/netinet/ip_icmp.h index efffda1e9c..620bcc7936 100644 --- a/options/posix/include/netinet/ip_icmp.h +++ b/options/posix/include/netinet/ip_icmp.h @@ -31,12 +31,12 @@ struct icmp { uint16_t icd_seq; } ih_idseq; uint32_t ih_void; - + struct ih_pmtu { uint16_t ipm_void; uint16_t ipm_nextmtu; } ih_pmtu; - + struct ih_rtradv { uint8_t irt_num_addrs; uint8_t irt_wpa; @@ -58,24 +58,24 @@ struct icmp { } icmp_dun; }; -#define icmp_pptr icmp_hun.ih_pptr -#define icmp_gwaddr icmp_hun.ih_gwaddr -#define icmp_id icmp_hun.ih_idseq.icd_id -#define icmp_seq icmp_hun.ih_idseq.icd_seq -#define icmp_void icmp_hun.ih_void -#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void -#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu -#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs -#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa -#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime +#define icmp_pptr icmp_hun.ih_pptr +#define icmp_gwaddr icmp_hun.ih_gwaddr +#define icmp_id icmp_hun.ih_idseq.icd_id +#define icmp_seq icmp_hun.ih_idseq.icd_seq +#define icmp_void icmp_hun.ih_void +#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void +#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu +#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs +#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa +#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime -#define icmp_otime icmp_dun.id_ts.its_otime -#define icmp_rtime icmp_dun.id_ts.its_rtime -#define icmp_ttime icmp_dun.id_ts.its_ttime -#define icmp_ip icmp_dun.id_ip.idi_ip -#define icmp_radv icmp_dun.id_radv -#define icmp_mask icmp_dun.id_mask -#define icmp_data icmp_dun.id_data +#define icmp_otime icmp_dun.id_ts.its_otime +#define icmp_rtime icmp_dun.id_ts.its_rtime +#define icmp_ttime icmp_dun.id_ts.its_ttime +#define icmp_ip icmp_dun.id_ip.idi_ip +#define icmp_radv icmp_dun.id_radv +#define icmp_mask icmp_dun.id_mask +#define icmp_data icmp_dun.id_data #ifdef __cplusplus } diff --git a/options/posix/include/netinet/udp.h b/options/posix/include/netinet/udp.h index 1563f1c52a..34d58cc021 100644 --- a/options/posix/include/netinet/udp.h +++ b/options/posix/include/netinet/udp.h @@ -8,20 +8,20 @@ extern "C" { #endif __extension__ struct udphdr { - __extension__ union { - struct { - uint16_t uh_sport; - uint16_t uh_dport; - uint16_t uh_ulen; - uint16_t uh_sum; - }; - struct { - uint16_t source; - uint16_t dest; - uint16_t len; - uint16_t check; - }; - }; + __extension__ union { + struct { + uint16_t uh_sport; + uint16_t uh_dport; + uint16_t uh_ulen; + uint16_t uh_sum; + }; + struct { + uint16_t source; + uint16_t dest; + uint16_t len; + uint16_t check; + }; + }; }; #ifdef __cplusplus diff --git a/options/posix/include/nl_types.h b/options/posix/include/nl_types.h index 8878629551..15f37066bd 100644 --- a/options/posix/include/nl_types.h +++ b/options/posix/include/nl_types.h @@ -1,6 +1,4 @@ #ifndef NL_TYPES_H #define NL_TYPES_H - - #endif /* NL_TYPES_H */ diff --git a/options/posix/include/pthread.h b/options/posix/include/pthread.h index 080eb6abc6..64975e5717 100644 --- a/options/posix/include/pthread.h +++ b/options/posix/include/pthread.h @@ -5,8 +5,8 @@ #include #include /* TODO: pthread is not required to define size_t. */ -#include #include +#include #include #include @@ -64,7 +64,7 @@ extern "C" { #define PTHREAD_MUTEX_INITIALIZER {0, 0, 0, 0} #define PTHREAD_RWLOCK_INITIALIZER {0, 0, 0} -#define PTHREAD_CANCELED ((void*) -1) +#define PTHREAD_CANCELED ((void *)-1) #define PTHREAD_BARRIER_SERIAL_THREAD -1 @@ -96,7 +96,7 @@ typedef struct __mlibc_condattr pthread_condattr_t; typedef struct __mlibc_cond pthread_cond_t; -struct __mlibc_barrierattr_struct { +struct __mlibc_barrierattr_struct { int __mlibc_pshared; }; typedef struct __mlibc_barrierattr_struct pthread_barrierattr_t; @@ -111,7 +111,7 @@ struct __mlibc_barrier { typedef struct __mlibc_barrier pthread_barrier_t; struct __mlibc_fair_rwlock { - unsigned int __mlibc_m; /* Mutex. */ + unsigned int __mlibc_m; /* Mutex. */ unsigned int __mlibc_rc; /* Reader count (not reference count). */ unsigned int __mlibc_flags; }; @@ -135,7 +135,8 @@ int pthread_attr_destroy(pthread_attr_t *__attr); int pthread_attr_getdetachstate(const pthread_attr_t *__attr, int *__state); int pthread_attr_setdetachstate(pthread_attr_t *__attr, int __state); -int pthread_attr_getstacksize(const pthread_attr_t *__restrict __attr, size_t *__restrict __stacksize); +int +pthread_attr_getstacksize(const pthread_attr_t *__restrict __attr, size_t *__restrict __stacksize); int pthread_attr_setstacksize(pthread_attr_t *__attr, size_t __stacksize); int pthread_attr_getstackaddr(const pthread_attr_t *__attr, void **__stackaddr); @@ -144,27 +145,41 @@ int pthread_attr_setstackaddr(pthread_attr_t *__attr, void *__stackaddr); int pthread_attr_getstack(const pthread_attr_t *__attr, void **__stackaddr, size_t *__stacksize); int pthread_attr_setstack(pthread_attr_t *__attr, void *__stackaddr, size_t __stacksize); -int pthread_attr_getguardsize(const pthread_attr_t *__restrict __attr, size_t *__restrict __guardsize); +int +pthread_attr_getguardsize(const pthread_attr_t *__restrict __attr, size_t *__restrict __guardsize); int pthread_attr_setguardsize(pthread_attr_t *__attr, size_t __guardsize); int pthread_attr_getscope(const pthread_attr_t *__attr, int *__scope); int pthread_attr_setscope(pthread_attr_t *__attr, int __scope); -int pthread_attr_getschedparam(const pthread_attr_t *__restrict __attr, struct sched_param *__restrict __param); -int pthread_attr_setschedparam(pthread_attr_t *__restrict __attr, const struct sched_param *__restrict __param); +int pthread_attr_getschedparam( + const pthread_attr_t *__restrict __attr, struct sched_param *__restrict __param +); +int pthread_attr_setschedparam( + pthread_attr_t *__restrict __attr, const struct sched_param *__restrict __param +); -int pthread_attr_getschedpolicy(const pthread_attr_t *__restrict __attr, int *__restrict __schedpolicy); +int +pthread_attr_getschedpolicy(const pthread_attr_t *__restrict __attr, int *__restrict __schedpolicy); int pthread_attr_setschedpolicy(pthread_attr_t *__restrict __attr, int __schedpolicy); -int pthread_attr_getinheritsched(const pthread_attr_t *__restrict __attr, int *__restrict __inheritsched); +int pthread_attr_getinheritsched( + const pthread_attr_t *__restrict __attr, int *__restrict __inheritsched +); int pthread_attr_setinheritsched(pthread_attr_t *__restrict __attr, int __inheritsched); #if __MLIBC_LINUX_OPTION -int pthread_attr_getaffinity_np(const pthread_attr_t *__restrict __attr, size_t __cpusetsize, cpu_set_t *__restrict __cpuset); -int pthread_attr_setaffinity_np(pthread_attr_t *__restrict __attr, size_t __cpusetsize, const cpu_set_t *__restrict __cpuset); - -int pthread_attr_getsigmask_np(const pthread_attr_t *__restrict __attr, sigset_t *__restrict __sigmask); -int pthread_attr_setsigmask_np(pthread_attr_t *__restrict __attr, const sigset_t *__restrict __sigmask); +int pthread_attr_getaffinity_np( + const pthread_attr_t *__restrict __attr, size_t __cpusetsize, cpu_set_t *__restrict __cpuset +); +int pthread_attr_setaffinity_np( + pthread_attr_t *__restrict __attr, size_t __cpusetsize, const cpu_set_t *__restrict __cpuset +); + +int +pthread_attr_getsigmask_np(const pthread_attr_t *__restrict __attr, sigset_t *__restrict __sigmask); +int +pthread_attr_setsigmask_np(pthread_attr_t *__restrict __attr, const sigset_t *__restrict __sigmask); int pthread_getattr_np(pthread_t __thrd, pthread_attr_t *__attr); @@ -173,16 +188,20 @@ int pthread_setaffinity_np(pthread_t __thrd, size_t __cpusetsize, const cpu_set_ #endif /* __MLIBC_LINUX_OPTION */ /* pthread functions. */ -int pthread_create(pthread_t *__restrict __thrd, const pthread_attr_t *__restrict __attr, - void *(*__fn) (void *__arg), void *__restrict __arg); +int pthread_create( + pthread_t *__restrict __thrd, + const pthread_attr_t *__restrict __attr, + void *(*__fn)(void *__arg), + void *__restrict __arg +); pthread_t pthread_self(void); int pthread_equal(pthread_t __a, pthread_t __b); -__attribute__ ((__noreturn__)) void pthread_exit(void *__arg); +__attribute__((__noreturn__)) void pthread_exit(void *__arg); int pthread_join(pthread_t __thrd, void **__res); int pthread_detach(pthread_t __thrd); -void pthread_cleanup_push(void (*__fn) (void *__arg), void *__arg); +void pthread_cleanup_push(void (*__fn)(void *__arg), void *__arg); void pthread_cleanup_pop(int __execute); int pthread_setname_np(pthread_t __thrd, const char *__name); @@ -201,13 +220,13 @@ int pthread_setcancelstate(int __state, int *__oldstate); void pthread_testcancel(void); int pthread_cancel(pthread_t __thrd); -int pthread_atfork(void (*__prepare) (void), void (*__parent) (void), void (*__child) (void)); +int pthread_atfork(void (*__prepare)(void), void (*__parent)(void), void (*__child)(void)); /* ---------------------------------------------------------------------------- */ /* pthread_key functions. */ /* ---------------------------------------------------------------------------- */ -int pthread_key_create(pthread_key_t *__key, void (*__destructor) (void *__data)); +int pthread_key_create(pthread_key_t *__key, void (*__destructor)(void *__data)); int pthread_key_delete(pthread_key_t __key); void *pthread_getspecific(pthread_key_t __key); @@ -217,7 +236,7 @@ int pthread_setspecific(pthread_key_t __key, const void *__data); /* pthread_once functions. */ /* ---------------------------------------------------------------------------- */ -int pthread_once(pthread_once_t *__once, void (*__fn) (void)); +int pthread_once(pthread_once_t *__once, void (*__fn)(void)); /* ---------------------------------------------------------------------------- */ /* pthread_mutexattr and pthread_mutex functions. */ @@ -230,26 +249,31 @@ int pthread_mutexattr_destroy(pthread_mutexattr_t *__attr); int pthread_mutexattr_gettype(const pthread_mutexattr_t *__restrict __attr, int *__restrict __type); int pthread_mutexattr_settype(pthread_mutexattr_t *__attr, int __type); -int pthread_mutexattr_getrobust(const pthread_mutexattr_t *__restrict __attr, int *__restrict __robust); +int +pthread_mutexattr_getrobust(const pthread_mutexattr_t *__restrict __attr, int *__restrict __robust); int pthread_mutexattr_setrobust(pthread_mutexattr_t *__attr, int __robust); int pthread_mutexattr_getpshared(const pthread_mutexattr_t *__attr, int *__pshared); int pthread_mutexattr_setpshared(pthread_mutexattr_t *__attr, int __pshared); -int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *__restrict __attr, int *__restrict __protocol); +int pthread_mutexattr_getprotocol( + const pthread_mutexattr_t *__restrict __attr, int *__restrict __protocol +); int pthread_mutexattr_setprotocol(pthread_mutexattr_t *__attr, int __protocol); int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *__attr, int *__prioceiling); int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *__attr, int __prioceiling); /* pthread_mutex functions */ -int pthread_mutex_init(pthread_mutex_t *__restrict __mtx, const pthread_mutexattr_t *__restrict __attr); +int +pthread_mutex_init(pthread_mutex_t *__restrict __mtx, const pthread_mutexattr_t *__restrict __attr); int pthread_mutex_destroy(pthread_mutex_t *__mtx); int pthread_mutex_lock(pthread_mutex_t *__mtx); int pthread_mutex_trylock(pthread_mutex_t *__mtx); -int pthread_mutex_timedlock(pthread_mutex_t *__restrict __mtx, - const struct timespec *__restrict __abs_timeout); +int pthread_mutex_timedlock( + pthread_mutex_t *__restrict __mtx, const struct timespec *__restrict __abs_timeout +); int pthread_mutex_unlock(pthread_mutex_t *__mtx); int pthread_mutex_consistent(pthread_mutex_t *__mtx); @@ -261,18 +285,25 @@ int pthread_mutex_consistent(pthread_mutex_t *__mtx); int pthread_condattr_init(pthread_condattr_t *__attr); int pthread_condattr_destroy(pthread_condattr_t *__attr); -int pthread_condattr_getclock(const pthread_condattr_t *__restrict __attr, clockid_t *__restrict __clockid); +int pthread_condattr_getclock( + const pthread_condattr_t *__restrict __attr, clockid_t *__restrict __clockid +); int pthread_condattr_setclock(pthread_condattr_t *__attr, clockid_t __clockid); -int pthread_condattr_getpshared(const pthread_condattr_t *__restrict __attr, int *__restrict __pshared); +int +pthread_condattr_getpshared(const pthread_condattr_t *__restrict __attr, int *__restrict __pshared); int pthread_condattr_setpshared(pthread_condattr_t *__attr, int __pshared); -int pthread_cond_init(pthread_cond_t *__restrict __cond, const pthread_condattr_t *__restrict __attr); +int +pthread_cond_init(pthread_cond_t *__restrict __cond, const pthread_condattr_t *__restrict __attr); int pthread_cond_destroy(pthread_cond_t *__cond); int pthread_cond_wait(pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mtx); -int pthread_cond_timedwait(pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mtx, - const struct timespec *__restrict __abs_timeout); +int pthread_cond_timedwait( + pthread_cond_t *__restrict __cond, + pthread_mutex_t *__restrict __mtx, + const struct timespec *__restrict __abs_timeout +); int pthread_cond_signal(pthread_cond_t *__cond); int pthread_cond_broadcast(pthread_cond_t *__cond); @@ -283,11 +314,15 @@ int pthread_cond_broadcast(pthread_cond_t *__cond); int pthread_barrierattr_init(pthread_barrierattr_t *__attr); int pthread_barrierattr_destroy(pthread_barrierattr_t *__attr); int pthread_barrierattr_setpshared(pthread_barrierattr_t *__attr, int __pshared); -int pthread_barrierattr_getpshared(const pthread_barrierattr_t *__restrict __attr, - int *__restrict __pshared); - -int pthread_barrier_init(pthread_barrier_t *__restrict __barrier, const pthread_barrierattr_t *__restrict __attr, - unsigned int __count); +int pthread_barrierattr_getpshared( + const pthread_barrierattr_t *__restrict __attr, int *__restrict __pshared +); + +int pthread_barrier_init( + pthread_barrier_t *__restrict __barrier, + const pthread_barrierattr_t *__restrict __attr, + unsigned int __count +); int pthread_barrier_destroy(pthread_barrier_t *__barrier); int pthread_barrier_wait(pthread_barrier_t *__barrier); @@ -299,10 +334,13 @@ int pthread_barrier_wait(pthread_barrier_t *__barrier); int pthread_rwlockattr_init(pthread_rwlockattr_t *__attr); int pthread_rwlockattr_destroy(pthread_rwlockattr_t *__attr); int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *__attr, int __pshared); -int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *__restrict __attr, - int *__restrict __pshared); +int pthread_rwlockattr_getpshared( + const pthread_rwlockattr_t *__restrict __attr, int *__restrict __pshared +); -int pthread_rwlock_init(pthread_rwlock_t *__restrict __rwlock, const pthread_rwlockattr_t *__restrict __attr); +int pthread_rwlock_init( + pthread_rwlock_t *__restrict __rwlock, const pthread_rwlockattr_t *__restrict __attr +); int pthread_rwlock_destroy(pthread_rwlock_t *__rwlock); int pthread_rwlock_trywrlock(pthread_rwlock_t *__rwlock); int pthread_rwlock_wrlock(pthread_rwlock_t *__rwlock); @@ -319,4 +357,3 @@ int pthread_getcpuclockid(pthread_t __thrd, clockid_t *__clockid); #endif #endif /* _PTHREAD_H */ - diff --git a/options/posix/include/pwd.h b/options/posix/include/pwd.h index fd4f9c4bfd..f8965b5f16 100644 --- a/options/posix/include/pwd.h +++ b/options/posix/include/pwd.h @@ -2,8 +2,8 @@ #ifndef _PWD_H #define _PWD_H -#include #include +#include #include #include @@ -28,9 +28,12 @@ struct passwd { void endpwent(void); struct passwd *getpwent(void); struct passwd *getpwnam(const char *__name); -int getpwnam_r(const char *__name, struct passwd *__ret, char *__buf, size_t __buflen, struct passwd **__res); +int getpwnam_r( + const char *__name, struct passwd *__ret, char *__buf, size_t __buflen, struct passwd **__res +); struct passwd *getpwuid(uid_t __uid); -int getpwuid_r(uid_t __uid, struct passwd *__ret, char *__buf, size_t __buflen, struct passwd **__res); +int +getpwuid_r(uid_t __uid, struct passwd *__ret, char *__buf, size_t __buflen, struct passwd **__res); void setpwent(void); int putpwent(const struct passwd *__pwd, FILE *__f); struct passwd *fgetpwent(FILE *__f); @@ -42,4 +45,3 @@ struct passwd *fgetpwent(FILE *__f); #endif #endif /* _PWD_H */ - diff --git a/options/posix/include/regex.h b/options/posix/include/regex.h index 8a2c827ced..325d41e95e 100644 --- a/options/posix/include/regex.h +++ b/options/posix/include/regex.h @@ -53,9 +53,19 @@ typedef struct { #ifndef __MLIBC_ABI_ONLY int regcomp(regex_t *__restrict __regex, const char *__restrict __pattern, int __flags); -int regexec(const regex_t *__restrict __regex, const char *__restrict __string, size_t __nmatch, - regmatch_t *__restrict __pmatch, int __flags); -size_t regerror(int __errcode, const regex_t *__restrict __regex, char *__restrict __errbuf, size_t __errbuf_size); +int regexec( + const regex_t *__restrict __regex, + const char *__restrict __string, + size_t __nmatch, + regmatch_t *__restrict __pmatch, + int __flags +); +size_t regerror( + int __errcode, + const regex_t *__restrict __regex, + char *__restrict __errbuf, + size_t __errbuf_size +); void regfree(regex_t *__regex); #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/posix/include/sched.h b/options/posix/include/sched.h index 5d745dda29..64b88676ff 100644 --- a/options/posix/include/sched.h +++ b/options/posix/include/sched.h @@ -3,8 +3,8 @@ #define _SCHED_H #include -#include #include +#include #include /* MISSING: time_t, struct timespec */ @@ -16,8 +16,8 @@ extern "C" { #endif #if __MLIBC_LINUX_OPTION -#include #include +#include #endif #define SCHED_OTHER 0 @@ -46,4 +46,3 @@ int sched_getparam(pid_t __pid, struct sched_param *__param); #endif #endif /* _SCHED_H */ - diff --git a/options/posix/include/search.h b/options/posix/include/search.h index 39174b5255..a69ceaddbd 100644 --- a/options/posix/include/search.h +++ b/options/posix/include/search.h @@ -2,20 +2,15 @@ #ifndef _SEARCH_H #define _SEARCH_H -#include #include #include +#include #ifdef __cplusplus extern "C" { #endif -typedef enum { - preorder, - postorder, - endorder, - leaf -} VISIT; +typedef enum { preorder, postorder, endorder, leaf } VISIT; #if __MLIBC_GLIBC_OPTION && defined(_GNU_SOURCE) #include @@ -23,16 +18,27 @@ typedef enum { #ifndef __MLIBC_ABI_ONLY -void *tsearch(const void *__key, void **__root, int(*__compar)(const void *__a, const void *__b)); -void *tfind(const void *__key, void *const *__root, int (*__compar)(const void *__a, const void *__b)); -void *tdelete(const void *__key, void **__root, int(*__compar)(const void * __a, const void *__b)); -void twalk(const void *__key, void (*__action)(const void *__node, VISIT __which, int __depth)); +void *tsearch(const void *__key, void **__root, int (*__compar)(const void *__a, const void *__b)); +void * +tfind(const void *__key, void *const *__root, int (*__compar)(const void *__a, const void *__b)); +void *tdelete(const void *__key, void **__root, int (*__compar)(const void *__a, const void *__b)); +void twalk(const void *__key, void (*__action)(const void *__node, VISIT __which, int __depth)); void tdestroy(void *__root, void (*__free_node)(void *__node)); -void *lsearch(const void *__key, void *__base, size_t *__nelp, size_t __width, - int (*__compar)(const void *__a, const void *__b)); -void *lfind(const void *__key, const void *__base, size_t *__nelp, - size_t __width, int (*__compar)(const void *__a, const void *__b)); +void *lsearch( + const void *__key, + void *__base, + size_t *__nelp, + size_t __width, + int (*__compar)(const void *__a, const void *__b) +); +void *lfind( + const void *__key, + const void *__base, + size_t *__nelp, + size_t __width, + int (*__compar)(const void *__a, const void *__b) +); int hcreate(size_t __num_entries); void hdestroy(void); diff --git a/options/posix/include/semaphore.h b/options/posix/include/semaphore.h index 89601505a8..2911f85ff6 100644 --- a/options/posix/include/semaphore.h +++ b/options/posix/include/semaphore.h @@ -9,7 +9,7 @@ extern "C" { #include #define SEM_VALUE_MAX 0x7FFFFFFF -#define SEM_FAILED ((sem_t *) 0) +#define SEM_FAILED ((sem_t *)0) typedef struct sem_ { unsigned int __mlibc_count; diff --git a/options/posix/include/spawn.h b/options/posix/include/spawn.h index ec5d938fa0..9232f6622f 100644 --- a/options/posix/include/spawn.h +++ b/options/posix/include/spawn.h @@ -2,9 +2,9 @@ #ifndef _SPAWN_H #define _SPAWN_H -#include #include #include +#include #include #ifdef __cplusplus @@ -41,34 +41,50 @@ struct sched_param; #ifndef __MLIBC_ABI_ONLY -int posix_spawn(pid_t *__restrict __pid, const char *__restrict __path, - const posix_spawn_file_actions_t *__file_actions, - const posix_spawnattr_t *__restrict __attrs, - char *const __argv[], char *const __envp[]); +int posix_spawn( + pid_t *__restrict __pid, + const char *__restrict __path, + const posix_spawn_file_actions_t *__file_actions, + const posix_spawnattr_t *__restrict __attrs, + char *const __argv[], + char *const __envp[] +); int posix_spawnattr_init(posix_spawnattr_t *__attr); int posix_spawnattr_destroy(posix_spawnattr_t *__attr); int posix_spawnattr_setflags(posix_spawnattr_t *__attr, short __flags); -int posix_spawnattr_setsigdefault(posix_spawnattr_t *__restrict __attr, - const sigset_t *__restrict __sigdefault); -int posix_spawnattr_setschedparam(posix_spawnattr_t *__restrict __attr, - const struct sched_param *__restrict __schedparam); +int posix_spawnattr_setsigdefault( + posix_spawnattr_t *__restrict __attr, const sigset_t *__restrict __sigdefault +); +int posix_spawnattr_setschedparam( + posix_spawnattr_t *__restrict __attr, const struct sched_param *__restrict __schedparam +); int posix_spawnattr_setschedpolicy(posix_spawnattr_t *__attr, int __schedpolicy); -int posix_spawnattr_setsigmask(posix_spawnattr_t *__restrict __attr, - const sigset_t *__restrict __sigmask); +int posix_spawnattr_setsigmask( + posix_spawnattr_t *__restrict __attr, const sigset_t *__restrict __sigmask +); int posix_spawnattr_setpgroup(posix_spawnattr_t *__attr, pid_t __pgroup); int posix_spawn_file_actions_init(posix_spawn_file_actions_t *__file_actions); int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *__file_actions); -int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *__file_actions, - int __fildes, int __newfildes); -int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *__file_actions, - int __fildes); -int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *__restrict __file_actions, - int __fildes, const char *__restrict __path, int __oflag, mode_t __mode); -int posix_spawnp(pid_t *__restrict __pid, const char *__restrict __file, - const posix_spawn_file_actions_t *__file_actions, - const posix_spawnattr_t *__restrict __attrp, - char *const __argv[], char *const __envp[]); +int posix_spawn_file_actions_adddup2( + posix_spawn_file_actions_t *__file_actions, int __fildes, int __newfildes +); +int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *__file_actions, int __fildes); +int posix_spawn_file_actions_addopen( + posix_spawn_file_actions_t *__restrict __file_actions, + int __fildes, + const char *__restrict __path, + int __oflag, + mode_t __mode +); +int posix_spawnp( + pid_t *__restrict __pid, + const char *__restrict __file, + const posix_spawn_file_actions_t *__file_actions, + const posix_spawnattr_t *__restrict __attrp, + char *const __argv[], + char *const __envp[] +); /* MISSING: all other functions */ @@ -79,4 +95,3 @@ int posix_spawnp(pid_t *__restrict __pid, const char *__restrict __file, #endif #endif /* SPAWN_H */ - diff --git a/options/posix/include/strings.h b/options/posix/include/strings.h index 071f3fa9f6..b07c7f26e1 100644 --- a/options/posix/include/strings.h +++ b/options/posix/include/strings.h @@ -10,7 +10,7 @@ extern "C" { #ifndef __MLIBC_ABI_ONLY -char *index (const char *__s, int __c); +char *index(const char *__s, int __c); char *rindex(const char *__s, int __c); int ffs(int __word); @@ -29,4 +29,3 @@ void bzero(void *__s, size_t __n); #endif #endif /* _STRINGS_H */ - diff --git a/options/posix/include/sys/file.h b/options/posix/include/sys/file.h index 11dff16a65..4041bb6f0a 100644 --- a/options/posix/include/sys/file.h +++ b/options/posix/include/sys/file.h @@ -23,4 +23,3 @@ int flock64(int __fd, int __op); #endif #endif /* _SYS_FILE_H */ - diff --git a/options/posix/include/sys/ipc.h b/options/posix/include/sys/ipc.h index e8c1714e1a..013ea52134 100644 --- a/options/posix/include/sys/ipc.h +++ b/options/posix/include/sys/ipc.h @@ -1,9 +1,9 @@ #ifndef _SYS_IPC_H #define _SYS_IPC_H -#include #include #include +#include #ifdef __cplusplus extern "C" { @@ -18,7 +18,7 @@ extern "C" { #define IPC_STAT 2 #define IPC_INFO 3 -#define IPC_PRIVATE ((key_t) 0) +#define IPC_PRIVATE ((key_t)0) #if defined(__aarch64__) || defined(__i386__) || defined(__m68k__) #define IPC_64 0x100 diff --git a/options/posix/include/sys/mman.h b/options/posix/include/sys/mman.h index 5c48465bb6..f6376ac55b 100644 --- a/options/posix/include/sys/mman.h +++ b/options/posix/include/sys/mman.h @@ -1,11 +1,11 @@ #ifndef _SYS_MMAN_H #define _SYS_MMAN_H -#include #include #include #include #include +#include #ifdef __cplusplus extern "C" { diff --git a/options/posix/include/sys/param.h b/options/posix/include/sys/param.h index b2c7d71340..85f22b61a7 100644 --- a/options/posix/include/sys/param.h +++ b/options/posix/include/sys/param.h @@ -19,17 +19,16 @@ extern "C" { #endif #undef MIN -#define MIN(a,b) (((a) < (b)) ? (a) : (b)) +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) #undef MAX -#define MAX(a,b) (((a) > (b)) ? (a) : (b)) +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#define howmany(x, y) (((x) + ((y) - 1)) / (y)) +#define howmany(x, y) (((x) + ((y) - 1)) / (y)) -#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) +#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) #ifdef __cplusplus } #endif #endif /* _SYS_PARAM_H */ - diff --git a/options/posix/include/sys/poll.h b/options/posix/include/sys/poll.h index bebe62724c..a764972ea1 100644 --- a/options/posix/include/sys/poll.h +++ b/options/posix/include/sys/poll.h @@ -1,11 +1,11 @@ #ifndef _SYS_POLL_H #define _SYS_POLL_H -#include -#include -#include #include #include +#include +#include +#include #include typedef __mlibc_size nfds_t; @@ -25,8 +25,12 @@ struct pollfd { int poll(struct pollfd *__fds, nfds_t __nfds, int __timeout); #if __MLIBC_LINUX_OPTION -int ppoll(struct pollfd *__fds, nfds_t __nfds, - const struct timespec *__timeout_ts, const sigset_t *__sigmask); +int ppoll( + struct pollfd *__fds, + nfds_t __nfds, + const struct timespec *__timeout_ts, + const sigset_t *__sigmask +); #endif /* __MLIBC_LINUX_OPTION */ #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/posix/include/sys/resource.h b/options/posix/include/sys/resource.h index 145c652864..034e7d4e29 100644 --- a/options/posix/include/sys/resource.h +++ b/options/posix/include/sys/resource.h @@ -3,9 +3,9 @@ #include #include -#include #include #include +#include #include #define PRIO_PROCESS 1 @@ -15,9 +15,9 @@ #define PRIO_MIN (-20) #define PRIO_MAX 20 -#define RLIM_INFINITY ((rlim_t)-1) -#define RLIM_SAVED_MAX ((rlim_t)-1) -#define RLIM_SAVED_CUR ((rlim_t)-1) +#define RLIM_INFINITY ((rlim_t) - 1) +#define RLIM_SAVED_MAX ((rlim_t) - 1) +#define RLIM_SAVED_CUR ((rlim_t) - 1) #define RLIM_NLIMITS RLIMIT_NLIMITS @@ -43,7 +43,9 @@ int getrlimit64(int __resource, struct rlimit *__rlim); int setrlimit(int __resource, const struct rlimit *__rlim); int setrlimit64(int __resource, const struct rlimit *__rlim); -int prlimit(pid_t __pid, int __resource, const struct rlimit *__new_limits, struct rlimit *__old_limits); +int prlimit( + pid_t __pid, int __resource, const struct rlimit *__new_limits, struct rlimit *__old_limits +); #endif /* !__MLIBC_ABI_ONLY */ diff --git a/options/posix/include/sys/select.h b/options/posix/include/sys/select.h index 10d1a34227..282d319e6a 100644 --- a/options/posix/include/sys/select.h +++ b/options/posix/include/sys/select.h @@ -4,11 +4,11 @@ #include +#include #include #include -#include -#include #include +#include #define FD_SETSIZE 1024 @@ -17,7 +17,7 @@ extern "C" { #endif typedef long int __fd_mask; -#define __NFDBITS (8 * (int) sizeof (__fd_mask)) +#define __NFDBITS (8 * (int)sizeof(__fd_mask)) typedef __fd_mask fd_mask; #define NFDBITS __NFDBITS @@ -34,10 +34,21 @@ void __FD_ZERO(fd_set *__set); #define FD_SET(fd, set) __FD_SET(fd, set) #define FD_ZERO(set) __FD_ZERO(set) -int select(int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, - fd_set *__restrict __exceptfds, struct timeval *__restrict __timeout); -int pselect(int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, - fd_set *__exceptfds, const struct timespec *__timeout, const sigset_t *__sigmask); +int select( + int __nfds, + fd_set *__restrict __readfds, + fd_set *__restrict __writefds, + fd_set *__restrict __exceptfds, + struct timeval *__restrict __timeout +); +int pselect( + int __nfds, + fd_set *__restrict __readfds, + fd_set *__restrict __writefds, + fd_set *__exceptfds, + const struct timespec *__timeout, + const sigset_t *__sigmask +); #endif /* !__MLIBC_ABI_ONLY */ @@ -46,4 +57,3 @@ int pselect(int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __write #endif #endif /* _SYS_SELECT_H */ - diff --git a/options/posix/include/sys/sem.h b/options/posix/include/sys/sem.h index d98f91f3f8..4befed1d96 100644 --- a/options/posix/include/sys/sem.h +++ b/options/posix/include/sys/sem.h @@ -2,8 +2,8 @@ #define _SYS_SEM_H #include -#include #include +#include #ifdef __cplusplus extern "C" { @@ -25,10 +25,10 @@ struct sembuf { struct semid_ds { struct ipc_perm sem_perm; - time_t sem_otime; - time_t sem_ctime; + time_t sem_otime; + time_t sem_ctime; - unsigned long sem_nsems; + unsigned long sem_nsems; }; #ifndef __MLIBC_ABI_ONLY diff --git a/options/posix/include/sys/socket.h b/options/posix/include/sys/socket.h index 69871eea64..535bb74bbb 100644 --- a/options/posix/include/sys/socket.h +++ b/options/posix/include/sys/socket.h @@ -4,14 +4,14 @@ #include #include -#include +#include #include -#include #include -#include -#include #include #include +#include +#include +#include #include @@ -34,8 +34,7 @@ struct sockaddr { /* Auxiliary macro. While there is basically no reason for applications */ /* to use this, it is exported by glibc. */ -#define CMSG_ALIGN(s) (((s) + __alignof__(size_t) - 1) & \ - ~(__alignof__(size_t) - 1)) +#define CMSG_ALIGN(s) (((s) + __alignof__(size_t) - 1) & ~(__alignof__(size_t) - 1)) /* Basic macros to return content and padding size of a control message. */ #define CMSG_LEN(s) (CMSG_ALIGN(sizeof(struct cmsghdr)) + (s)) @@ -49,18 +48,20 @@ struct sockaddr { /* For parsing control messages only. */ /* Returns a pointer to the first header or nullptr if there is none. */ -#define CMSG_FIRSTHDR(m) ((size_t)(m)->msg_controllen <= sizeof(struct cmsghdr) \ - ? (struct cmsghdr *)0 : (struct cmsghdr *) (m)->msg_control) +#define CMSG_FIRSTHDR(m) \ + ((size_t)(m)->msg_controllen <= sizeof(struct cmsghdr) ? (struct cmsghdr *)0 \ + : (struct cmsghdr *)(m)->msg_control) /* For parsing control messages only. */ /* Returns a pointer to the next header or nullptr if there is none. */ -#define CMSG_NXTHDR(m, c) \ - ((c)->cmsg_len < sizeof(struct cmsghdr) || \ - (ptrdiff_t)(sizeof(struct cmsghdr) + CMSG_ALIGN((c)->cmsg_len)) \ - >= __MLIBC_MHDR_LIMIT(m) - (char *)(c) \ - ? (struct cmsghdr *)0 : (struct cmsghdr *)__MLIBC_CMSG_NEXT(c)) - -struct linger{ +#define CMSG_NXTHDR(m, c) \ + ((c)->cmsg_len < sizeof(struct cmsghdr) || \ + (ptrdiff_t)(sizeof(struct cmsghdr) + CMSG_ALIGN((c)->cmsg_len)) >= \ + __MLIBC_MHDR_LIMIT(m) - (char *)(c) \ + ? (struct cmsghdr *)0 \ + : (struct cmsghdr *)__MLIBC_CMSG_NEXT(c)) + +struct linger { int l_onoff; int l_linger; }; @@ -74,24 +75,51 @@ struct ucred { #ifndef __MLIBC_ABI_ONLY int accept(int __sockfd, struct sockaddr *__restrict __addr, socklen_t *__restrict __addrlen); -int accept4(int __sockfd, struct sockaddr *__restrict __addr, socklen_t *__restrict __addrlen, int __flags); +int accept4( + int __sockfd, struct sockaddr *__restrict __addr, socklen_t *__restrict __addrlen, int __flags +); int bind(int __sockfd, const struct sockaddr *__addr, socklen_t __addrlen); int connect(int __sockfd, const struct sockaddr *__addr, socklen_t __addrlen); int getpeername(int __sockfd, struct sockaddr *__restrict __addr, socklen_t *__restrict __addrlen); int getsockname(int __sockfd, struct sockaddr *__restrict __addr, socklen_t *__restrict __addrlen); -int getsockopt(int __sockfd, int __level, int __optname, void *__restrict __optval, socklen_t *__restrict __optlen); +int getsockopt( + int __sockfd, + int __level, + int __optname, + void *__restrict __optval, + socklen_t *__restrict __optlen +); int listen(int __sockfd, int __backlog); ssize_t recv(int __sockfd, void *__buf, size_t __size, int __flags); -ssize_t recvfrom(int __sockfd, void *__restrict __buf, size_t __size, int __flags, - struct sockaddr *__restrict __src_addr, socklen_t *__restrict __addrlen); +ssize_t recvfrom( + int __sockfd, + void *__restrict __buf, + size_t __size, + int __flags, + struct sockaddr *__restrict __src_addr, + socklen_t *__restrict __addrlen +); ssize_t recvmsg(int __sockfd, struct msghdr *__msg, int __flags); ssize_t send(int __sockfd, const void *__buf, size_t __size, int __flags); ssize_t sendmsg(int __sockfd, const struct msghdr *__msg, int __flags); -ssize_t sendto(int __sockfd, const void *__buf, size_t __size, int __flags, - const struct sockaddr *__dest_addr, socklen_t __addrlen); -int recvmmsg(int __sockfd, struct mmsghdr *__msgvec, unsigned int __vlen, int __flags, struct timespec *__timeout); +ssize_t sendto( + int __sockfd, + const void *__buf, + size_t __size, + int __flags, + const struct sockaddr *__dest_addr, + socklen_t __addrlen +); +int recvmmsg( + int __sockfd, + struct mmsghdr *__msgvec, + unsigned int __vlen, + int __flags, + struct timespec *__timeout +); int sendmmsg(int __sockfd, struct mmsghdr *__msgvec, unsigned int __vlen, int __flags); -int setsockopt(int __sockfd, int __level, int __option_name, const void *__optval, socklen_t __optlen); +int +setsockopt(int __sockfd, int __level, int __option_name, const void *__optval, socklen_t __optlen); int shutdown(int __sockfd, int __how); int sockatmark(int __sockfd); int socket(int __domain, int __type, int __protocol); @@ -104,4 +132,3 @@ int socketpair(int __domain, int __type, int __protocol, int __sv[2]); #endif #endif /* _UNISTD_H */ - diff --git a/options/posix/include/sys/stat.h b/options/posix/include/sys/stat.h index 98f1d2a497..dd6e08e19c 100644 --- a/options/posix/include/sys/stat.h +++ b/options/posix/include/sys/stat.h @@ -20,7 +20,8 @@ int fchmod(int __fd, mode_t __mode); int fchmodat(int __fd, const char *__pathname, mode_t __mode, int __flags); int fstat(int __fd, struct stat *__result); int fstat64(int __fd, struct stat64 *__result); -int fstatat(int __fd, const char *__restrict __pathname, struct stat *__restrict __buf, int __flags); +int +fstatat(int __fd, const char *__restrict __pathname, struct stat *__restrict __buf, int __flags); int futimens(int __fd, const struct timespec __times[2]); int lstat(const char *__restrict __pathname, struct stat *__restrict __buf); int lstat64(const char *__restrict __pathname, struct stat64 *__restrict __buf); @@ -41,4 +42,3 @@ int utimensat(int __dirfd, const char *__pathname, const struct timespec __times #endif #endif /* _SYS_STAT_H */ - diff --git a/options/posix/include/sys/statvfs.h b/options/posix/include/sys/statvfs.h index 03e65a339a..dfc8e9fdfd 100644 --- a/options/posix/include/sys/statvfs.h +++ b/options/posix/include/sys/statvfs.h @@ -21,4 +21,3 @@ int fstatvfs64(int __fd, struct statvfs64 *__buf); #endif #endif /* _SYS_STATVFS_H */ - diff --git a/options/posix/include/sys/termios.h b/options/posix/include/sys/termios.h index 21767807bc..6eb0ec1eff 100644 --- a/options/posix/include/sys/termios.h +++ b/options/posix/include/sys/termios.h @@ -3,4 +3,3 @@ #define _SYS_TERMIOS_H #include #endif /* _SYS_TERMIOS_H */ - diff --git a/options/posix/include/sys/time.h b/options/posix/include/sys/time.h index 0debecfa5f..db40e2f6ea 100644 --- a/options/posix/include/sys/time.h +++ b/options/posix/include/sys/time.h @@ -1,11 +1,11 @@ #ifndef _SYS_TIME_H #define _SYS_TIME_H -#include -#include #include -#include +#include #include +#include +#include #include #include @@ -34,32 +34,33 @@ int timerisset(struct timeval *__tvp); #endif /* !__MLIBC_ABI_ONLY */ /* timercmp taken from musl */ -#define timercmp(s,t,op) ((s)->tv_sec == (t)->tv_sec ? \ - (s)->tv_usec op (t)->tv_usec : (s)->tv_sec op (t)->tv_sec) +#define timercmp(s, t, op) \ + ((s)->tv_sec == (t)->tv_sec ? (s)->tv_usec op(t)->tv_usec : (s)->tv_sec op(t)->tv_sec) #ifndef __MLIBC_ABI_ONLY int getitimer(int __which, struct itimerval *__curr_value); -int setitimer(int __which, const struct itimerval *__new_value, - struct itimerval *__old_value); - -int timer_create(clockid_t __clockid, struct sigevent *__restrict __sevp, timer_t *__restrict __timerid); -int timer_settime(timer_t __timerid, int __flags, const struct itimerspec *__restrict __new_value, - struct itimerspec *__restrict __old_value); +int setitimer(int __which, const struct itimerval *__new_value, struct itimerval *__old_value); + +int timer_create( + clockid_t __clockid, struct sigevent *__restrict __sevp, timer_t *__restrict __timerid +); +int timer_settime( + timer_t __timerid, + int __flags, + const struct itimerspec *__restrict __new_value, + struct itimerspec *__restrict __old_value +); int timer_gettime(timer_t __timerid, struct itimerspec *__curr_value); int timer_delete(timer_t __timerid); #endif /* !__MLIBC_ABI_ONLY */ /* The following 2 macros are taken from musl */ -#define TIMEVAL_TO_TIMESPEC(tv, ts) ( \ - (ts)->tv_sec = (tv)->tv_sec, \ - (ts)->tv_nsec = (tv)->tv_usec * 1000, \ - (void)0 ) -#define TIMESPEC_TO_TIMEVAL(tv, ts) ( \ - (tv)->tv_sec = (ts)->tv_sec, \ - (tv)->tv_usec = (ts)->tv_nsec / 1000, \ - (void)0 ) +#define TIMEVAL_TO_TIMESPEC(tv, ts) \ + ((ts)->tv_sec = (tv)->tv_sec, (ts)->tv_nsec = (tv)->tv_usec * 1000, (void)0) +#define TIMESPEC_TO_TIMEVAL(tv, ts) \ + ((tv)->tv_sec = (ts)->tv_sec, (tv)->tv_usec = (ts)->tv_nsec / 1000, (void)0) #ifdef __cplusplus } diff --git a/options/posix/include/sys/ttydefaults.h b/options/posix/include/sys/ttydefaults.h index 8ed811f301..c8e93ca51b 100644 --- a/options/posix/include/sys/ttydefaults.h +++ b/options/posix/include/sys/ttydefaults.h @@ -6,7 +6,7 @@ #define TTYDEF_IFLAG (BRKINT | ISTRIP | ICRNL | IMAXBEL | IXON | IXANY) #define TTYDEF_OFLAG (OPOST | ONLCR | XTABS) -#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL) +#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE | ECHOKE | ECHOCTL) #define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL) #define TTYDEF_SPEED (B9600) diff --git a/options/posix/include/sys/types.h b/options/posix/include/sys/types.h index 41f6ebca8a..7b64f651f8 100644 --- a/options/posix/include/sys/types.h +++ b/options/posix/include/sys/types.h @@ -2,24 +2,24 @@ #ifndef _SYS_TYPES_H #define _SYS_TYPES_H +#include #include #include -#include -#include -#include #include #include +#include +#include -#include +#include +#include #include #include -#include -#include +#include #include -#include #include +#include #include #include @@ -50,4 +50,3 @@ typedef int64_t quad_t; typedef uint64_t u_quad_t; #endif /* _SYS_TYPES_H */ - diff --git a/options/posix/include/sys/uio.h b/options/posix/include/sys/uio.h index 1547036d83..81bc8ae635 100644 --- a/options/posix/include/sys/uio.h +++ b/options/posix/include/sys/uio.h @@ -1,10 +1,10 @@ #ifndef _SYS_UIO_H #define _SYS_UIO_H -#include -#include #include +#include #include +#include #include #ifdef __cplusplus diff --git a/options/posix/include/sys/un.h b/options/posix/include/sys/un.h index 7a0093e69d..546d40af62 100644 --- a/options/posix/include/sys/un.h +++ b/options/posix/include/sys/un.h @@ -14,11 +14,10 @@ struct sockaddr_un { }; /* Evaluate to actual length of the `sockaddr_un' structure. */ -#define SUN_LEN(ptr) ((size_t) offsetof(struct sockaddr_un, sun_path) + strlen((ptr)->sun_path)) +#define SUN_LEN(ptr) ((size_t)offsetof(struct sockaddr_un, sun_path) + strlen((ptr)->sun_path)) #ifdef __cplusplus } #endif #endif /* _SYS_UN_H */ - diff --git a/options/posix/include/sys/utsname.h b/options/posix/include/sys/utsname.h index 5ae31dec17..5e9a3cc9fa 100644 --- a/options/posix/include/sys/utsname.h +++ b/options/posix/include/sys/utsname.h @@ -19,4 +19,3 @@ int uname(struct utsname *__name); #endif #endif /* _SYS_UTSNAME_H */ - diff --git a/options/posix/include/sys/wait.h b/options/posix/include/sys/wait.h index 5143086bf7..302e181024 100644 --- a/options/posix/include/sys/wait.h +++ b/options/posix/include/sys/wait.h @@ -2,8 +2,8 @@ #ifndef _SYS_WAIT_H #define _SYS_WAIT_H -#include #include +#include /* for siginfo_t */ #include #include @@ -16,9 +16,7 @@ extern "C" { struct rusage; /* TODO: move to own file and include in sys/types.h */ -typedef enum { - P_ALL, P_PID, P_PGID -} idtype_t; +typedef enum { P_ALL, P_PID, P_PGID } idtype_t; #ifndef __MLIBC_ABI_ONLY @@ -37,4 +35,3 @@ pid_t wait4(pid_t __pid, int *__status, int __options, struct rusage *__ru); #endif #endif /* _SYS_WAIT_H */ - diff --git a/options/posix/include/syslog.h b/options/posix/include/syslog.h index c984be1696..d8fe0127f9 100644 --- a/options/posix/include/syslog.h +++ b/options/posix/include/syslog.h @@ -15,36 +15,36 @@ extern "C" { #define LOG_NOWAIT 0x10 #define LOG_PERROR 0x20 -#define LOG_KERN (0<<3) -#define LOG_USER (1<<3) -#define LOG_MAIL (2<<3) -#define LOG_DAEMON (3<<3) -#define LOG_AUTH (4<<3) -#define LOG_SYSLOG (5<<3) -#define LOG_LPR (6<<3) -#define LOG_NEWS (7<<3) -#define LOG_UUCP (8<<3) -#define LOG_CRON (9<<3) -#define LOG_AUTHPRIV (10<<3) -#define LOG_FTP (11<<3) +#define LOG_KERN (0 << 3) +#define LOG_USER (1 << 3) +#define LOG_MAIL (2 << 3) +#define LOG_DAEMON (3 << 3) +#define LOG_AUTH (4 << 3) +#define LOG_SYSLOG (5 << 3) +#define LOG_LPR (6 << 3) +#define LOG_NEWS (7 << 3) +#define LOG_UUCP (8 << 3) +#define LOG_CRON (9 << 3) +#define LOG_AUTHPRIV (10 << 3) +#define LOG_FTP (11 << 3) -#define LOG_LOCAL0 (16<<3) -#define LOG_LOCAL1 (17<<3) -#define LOG_LOCAL2 (18<<3) -#define LOG_LOCAL3 (19<<3) -#define LOG_LOCAL4 (20<<3) -#define LOG_LOCAL5 (21<<3) -#define LOG_LOCAL6 (22<<3) -#define LOG_LOCAL7 (23<<3) +#define LOG_LOCAL0 (16 << 3) +#define LOG_LOCAL1 (17 << 3) +#define LOG_LOCAL2 (18 << 3) +#define LOG_LOCAL3 (19 << 3) +#define LOG_LOCAL4 (20 << 3) +#define LOG_LOCAL5 (21 << 3) +#define LOG_LOCAL6 (22 << 3) +#define LOG_LOCAL7 (23 << 3) #define LOG_PRIMASK 7 -#define LOG_PRI(p) ((p)&LOG_PRIMASK) -#define LOG_MAKEPRI(f, p) (((f)<<3) | (p)) -#define LOG_MASK(p) (1<<(p)) -#define LOG_UPTO(p) ((1<<((p)+1))-1) +#define LOG_PRI(p) ((p) & LOG_PRIMASK) +#define LOG_MAKEPRI(f, p) (((f) << 3) | (p)) +#define LOG_MASK(p) (1 << (p)) +#define LOG_UPTO(p) ((1 << ((p) + 1)) - 1) #define LOG_NFACILITIES 24 -#define LOG_FACMASK (0x7F<<3) -#define LOG_FAC(p) (((p)&LOG_FACMASK)>>3) +#define LOG_FACMASK (0x7F << 3) +#define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3) #define LOG_EMERG 0 #define LOG_ALERT 1 @@ -60,12 +60,12 @@ extern "C" { void closelog(void); void openlog(const char *__ident, int __option, int __facility); int setlogmask(int __mask); -__attribute__((__format__(__printf__, 2, 3))) -void syslog(int __priority, const char *__format, ...); +__attribute__((__format__(__printf__, 2, 3))) void +syslog(int __priority, const char *__format, ...); /* This is a linux extension */ -__attribute__((__format__(__printf__, 2, 0))) -void vsyslog(int __priority, const char *__format, va_list __args); +__attribute__((__format__(__printf__, 2, 0))) void +vsyslog(int __priority, const char *__format, va_list __args); #endif /* !__MLIBC_ABI_ONLY */ @@ -74,4 +74,3 @@ void vsyslog(int __priority, const char *__format, va_list __args); #endif #endif /* _SYSLOG_H */ - diff --git a/options/posix/include/termios.h b/options/posix/include/termios.h index 7f62142e4e..0d7fa3462a 100644 --- a/options/posix/include/termios.h +++ b/options/posix/include/termios.h @@ -16,29 +16,29 @@ extern "C" { #endif /* baud rate constants for speed_t */ -#define B0 0 -#define B50 1 -#define B75 2 -#define B110 3 -#define B134 4 -#define B150 5 -#define B200 6 -#define B300 7 -#define B600 8 -#define B1200 9 -#define B1800 10 -#define B2400 11 -#define B4800 12 -#define B9600 13 -#define B19200 14 -#define B38400 15 -#define B57600 0010001 -#define B115200 0010002 -#define B230400 0010003 -#define B460800 0010004 -#define B500000 0010005 -#define B576000 0010006 -#define B921600 0010007 +#define B0 0 +#define B50 1 +#define B75 2 +#define B110 3 +#define B134 4 +#define B150 5 +#define B200 6 +#define B300 7 +#define B600 8 +#define B1200 9 +#define B1800 10 +#define B2400 11 +#define B4800 12 +#define B9600 13 +#define B19200 14 +#define B38400 15 +#define B57600 0010001 +#define B115200 0010002 +#define B230400 0010003 +#define B460800 0010004 +#define B500000 0010005 +#define B576000 0010006 +#define B921600 0010007 #define B1000000 0010010 #define B1152000 0010011 #define B1500000 0010012 @@ -98,4 +98,3 @@ int tcsetattr(int __fd, int __optional_actions, const struct termios *__attr); #endif #endif /* _TERMIOS_H */ - diff --git a/options/posix/include/unistd.h b/options/posix/include/unistd.h index 97bbaae63c..f358121c32 100644 --- a/options/posix/include/unistd.h +++ b/options/posix/include/unistd.h @@ -2,17 +2,16 @@ #ifndef _UNISTD_H #define _UNISTD_H -#include -#include -#include -#include -#include -#include #include -#include #include #include #include +#include +#include +#include +#include +#include +#include #if __MLIBC_SYSDEP_HAS_BITS_SYSCALL_H && __MLIBC_LINUX_OPTION #include @@ -90,15 +89,15 @@ extern "C" { /* MISSING: _PC macros */ /* For now, use the Linux ABI for _PC constants. */ -#define _PC_LINK_MAX 0 -#define _PC_MAX_CANON 1 -#define _PC_MAX_INPUT 2 -#define _PC_NAME_MAX 3 -#define _PC_PATH_MAX 4 -#define _PC_PIPE_BUF 5 -#define _PC_CHOWN_RESTRICTED 6 -#define _PC_NO_TRUNC 7 -#define _PC_VDISABLE 8 +#define _PC_LINK_MAX 0 +#define _PC_MAX_CANON 1 +#define _PC_MAX_INPUT 2 +#define _PC_NAME_MAX 3 +#define _PC_PATH_MAX 4 +#define _PC_PIPE_BUF 5 +#define _PC_CHOWN_RESTRICTED 6 +#define _PC_NO_TRUNC 7 +#define _PC_VDISABLE 8 #define _PC_FILESIZEBITS 9 #define _PC_SYMLINK_MAX 10 @@ -304,7 +303,8 @@ char *getusershell(void); int isatty(int __fd); int lchown(const char *__path, uid_t __uid, gid_t __gid); int link(const char *__oldpath, const char *__newpath); -int linkat(int __olddirfd, const char *__oldpath, int __newdirfd, const char *__newpath, int __flags); +int +linkat(int __olddirfd, const char *__oldpath, int __newdirfd, const char *__newpath, int __flags); int lockf(int __fd, int __op, off_t __size); off_t lseek(int __fd, off_t __offset, int __whence); off64_t lseek64(int __fd, off64_t __offset, int __whence); @@ -318,7 +318,8 @@ ssize_t pwrite(int __fd, const void *__buf, size_t __size, off_t __offset); ssize_t pwrite64(int __fd, const void *__buf, size_t __size, off_t __offset); ssize_t read(int fd, void *buffer, size_t size); ssize_t readlink(const char *__restrict __path, char *__restrict __buf, size_t __size); -ssize_t readlinkat(int __dirfd, const char *__restrict __path, char *__restrict __buf, size_t __size); +ssize_t +readlinkat(int __dirfd, const char *__restrict __path, char *__restrict __buf, size_t __size); int rmdir(const char *__path); int setegid(gid_t __egid); int seteuid(uid_t __euid); @@ -392,12 +393,11 @@ int getresgid(gid_t *__rgid, gid_t *__egid, gid_t *__sgid); #endif #if __MLIBC_LINUX_OPTION -# include +#include #endif #if __MLIBC_BSD_OPTION -# include +#include #endif #endif /* _UNISTD_H */ - diff --git a/options/rtld/generic/linker.cpp b/options/rtld/generic/linker.cpp index ec11f1b92b..bcccba3d05 100644 --- a/options/rtld/generic/linker.cpp +++ b/options/rtld/generic/linker.cpp @@ -4,19 +4,18 @@ // keep a list of optional generic relocation types enum { - R_OFFSET = (uintptr_t) -1, + R_OFFSET = (uintptr_t)-1, }; - +#include #include #include +#include #include #include -#include #include +#include #include -#include -#include #include "elf.hpp" #include "linker.hpp" @@ -45,13 +44,15 @@ constexpr inline uintptr_t tlsOffsetFromTp = 0; constexpr inline bool tlsAboveTp = true; constexpr inline ptrdiff_t tlsOffsetFromTp = -0x7000; #else -# error Unknown architecture +#error Unknown architecture #endif extern DebugInterface globalDebugInterface; extern uintptr_t __stack_chk_guard; -extern frg::manual_box> libraryPaths; +extern frg::manual_box< + frg::small_vector> + libraryPaths; extern frg::manual_box> preloads; #if MLIBC_STATIC_BUILD @@ -80,10 +81,9 @@ bool trySeek(int fd, int64_t offset) { bool tryReadExactly(int fd, void *data, size_t length) { size_t offset = 0; - while(offset < length) { + while (offset < length) { ssize_t chunk; - if(mlibc::sys_read(fd, reinterpret_cast(data) + offset, - length - offset, &chunk)) + if (mlibc::sys_read(fd, reinterpret_cast(data) + offset, length - offset, &chunk)) return false; __ensure(chunk > 0); offset += chunk; @@ -93,30 +93,33 @@ bool tryReadExactly(int fd, void *data, size_t length) { } void closeOrDie(int fd) { - if(mlibc::sys_close(fd)) + if (mlibc::sys_close(fd)) __ensure(!"sys_close() failed"); } -uintptr_t alignUp(uintptr_t address, size_t align) { - return (address + align - 1) & ~(align - 1); -} +uintptr_t alignUp(uintptr_t address, size_t align) { return (address + align - 1) & ~(align - 1); } // -------------------------------------------------------- // ObjectRepository // -------------------------------------------------------- ObjectRepository::ObjectRepository() -: loadedObjects{getAllocator()}, - _nameMap{frg::hash{}, getAllocator()}, - _destructQueue{getAllocator()} {} - -SharedObject *ObjectRepository::injectObjectFromDts(frg::string_view name, - frg::string path, uintptr_t base_address, - elf_dyn *dynamic, uint64_t rts) { + : loadedObjects{getAllocator()}, + _nameMap{frg::hash{}, getAllocator()}, + _destructQueue{getAllocator()} {} + +SharedObject *ObjectRepository::injectObjectFromDts( + frg::string_view name, + frg::string path, + uintptr_t base_address, + elf_dyn *dynamic, + uint64_t rts +) { __ensure(!findLoadedObject(name)); - auto object = frg::construct(getAllocator(), - name.data(), std::move(path), false, globalScope.get(), rts); + auto object = frg::construct( + getAllocator(), name.data(), std::move(path), false, globalScope.get(), rts + ); object->baseAddress = base_address; object->dynamic = dynamic; _parseDynamic(object); @@ -127,14 +130,20 @@ SharedObject *ObjectRepository::injectObjectFromDts(frg::string_view name, return object; } -SharedObject *ObjectRepository::injectObjectFromPhdrs(frg::string_view name, - frg::string path, void *phdr_pointer, - size_t phdr_entry_size, size_t num_phdrs, void *entry_pointer, - uint64_t rts) { +SharedObject *ObjectRepository::injectObjectFromPhdrs( + frg::string_view name, + frg::string path, + void *phdr_pointer, + size_t phdr_entry_size, + size_t num_phdrs, + void *entry_pointer, + uint64_t rts +) { __ensure(!findLoadedObject(name)); - auto object = frg::construct(getAllocator(), - name.data(), std::move(path), true, globalScope.get(), rts); + auto object = frg::construct( + getAllocator(), name.data(), std::move(path), true, globalScope.get(), rts + ); _fetchFromPhdrs(object, phdr_pointer, phdr_entry_size, num_phdrs, entry_pointer); _parseDynamic(object); @@ -144,25 +153,31 @@ SharedObject *ObjectRepository::injectObjectFromPhdrs(frg::string_view name, return object; } -SharedObject *ObjectRepository::injectStaticObject(frg::string_view name, - frg::string path, void *phdr_pointer, - size_t phdr_entry_size, size_t num_phdrs, void *entry_pointer, - uint64_t rts) { +SharedObject *ObjectRepository::injectStaticObject( + frg::string_view name, + frg::string path, + void *phdr_pointer, + size_t phdr_entry_size, + size_t num_phdrs, + void *entry_pointer, + uint64_t rts +) { __ensure(!findLoadedObject(name)); - auto object = frg::construct(getAllocator(), - name.data(), std::move(path), true, globalScope.get(), rts); + auto object = frg::construct( + getAllocator(), name.data(), std::move(path), true, globalScope.get(), rts + ); _fetchFromPhdrs(object, phdr_pointer, phdr_entry_size, num_phdrs, entry_pointer); #if MLIBC_STATIC_BUILD - object->initArray = reinterpret_cast(__init_array_start); - object->initArraySize = static_cast((uintptr_t)__init_array_end - - (uintptr_t)__init_array_start); - object->finiArray = reinterpret_cast(__fini_array_start); - object->finiArraySize = static_cast((uintptr_t)__fini_array_end - - (uintptr_t)__fini_array_start); - object->preInitArray = reinterpret_cast(__preinit_array_start); - object->preInitArraySize = static_cast((uintptr_t)__preinit_array_end - - (uintptr_t)__preinit_array_start); + object->initArray = reinterpret_cast(__init_array_start); + object->initArraySize = + static_cast((uintptr_t)__init_array_end - (uintptr_t)__init_array_start); + object->finiArray = reinterpret_cast(__fini_array_start); + object->finiArraySize = + static_cast((uintptr_t)__fini_array_end - (uintptr_t)__fini_array_start); + object->preInitArray = reinterpret_cast(__preinit_array_start); + object->preInitArraySize = + static_cast((uintptr_t)__preinit_array_end - (uintptr_t)__preinit_array_start); #endif _addLoadedObject(object); @@ -170,14 +185,15 @@ SharedObject *ObjectRepository::injectStaticObject(frg::string_view name, return object; } -frg::expected ObjectRepository::requestObjectWithName(frg::string_view name, - SharedObject *origin, Scope *localScope, bool createScope, uint64_t rts) { +frg::expected ObjectRepository::requestObjectWithName( + frg::string_view name, SharedObject *origin, Scope *localScope, bool createScope, uint64_t rts +) { if (auto obj = findLoadedObject(name)) return obj; - auto tryToOpen = [&] (const char *path) { + auto tryToOpen = [&](const char *path) { int fd; - if(auto x = mlibc::sys_open(path, O_RDONLY, 0, &fd); x) { + if (auto x = mlibc::sys_open(path, O_RDONLY, 0, &fd); x) { return -1; } return fd; @@ -185,8 +201,8 @@ frg::expected ObjectRepository::requestObjectWithNa // TODO(arsen): this process can probably undergo heavy optimization, by // preprocessing the rpath only once on parse - auto processRpath = [&] (frg::string_view path) { - frg::string sPath { getAllocator() }; + auto processRpath = [&](frg::string_view path) { + frg::string sPath{getAllocator()}; if (path.starts_with("$ORIGIN")) { frg::string_view dirname = origin->path; auto lastsl = dirname.find_last('/'); @@ -195,10 +211,10 @@ frg::expected ObjectRepository::requestObjectWithNa } else { dirname = "."; } - sPath = frg::string{ getAllocator(), dirname }; + sPath = frg::string{getAllocator(), dirname}; sPath += path.sub_string(7, path.size() - 7); } else { - sPath = frg::string{ getAllocator(), path }; + sPath = frg::string{getAllocator(), path}; } if (sPath[sPath.size() - 1] != '/') { sPath += '/'; @@ -209,16 +225,16 @@ frg::expected ObjectRepository::requestObjectWithNa int fd = tryToOpen(sPath.data()); if (logRpath && fd >= 0) mlibc::infoLogger() << "rtld: found in rpath" << frg::endlog; - return frg::tuple { fd, std::move(sPath) }; + return frg::tuple{fd, std::move(sPath)}; }; - frg::string chosenPath { getAllocator() }; + frg::string chosenPath{getAllocator()}; int fd = -1; if (origin && origin->runPath) { size_t start = 0; size_t idx = 0; - frg::string_view rpath { origin->runPath }; - auto next = [&] () { + frg::string_view rpath{origin->runPath}; + auto next = [&]() { idx = rpath.find_first(':', start); if (idx == (size_t)-1) idx = rpath.size(); @@ -245,18 +261,19 @@ frg::expected ObjectRepository::requestObjectWithNa mlibc::infoLogger() << "rtld: no rpath set for object" << frg::endlog; } - for(size_t i = 0; i < libraryPaths->size() && fd == -1; i++) { + for (size_t i = 0; i < libraryPaths->size() && fd == -1; i++) { auto ldPath = (*libraryPaths)[i]; auto path = frg::string{getAllocator(), ldPath} + '/' + name; - if(logLdPath) - mlibc::infoLogger() << "rtld: Trying to load " << name << " from ldpath " << ldPath << "/" << frg::endlog; + if (logLdPath) + mlibc::infoLogger() << "rtld: Trying to load " << name << " from ldpath " << ldPath + << "/" << frg::endlog; fd = tryToOpen(path.data()); - if(fd >= 0) { + if (fd >= 0) { chosenPath = std::move(path); break; } } - if(fd == -1) + if (fd == -1) return LinkerError::notFound; if (createScope) { @@ -268,12 +285,13 @@ frg::expected ObjectRepository::requestObjectWithNa __ensure(localScope != nullptr); - auto object = frg::construct(getAllocator(), - name.data(), std::move(chosenPath), false, localScope, rts); + auto object = frg::construct( + getAllocator(), name.data(), std::move(chosenPath), false, localScope, rts + ); auto result = _fetchFromFile(object, fd); closeOrDie(fd); - if(!result) { + if (!result) { frg::destruct(getAllocator(), object); return result.error(); } @@ -286,8 +304,9 @@ frg::expected ObjectRepository::requestObjectWithNa return object; } -frg::expected ObjectRepository::requestObjectAtPath(frg::string_view path, - Scope *localScope, bool createScope, uint64_t rts) { +frg::expected ObjectRepository::requestObjectAtPath( + frg::string_view path, Scope *localScope, bool createScope, uint64_t rts +) { // TODO: Support SONAME correctly. auto lastSlash = path.find_last('/') + 1; auto name = path; @@ -306,19 +325,20 @@ frg::expected ObjectRepository::requestObjectAtPath __ensure(localScope != nullptr); - auto object = frg::construct(getAllocator(), - name.data(), path.data(), false, localScope, rts); + auto object = frg::construct( + getAllocator(), name.data(), path.data(), false, localScope, rts + ); frg::string no_prefix(getAllocator(), path); int fd; - if(mlibc::sys_open((no_prefix + '\0').data(), O_RDONLY, 0, &fd)) { + if (mlibc::sys_open((no_prefix + '\0').data(), O_RDONLY, 0, &fd)) { frg::destruct(getAllocator(), object); return LinkerError::notFound; } auto result = _fetchFromFile(object, fd); closeOrDie(fd); - if(!result) { + if (!result) { frg::destruct(getAllocator(), object); return result.error(); } @@ -336,7 +356,7 @@ SharedObject *ObjectRepository::findCaller(void *addr) { for (auto [name, object] : _nameMap) { // Search all PT_LOAD segments for the specified address. - for(size_t j = 0; j < object->phdrCount; j++) { + for (size_t j = 0; j < object->phdrCount; j++) { auto phdr = (elf_phdr *)((uintptr_t)object->phdrPointer + j * object->phdrEntrySize); if (phdr->p_type == PT_LOAD) { uintptr_t start = object->baseAddress + phdr->p_vaddr; @@ -383,13 +403,18 @@ void ObjectRepository::destructObjects() { // ObjectRepository: Fetching methods. // -------------------------------------------------------- -void ObjectRepository::_fetchFromPhdrs(SharedObject *object, void *phdr_pointer, - size_t phdr_entry_size, size_t phdr_count, void *entry_pointer) { +void ObjectRepository::_fetchFromPhdrs( + SharedObject *object, + void *phdr_pointer, + size_t phdr_entry_size, + size_t phdr_count, + void *entry_pointer +) { __ensure(object->isMainObject); object->phdrPointer = phdr_pointer; object->phdrEntrySize = phdr_entry_size; object->phdrCount = phdr_count; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Loading " << object->name << frg::endlog; // Note: the entry pointer is absolute and not relative to the base address. @@ -399,16 +424,16 @@ void ObjectRepository::_fetchFromPhdrs(SharedObject *object, void *phdr_pointer, frg::optional tls_offset; // segments are already mapped, so we just have to find the dynamic section - for(size_t i = 0; i < phdr_count; i++) { + for (size_t i = 0; i < phdr_count; i++) { auto phdr = (elf_phdr *)((uintptr_t)phdr_pointer + i * phdr_entry_size); - switch(phdr->p_type) { + switch (phdr->p_type) { case PT_PHDR: // Determine the executable's base address (in the PIE case) by comparing // the PHDR segment's load address against it's address in the ELF file. object->baseAddress = reinterpret_cast(phdr_pointer) - phdr->p_vaddr; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Executable is loaded at " - << (void *)object->baseAddress << frg::endlog; + << (void *)object->baseAddress << frg::endlog; break; case PT_DYNAMIC: dynamic_offset = phdr->p_vaddr; @@ -421,52 +446,47 @@ void ObjectRepository::_fetchFromPhdrs(SharedObject *object, void *phdr_pointer, break; case PT_INTERP: object->interpreterPath = frg::string{ - (char*)(object->baseAddress + phdr->p_vaddr), - getAllocator() + (char *)(object->baseAddress + phdr->p_vaddr), getAllocator() }; } break; default: - //FIXME warn about unknown phdrs + // FIXME warn about unknown phdrs break; } } - if(dynamic_offset) + if (dynamic_offset) object->dynamic = (elf_dyn *)(object->baseAddress + *dynamic_offset); - if(tls_offset) + if (tls_offset) object->tlsImagePtr = (void *)(object->baseAddress + *tls_offset); } - frg::expected ObjectRepository::_fetchFromFile(SharedObject *object, int fd) { __ensure(!object->isMainObject); // read the elf file header elf_ehdr ehdr; - if(!tryReadExactly(fd, &ehdr, sizeof(elf_ehdr))) + if (!tryReadExactly(fd, &ehdr, sizeof(elf_ehdr))) return LinkerError::fileTooShort; - if(ehdr.e_ident[0] != 0x7F - || ehdr.e_ident[1] != 'E' - || ehdr.e_ident[2] != 'L' - || ehdr.e_ident[3] != 'F') + if (ehdr.e_ident[0] != 0x7F || ehdr.e_ident[1] != 'E' || ehdr.e_ident[2] != 'L' || + ehdr.e_ident[3] != 'F') return LinkerError::notElf; - if((ehdr.e_type != ET_EXEC && ehdr.e_type != ET_DYN) - || ehdr.e_machine != ELF_MACHINE - || ehdr.e_ident[EI_CLASS] != ELF_CLASS) + if ((ehdr.e_type != ET_EXEC && ehdr.e_type != ET_DYN) || ehdr.e_machine != ELF_MACHINE || + ehdr.e_ident[EI_CLASS] != ELF_CLASS) return LinkerError::wrongElfType; // read the elf program headers auto phdr_buffer = (char *)getAllocator().allocate(ehdr.e_phnum * ehdr.e_phentsize); - if(!phdr_buffer) + if (!phdr_buffer) return LinkerError::outOfMemory; - if(!trySeek(fd, ehdr.e_phoff)) { + if (!trySeek(fd, ehdr.e_phoff)) { getAllocator().deallocate(phdr_buffer, ehdr.e_phnum * ehdr.e_phentsize); return LinkerError::invalidProgramHeader; } - if(!tryReadExactly(fd, phdr_buffer, ehdr.e_phnum * ehdr.e_phentsize)) { + if (!tryReadExactly(fd, phdr_buffer, ehdr.e_phnum * ehdr.e_phentsize)) { getAllocator().deallocate(phdr_buffer, ehdr.e_phnum * ehdr.e_phentsize); return LinkerError::invalidProgramHeader; } @@ -479,14 +499,14 @@ frg::expected ObjectRepository::_fetchFromFile(SharedObject * constexpr size_t hugeSize = 0x200000; uintptr_t highest_address = 0; - for(int i = 0; i < ehdr.e_phnum; i++) { + for (int i = 0; i < ehdr.e_phnum; i++) { auto phdr = (elf_phdr *)(phdr_buffer + i * ehdr.e_phentsize); - if(phdr->p_type != PT_LOAD) + if (phdr->p_type != PT_LOAD) continue; auto limit = phdr->p_vaddr + phdr->p_memsz; - if(limit > highest_address) + if (limit > highest_address) highest_address = limit; } @@ -497,14 +517,19 @@ frg::expected ObjectRepository::_fetchFromFile(SharedObject * #if MLIBC_MMAP_ALLOCATE_DSO void *mappedAddr = nullptr; - if (mlibc::sys_vm_map(nullptr, - highest_address - object->baseAddress, PROT_NONE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0, &mappedAddr)) { + if (mlibc::sys_vm_map( + nullptr, + highest_address - object->baseAddress, + PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0, + &mappedAddr + )) { mlibc::infoLogger() << "sys_vm_map failed when allocating address space for DSO \"" - << object->name << "\"" - << ", base " << (void *)object->baseAddress - << ", requested " << (highest_address - object->baseAddress) << " bytes" - << frg::endlog; + << object->name << "\"" + << ", base " << (void *)object->baseAddress << ", requested " + << (highest_address - object->baseAddress) << " bytes" << frg::endlog; getAllocator().deallocate(phdr_buffer, ehdr.e_phnum * ehdr.e_phentsize); return LinkerError::outOfMemory; } @@ -515,18 +540,18 @@ frg::expected ObjectRepository::_fetchFromFile(SharedObject * libraryBase += (highest_address + (hugeSize - 1)) & ~(hugeSize - 1); #endif - if(verbose || logBaseAddresses) - mlibc::infoLogger() << "rtld: Loading " << object->name - << " at " << (void *)object->baseAddress << frg::endlog; + if (verbose || logBaseAddresses) + mlibc::infoLogger() << "rtld: Loading " << object->name << " at " + << (void *)object->baseAddress << frg::endlog; // Load all segments. constexpr size_t pageSize = 0x1000; - for(int i = 0; i < ehdr.e_phnum; i++) { + for (int i = 0; i < ehdr.e_phnum; i++) { auto phdr = (elf_phdr *)(phdr_buffer + i * ehdr.e_phentsize); - if(phdr->p_type == PT_LOAD) { + if (phdr->p_type == PT_LOAD) { size_t misalign = phdr->p_vaddr & (pageSize - 1); - if(!phdr->p_memsz) + if (!phdr->p_memsz) continue; __ensure(phdr->p_memsz >= phdr->p_filesz); @@ -539,71 +564,88 @@ frg::expected ObjectRepository::_fetchFromFile(SharedObject * auto total_map_size = (phdr->p_memsz + misalign + pageSize - 1) & ~(pageSize - 1); int prot = 0; - if(phdr->p_flags & PF_R) + if (phdr->p_flags & PF_R) prot |= PROT_READ; - if(phdr->p_flags & PF_W) + if (phdr->p_flags & PF_W) prot |= PROT_WRITE; - if(phdr->p_flags & PF_X) + if (phdr->p_flags & PF_X) prot |= PROT_EXEC; - #if MLIBC_MAP_DSO_SEGMENTS - void *map_pointer; - if(mlibc::sys_vm_map(reinterpret_cast(map_address), - backed_map_size, prot | PROT_WRITE, - MAP_PRIVATE | MAP_FIXED, fd, phdr->p_offset - misalign, &map_pointer)) - __ensure(!"sys_vm_map failed"); - if(total_map_size > backed_map_size) - if(mlibc::sys_vm_map(reinterpret_cast(map_address + backed_map_size), - total_map_size - backed_map_size, prot | PROT_WRITE, - MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0, &map_pointer)) - __ensure(!"sys_vm_map failed"); - - if(mlibc::sys_vm_readahead) - if(mlibc::sys_vm_readahead(reinterpret_cast(map_address), - backed_map_size)) - mlibc::infoLogger() << "mlibc: sys_vm_readahead() failed in ld.so" - << frg::endlog; - - // Clear the trailing area at the end of the backed mapping. - // We do not clear the leading area; programs are not supposed to access it. - memset(reinterpret_cast(map_address + misalign + phdr->p_filesz), - 0, phdr->p_memsz - phdr->p_filesz); - #else - (void)backed_map_size; - - void *map_pointer; - if(mlibc::sys_vm_map(reinterpret_cast(map_address), - total_map_size, prot | PROT_WRITE, - MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0, &map_pointer)) +#if MLIBC_MAP_DSO_SEGMENTS + void *map_pointer; + if (mlibc::sys_vm_map( + reinterpret_cast(map_address), + backed_map_size, + prot | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED, + fd, + phdr->p_offset - misalign, + &map_pointer + )) + __ensure(!"sys_vm_map failed"); + if (total_map_size > backed_map_size) + if (mlibc::sys_vm_map( + reinterpret_cast(map_address + backed_map_size), + total_map_size - backed_map_size, + prot | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, + -1, + 0, + &map_pointer + )) __ensure(!"sys_vm_map failed"); - __ensure(trySeek(fd, phdr->p_offset)); - __ensure(tryReadExactly(fd, reinterpret_cast(map_address) + misalign, - phdr->p_filesz)); - #endif + if (mlibc::sys_vm_readahead) + if (mlibc::sys_vm_readahead(reinterpret_cast(map_address), backed_map_size)) + mlibc::infoLogger() + << "mlibc: sys_vm_readahead() failed in ld.so" << frg::endlog; + + // Clear the trailing area at the end of the backed mapping. + // We do not clear the leading area; programs are not supposed to access it. + memset( + reinterpret_cast(map_address + misalign + phdr->p_filesz), + 0, + phdr->p_memsz - phdr->p_filesz + ); +#else + (void)backed_map_size; + + void *map_pointer; + if (mlibc::sys_vm_map( + reinterpret_cast(map_address), + total_map_size, + prot | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, + -1, + 0, + &map_pointer + )) + __ensure(!"sys_vm_map failed"); + + __ensure(trySeek(fd, phdr->p_offset)); + __ensure( + tryReadExactly(fd, reinterpret_cast(map_address) + misalign, phdr->p_filesz) + ); +#endif // Take care of removing superfluous permissions. - if(mlibc::sys_vm_protect && ((prot & PROT_WRITE) == 0)) - if(mlibc::sys_vm_protect(map_pointer, total_map_size, prot)) + if (mlibc::sys_vm_protect && ((prot & PROT_WRITE) == 0)) + if (mlibc::sys_vm_protect(map_pointer, total_map_size, prot)) mlibc::infoLogger() << "mlibc: sys_vm_protect() failed in ld.so" << frg::endlog; - }else if(phdr->p_type == PT_TLS) { + } else if (phdr->p_type == PT_TLS) { object->tlsSegmentSize = phdr->p_memsz; object->tlsAlignment = phdr->p_align; object->tlsImageSize = phdr->p_filesz; object->tlsImagePtr = (void *)(object->baseAddress + phdr->p_vaddr); - }else if(phdr->p_type == PT_DYNAMIC) { + } else if (phdr->p_type == PT_DYNAMIC) { object->dynamic = (elf_dyn *)(object->baseAddress + phdr->p_vaddr); - }else if(phdr->p_type == PT_INTERP - || phdr->p_type == PT_PHDR - || phdr->p_type == PT_NOTE - || phdr->p_type == PT_RISCV_ATTRIBUTES - || phdr->p_type == PT_GNU_EH_FRAME - || phdr->p_type == PT_GNU_RELRO - || phdr->p_type == PT_GNU_STACK - || phdr->p_type == PT_GNU_PROPERTY) { + } else if (phdr->p_type == PT_INTERP || phdr->p_type == PT_PHDR || + phdr->p_type == PT_NOTE || phdr->p_type == PT_RISCV_ATTRIBUTES || + phdr->p_type == PT_GNU_EH_FRAME || phdr->p_type == PT_GNU_RELRO || + phdr->p_type == PT_GNU_STACK || phdr->p_type == PT_GNU_PROPERTY) { // ignore the phdr - }else{ - mlibc::panicLogger() << "Unexpected PHDR type 0x" - << frg::hex_fmt(phdr->p_type) << " in DSO " << object->name << frg::endlog; + } else { + mlibc::panicLogger() << "Unexpected PHDR type 0x" << frg::hex_fmt(phdr->p_type) + << " in DSO " << object->name << frg::endlog; } } @@ -615,9 +657,9 @@ frg::expected ObjectRepository::_fetchFromFile(SharedObject * // -------------------------------------------------------- void ObjectRepository::_parseDynamic(SharedObject *object) { - if(!object->dynamic) + if (!object->dynamic) mlibc::infoLogger() << "ldso: Object '" << object->name - << "' does not have a dynamic section" << frg::endlog; + << "' does not have a dynamic section" << frg::endlog; __ensure(object->dynamic); // Fix up these offsets to addresses after the loop, since the @@ -627,9 +669,9 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { bool runpath_found = false; frg::optional soname_offset; - for(size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { elf_dyn *dynamic = &object->dynamic[i]; - switch(dynamic->d_tag) { + switch (dynamic->d_tag) { // handle hash table, symbol table and string table case DT_HASH: object->hashStyle = HashStyle::systemV; @@ -652,8 +694,7 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { break; // handle lazy relocation table case DT_PLTGOT: - object->globalOffsetTable = (void **)(object->baseAddress - + dynamic->d_un.d_ptr); + object->globalOffsetTable = (void **)(object->baseAddress + dynamic->d_un.d_ptr); break; case DT_JMPREL: object->lazyRelocTableOffset = dynamic->d_un.d_ptr; @@ -662,9 +703,9 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { object->lazyTableSize = dynamic->d_un.d_val; break; case DT_PLTREL: - if(dynamic->d_un.d_val == DT_RELA) { + if (dynamic->d_un.d_val == DT_RELA) { object->lazyExplicitAddend = true; - }else{ + } else { __ensure(dynamic->d_un.d_val == DT_REL); object->lazyExplicitAddend = false; } @@ -677,11 +718,11 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { object->eagerBinding = true; break; case DT_FLAGS: { - if(dynamic->d_un.d_val & DF_SYMBOLIC) + if (dynamic->d_un.d_val & DF_SYMBOLIC) object->symbolicResolution = true; - if(dynamic->d_un.d_val & DF_STATIC_TLS) + if (dynamic->d_un.d_val & DF_STATIC_TLS) object->haveStaticTls = true; - if(dynamic->d_un.d_val & DF_BIND_NOW) + if (dynamic->d_un.d_val & DF_BIND_NOW) object->eagerBinding = true; auto ignored = DF_BIND_NOW | DF_SYMBOLIC | DF_STATIC_TLS; @@ -689,24 +730,24 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { // Work around https://sourceware.org/bugzilla/show_bug.cgi?id=24673. ignored |= DF_TEXTREL; #else - if(dynamic->d_un.d_val & DF_TEXTREL) + if (dynamic->d_un.d_val & DF_TEXTREL) mlibc::panicLogger() << "\e[31mrtld: DF_TEXTREL is unimplemented" << frg::endlog; #endif - if(dynamic->d_un.d_val & ~ignored) - mlibc::infoLogger() << "\e[31mrtld: DT_FLAGS(" << frg::hex_fmt{dynamic->d_un.d_val & ~ignored} - << ") is not implemented correctly!\e[39m" - << frg::endlog; + if (dynamic->d_un.d_val & ~ignored) + mlibc::infoLogger() + << "\e[31mrtld: DT_FLAGS(" << frg::hex_fmt{dynamic->d_un.d_val & ~ignored} + << ") is not implemented correctly!\e[39m" << frg::endlog; } break; case DT_FLAGS_1: - if(dynamic->d_un.d_val & DF_1_NOW) + if (dynamic->d_un.d_val & DF_1_NOW) object->eagerBinding = true; // The DF_1_PIE flag is informational only. It is used by e.g file(1). // The DF_1_NODELETE flag has a similar effect to RTLD_NODELETE, both of which we // ignore because we don't implement dlclose(). - if(dynamic->d_un.d_val & ~(DF_1_NOW | DF_1_PIE | DF_1_NODELETE)) - mlibc::infoLogger() << "\e[31mrtld: DT_FLAGS_1(" << frg::hex_fmt{dynamic->d_un.d_val} - << ") is not implemented correctly!\e[39m" - << frg::endlog; + if (dynamic->d_un.d_val & ~(DF_1_NOW | DF_1_PIE | DF_1_NODELETE)) + mlibc::infoLogger() + << "\e[31mrtld: DT_FLAGS_1(" << frg::hex_fmt{dynamic->d_un.d_val} + << ") is not implemented correctly!\e[39m" << frg::endlog; break; case DT_RPATH: if (runpath_found) { @@ -719,19 +760,19 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { runpath_offset = dynamic->d_un.d_val; break; case DT_INIT: - if(dynamic->d_un.d_ptr != 0) + if (dynamic->d_un.d_ptr != 0) object->initPtr = (InitFuncPtr)(object->baseAddress + dynamic->d_un.d_ptr); break; case DT_FINI: - if(dynamic->d_un.d_ptr != 0) + if (dynamic->d_un.d_ptr != 0) object->finiPtr = (InitFuncPtr)(object->baseAddress + dynamic->d_un.d_ptr); break; case DT_INIT_ARRAY: - if(dynamic->d_un.d_ptr != 0) + if (dynamic->d_un.d_ptr != 0) object->initArray = (InitFuncPtr *)(object->baseAddress + dynamic->d_un.d_ptr); break; case DT_FINI_ARRAY: - if(dynamic->d_un.d_ptr != 0) + if (dynamic->d_un.d_ptr != 0) object->finiArray = (InitFuncPtr *)(object->baseAddress + dynamic->d_un.d_ptr); break; case DT_INIT_ARRAYSZ: @@ -741,7 +782,7 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { object->finiArraySize = dynamic->d_un.d_val; break; case DT_PREINIT_ARRAY: - if(dynamic->d_un.d_ptr != 0) { + if (dynamic->d_un.d_ptr != 0) { // Only the main object is allowed pre-initializers. __ensure(object->isMainObject); object->preInitArray = (InitFuncPtr *)(object->baseAddress + dynamic->d_un.d_ptr); @@ -764,51 +805,64 @@ void ObjectRepository::_parseDynamic(SharedObject *object) { break; // ignore unimportant tags case DT_NEEDED: // we handle this later - case DT_RELA: case DT_RELASZ: case DT_RELAENT: case DT_RELACOUNT: - case DT_REL: case DT_RELSZ: case DT_RELENT: case DT_RELCOUNT: - case DT_RELR: case DT_RELRSZ: case DT_RELRENT: + case DT_RELA: + case DT_RELASZ: + case DT_RELAENT: + case DT_RELACOUNT: + case DT_REL: + case DT_RELSZ: + case DT_RELENT: + case DT_RELCOUNT: + case DT_RELR: + case DT_RELRSZ: + case DT_RELRENT: case DT_VERSYM: - case DT_VERDEF: case DT_VERDEFNUM: - case DT_VERNEED: case DT_VERNEEDNUM: + case DT_VERDEF: + case DT_VERDEFNUM: + case DT_VERNEED: + case DT_VERNEEDNUM: #ifdef __riscv case DT_TEXTREL: // Work around https://sourceware.org/bugzilla/show_bug.cgi?id=24673. #endif break; - case DT_TLSDESC_PLT: case DT_TLSDESC_GOT: + case DT_TLSDESC_PLT: + case DT_TLSDESC_GOT: break; default: // Ignore unknown entries in the os-specific area as we don't use them. - if(dynamic->d_tag < DT_LOOS || dynamic->d_tag > DT_HIOS) { - mlibc::panicLogger() << "Unexpected dynamic entry " - << (void *)dynamic->d_tag << " in object" << frg::endlog; + if (dynamic->d_tag < DT_LOOS || dynamic->d_tag > DT_HIOS) { + mlibc::panicLogger() << "Unexpected dynamic entry " << (void *)dynamic->d_tag + << " in object" << frg::endlog; } } } - if(runpath_offset) { - object->runPath = reinterpret_cast(object->baseAddress - + object->stringTableOffset + *runpath_offset); + if (runpath_offset) { + object->runPath = reinterpret_cast( + object->baseAddress + object->stringTableOffset + *runpath_offset + ); } - if(soname_offset) { - object->soName = reinterpret_cast(object->baseAddress - + object->stringTableOffset + *soname_offset); + if (soname_offset) { + object->soName = reinterpret_cast( + object->baseAddress + object->stringTableOffset + *soname_offset + ); } } -void ObjectRepository::_discoverDependencies(SharedObject *object, - Scope *localScope, uint64_t rts) { - if(object->isMainObject) { - for(auto preload : *preloads) { +void +ObjectRepository::_discoverDependencies(SharedObject *object, Scope *localScope, uint64_t rts) { + if (object->isMainObject) { + for (auto preload : *preloads) { frg::expected libraryResult; if (preload.find_first('/') == size_t(-1)) { libraryResult = requestObjectWithName(preload, object, globalScope.get(), false, 1); } else { libraryResult = requestObjectAtPath(preload, globalScope.get(), false, 1); } - if(!libraryResult) + if (!libraryResult) mlibc::panicLogger() << "rtld: Could not load preload " << preload << frg::endlog; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Preloading " << preload << frg::endlog; object->dependencies.push_back(libraryResult.value()); @@ -816,17 +870,17 @@ void ObjectRepository::_discoverDependencies(SharedObject *object, } // Load required dynamic libraries. - for(size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { elf_dyn *dynamic = &object->dynamic[i]; - if(dynamic->d_tag != DT_NEEDED) + if (dynamic->d_tag != DT_NEEDED) continue; - const char *library_str = (const char *)(object->baseAddress - + object->stringTableOffset + dynamic->d_un.d_val); + const char *library_str = + (const char *)(object->baseAddress + object->stringTableOffset + dynamic->d_un.d_val); - auto library = requestObjectWithName(frg::string_view{library_str}, - object, localScope, false, rts); - if(!library) + auto library = + requestObjectWithName(frg::string_view{library_str}, object, localScope, false, rts); + if (!library) mlibc::panicLogger() << "Could not satisfy dependency " << library_str << frg::endlog; object->dependencies.push(library.value()); } @@ -841,58 +895,94 @@ void ObjectRepository::_addLoadedObject(SharedObject *object) { // SharedObject // -------------------------------------------------------- -SharedObject::SharedObject(const char *name, frg::string path, - bool is_main_object, Scope *local_scope, uint64_t object_rts) - : name(name, getAllocator()), path(std::move(path)), - interpreterPath(getAllocator()), soName(nullptr), - isMainObject(is_main_object), objectRts(object_rts), inLinkMap(false), - baseAddress(0), localScope(local_scope), dynamic(nullptr), - globalOffsetTable(nullptr), entry(nullptr), tlsSegmentSize(0), - tlsAlignment(0), tlsImageSize(0), tlsImagePtr(nullptr), - tlsInitialized(false), hashTableOffset(0), symbolTableOffset(0), - stringTableOffset(0), lazyRelocTableOffset(0), lazyTableSize(0), - lazyExplicitAddend(false), symbolicResolution(false), - eagerBinding(false), haveStaticTls(false), - dependencies(getAllocator()), tlsModel(TlsModel::null), - tlsOffset(0), globalRts(0), wasLinked(false), - scheduledForInit(false), onInitStack(false), - wasInitialized(false) { } - -SharedObject::SharedObject(const char *name, const char *path, - bool is_main_object, Scope *localScope, uint64_t object_rts) - : SharedObject(name, - frg::string { path, getAllocator() }, - is_main_object, localScope, object_rts) {} +SharedObject::SharedObject( + const char *name, + frg::string path, + bool is_main_object, + Scope *local_scope, + uint64_t object_rts +) + : name(name, getAllocator()), + path(std::move(path)), + interpreterPath(getAllocator()), + soName(nullptr), + isMainObject(is_main_object), + objectRts(object_rts), + inLinkMap(false), + baseAddress(0), + localScope(local_scope), + dynamic(nullptr), + globalOffsetTable(nullptr), + entry(nullptr), + tlsSegmentSize(0), + tlsAlignment(0), + tlsImageSize(0), + tlsImagePtr(nullptr), + tlsInitialized(false), + hashTableOffset(0), + symbolTableOffset(0), + stringTableOffset(0), + lazyRelocTableOffset(0), + lazyTableSize(0), + lazyExplicitAddend(false), + symbolicResolution(false), + eagerBinding(false), + haveStaticTls(false), + dependencies(getAllocator()), + tlsModel(TlsModel::null), + tlsOffset(0), + globalRts(0), + wasLinked(false), + scheduledForInit(false), + onInitStack(false), + wasInitialized(false) {} + +SharedObject::SharedObject( + const char *name, const char *path, bool is_main_object, Scope *localScope, uint64_t object_rts +) + : SharedObject( + name, + frg::string{path, getAllocator()}, + is_main_object, + localScope, + object_rts + ) {} void processLateRelocation(Relocation rel) { // resolve the symbol if there is a symbol frg::optional p; - if(rel.symbol_index()) { - auto symbol = (elf_sym *)(rel.object()->baseAddress + rel.object()->symbolTableOffset - + rel.symbol_index() * sizeof(elf_sym)); + if (rel.symbol_index()) { + auto symbol = (elf_sym *)(rel.object()->baseAddress + rel.object()->symbolTableOffset + + rel.symbol_index() * sizeof(elf_sym)); ObjectSymbol r(rel.object(), symbol); - p = Scope::resolveGlobalOrLocal(*globalScope, rel.object()->localScope, - r.getString(), rel.object()->objectRts, Scope::resolveCopy); + p = Scope::resolveGlobalOrLocal( + *globalScope, + rel.object()->localScope, + r.getString(), + rel.object()->objectRts, + Scope::resolveCopy + ); } - switch(rel.type()) { + switch (rel.type()) { case R_COPY: __ensure(p); memcpy(rel.destination(), (void *)p->virtualAddress(), p->symbol()->st_size); break; -// TODO: R_IRELATIVE also exists on other architectures but will likely need a different implementation. +// TODO: R_IRELATIVE also exists on other architectures but will likely need a different +// implementation. #if defined(__x86_64__) || defined(__i386__) case R_IRELATIVE: { uintptr_t addr = rel.object()->baseAddress + rel.addend_rel(); - auto* fn = reinterpret_cast(addr); + auto *fn = reinterpret_cast(addr); rel.relocate(fn()); } break; #elif defined(__aarch64__) case R_IRELATIVE: { uintptr_t addr = rel.object()->baseAddress + rel.addend_rel(); - auto* fn = reinterpret_cast(addr); + auto *fn = reinterpret_cast(addr); // TODO: the function should get passed AT_HWCAP value. rel.relocate(fn(0)); } break; @@ -910,10 +1000,10 @@ void processLateRelocations(SharedObject *object) { frg::optional rela_offset; frg::optional rela_length; - for(size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { elf_dyn *dynamic = &object->dynamic[i]; - switch(dynamic->d_tag) { + switch (dynamic->d_tag) { case DT_REL: rel_offset = dynamic->d_un.d_ptr; break; @@ -935,19 +1025,19 @@ void processLateRelocations(SharedObject *object) { } } - if(rela_offset && rela_length) { - for(size_t offset = 0; offset < *rela_length; offset += sizeof(elf_rela)) { + if (rela_offset && rela_length) { + for (size_t offset = 0; offset < *rela_length; offset += sizeof(elf_rela)) { auto reloc = (elf_rela *)(object->baseAddress + *rela_offset + offset); auto r = Relocation(object, reloc); processLateRelocation(r); } - } else if(rel_offset && rel_length) { - for(size_t offset = 0; offset < *rel_length; offset += sizeof(elf_rel)) { + } else if (rel_offset && rel_length) { + for (size_t offset = 0; offset < *rel_length; offset += sizeof(elf_rel)) { auto reloc = (elf_rel *)(object->baseAddress + *rel_offset + offset); auto r = Relocation(object, reloc); processLateRelocation(r); } - }else{ + } else { __ensure(!rela_offset && !rela_length); __ensure(!rel_offset && !rel_length); } @@ -957,44 +1047,44 @@ void doInitialize(SharedObject *object) { __ensure(object->wasLinked); __ensure(!object->wasInitialized); - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Initialize " << object->name << frg::endlog; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Running DT_INIT function" << frg::endlog; - if(object->initPtr != nullptr) + if (object->initPtr != nullptr) object->initPtr(); - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Running DT_INIT_ARRAY functions" << frg::endlog; __ensure((object->initArraySize % sizeof(InitFuncPtr)) == 0); - for(size_t i = 0; i < object->initArraySize / sizeof(InitFuncPtr); i++) + for (size_t i = 0; i < object->initArraySize / sizeof(InitFuncPtr); i++) object->initArray[i](); - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Object initialization complete" << frg::endlog; object->wasInitialized = true; } void doDestruct(SharedObject *object) { - if(!object->wasInitialized || object->wasDestroyed) + if (!object->wasInitialized || object->wasDestroyed) return; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Destruct " << object->name << frg::endlog; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Running DT_FINI_ARRAY functions" << frg::endlog; __ensure((object->finiArraySize % sizeof(InitFuncPtr)) == 0); - for(size_t i = object->finiArraySize / sizeof(InitFuncPtr); i > 0; i--) + for (size_t i = object->finiArraySize / sizeof(InitFuncPtr); i > 0; i--) object->finiArray[i - 1](); - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Running DT_FINI function" << frg::endlog; - if(object->finiPtr != nullptr) + if (object->finiPtr != nullptr) object->finiPtr(); - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Object destruction complete" << frg::endlog; object->wasDestroyed = true; } @@ -1003,14 +1093,15 @@ void doDestruct(SharedObject *object) { // RuntimeTlsMap // -------------------------------------------------------- -RuntimeTlsMap::RuntimeTlsMap() -: initialPtr{0}, initialLimit{0}, indices{getAllocator()} { } +RuntimeTlsMap::RuntimeTlsMap() : initialPtr{0}, initialLimit{0}, indices{getAllocator()} {} -void initTlsObjects(Tcb *tcb, const frg::vector &objects, bool checkInitialized) { +void initTlsObjects( + Tcb *tcb, const frg::vector &objects, bool checkInitialized +) { // Initialize TLS segments that follow the static model. - for(auto object : objects) { - if(object->tlsModel == TlsModel::initial) { - if(checkInitialized && object->tlsInitialized) + for (auto object : objects) { + if (object->tlsModel == TlsModel::initial) { + if (checkInitialized && object->tlsInitialized) continue; char *tcb_ptr = reinterpret_cast(tcb); @@ -1024,8 +1115,9 @@ void initTlsObjects(Tcb *tcb, const frg::vector memcpy(tls_ptr, object->tlsImagePtr, object->tlsImageSize); if (verbose) { - mlibc::infoLogger() << "rtld: wrote tls image at " << (void *)tls_ptr - << ", size = 0x" << frg::hex_fmt{object->tlsSegmentSize} << frg::endlog; + mlibc::infoLogger() + << "rtld: wrote tls image at " << (void *)tls_ptr << ", size = 0x" + << frg::hex_fmt{object->tlsSegmentSize} << frg::endlog; } if (checkInitialized) @@ -1069,10 +1161,10 @@ Tcb *allocateTcb() { __ensure((tcbAddress & (alignof(Tcb) - 1)) == 0); if (verbose) { - mlibc::infoLogger() << "rtld: tcb allocated at " << (void *)tcbAddress - << ", size = 0x" << frg::hex_fmt{sizeof(Tcb)} << frg::endlog; - mlibc::infoLogger() << "rtld: tls allocated at " << (void *)tlsAddress - << ", size = 0x" << frg::hex_fmt{tlsInitialSize} << frg::endlog; + mlibc::infoLogger() << "rtld: tcb allocated at " << (void *)tcbAddress << ", size = 0x" + << frg::hex_fmt{sizeof(Tcb)} << frg::endlog; + mlibc::infoLogger() << "rtld: tls allocated at " << (void *)tlsAddress << ", size = 0x" + << frg::hex_fmt{tlsInitialSize} << frg::endlog; } Tcb *tcb_ptr = new ((char *)tcbAddress) Tcb; @@ -1083,17 +1175,19 @@ Tcb *allocateTcb() { tcb_ptr->didExit = 0; tcb_ptr->isJoinable = 1; memset(&tcb_ptr->returnValue, 0, sizeof(tcb_ptr->returnValue)); - tcb_ptr->localKeys = frg::construct>(getAllocator()); + tcb_ptr->localKeys = + frg::construct>(getAllocator()); tcb_ptr->dtvSize = runtimeTlsMap->indices.size(); tcb_ptr->dtvPointers = frg::construct_n(getAllocator(), runtimeTlsMap->indices.size()); memset(tcb_ptr->dtvPointers, 0, sizeof(void *) * runtimeTlsMap->indices.size()); - for(size_t i = 0; i < runtimeTlsMap->indices.size(); ++i) { + for (size_t i = 0; i < runtimeTlsMap->indices.size(); ++i) { auto object = runtimeTlsMap->indices[i]; - if(object->tlsModel != TlsModel::initial) + if (object->tlsModel != TlsModel::initial) continue; if constexpr (tlsAboveTp) { - tcb_ptr->dtvPointers[i] = reinterpret_cast(tcb_ptr) + sizeof(Tcb) + object->tlsOffset; + tcb_ptr->dtvPointers[i] = + reinterpret_cast(tcb_ptr) + sizeof(Tcb) + object->tlsOffset; } else { tcb_ptr->dtvPointers[i] = reinterpret_cast(tcb_ptr) + object->tlsOffset; } @@ -1106,7 +1200,7 @@ void *accessDtv(SharedObject *object) { Tcb *tcb_ptr = mlibc::get_current_tcb(); // We might need to reallocate the DTV. - if(object->tlsIndex >= tcb_ptr->dtvSize) { + if (object->tlsIndex >= tcb_ptr->dtvSize) { // TODO: need to protect runtimeTlsMap against concurrent access. auto ndtv = frg::construct_n(getAllocator(), runtimeTlsMap->indices.size()); memset(ndtv, 0, sizeof(void *) * runtimeTlsMap->indices.size()); @@ -1117,7 +1211,7 @@ void *accessDtv(SharedObject *object) { } // We might need to fill in a new DTV entry. - if(!tcb_ptr->dtvPointers[object->tlsIndex]) { + if (!tcb_ptr->dtvPointers[object->tlsIndex]) { __ensure(object->tlsModel == TlsModel::dynamic); auto buffer = getAllocator().allocate(object->tlsSegmentSize); @@ -1127,8 +1221,8 @@ void *accessDtv(SharedObject *object) { tcb_ptr->dtvPointers[object->tlsIndex] = buffer; if (verbose) { - mlibc::infoLogger() << "rtld: accessDtv wrote tls image at " << buffer - << ", size = 0x" << frg::hex_fmt{object->tlsSegmentSize} << frg::endlog; + mlibc::infoLogger() << "rtld: accessDtv wrote tls image at " << buffer << ", size = 0x" + << frg::hex_fmt{object->tlsSegmentSize} << frg::endlog; } } @@ -1151,12 +1245,12 @@ void *tryAccessDtv(SharedObject *object) { // -------------------------------------------------------- ObjectSymbol::ObjectSymbol(SharedObject *object, const elf_sym *symbol) -: _object(object), _symbol(symbol) { } + : _object(object), + _symbol(symbol) {} const char *ObjectSymbol::getString() { __ensure(_symbol->st_name != 0); - return (const char *)(_object->baseAddress - + _object->stringTableOffset + _symbol->st_name); + return (const char *)(_object->baseAddress + _object->stringTableOffset + _symbol->st_name); } uintptr_t ObjectSymbol::virtualAddress() { @@ -1173,10 +1267,10 @@ uintptr_t ObjectSymbol::virtualAddress() { uint32_t elf64Hash(frg::string_view string) { uint32_t h = 0, g; - for(size_t i = 0; i < string.size(); ++i) { + for (size_t i = 0; i < string.size(); ++i) { h = (h << 4) + (uint32_t)string[i]; g = h & 0xF0000000; - if(g) + if (g) h ^= g >> 24; h &= 0x0FFFFFFF; } @@ -1185,21 +1279,21 @@ uint32_t elf64Hash(frg::string_view string) { } uint32_t gnuHash(frg::string_view string) { - uint32_t h = 5381; - for(size_t i = 0; i < string.size(); ++i) - h = (h << 5) + h + string[i]; - return h; + uint32_t h = 5381; + for (size_t i = 0; i < string.size(); ++i) + h = (h << 5) + h + string[i]; + return h; } // TODO: move this to some namespace or class? frg::optional resolveInObject(SharedObject *object, frg::string_view string) { // Checks if the symbol can be used to satisfy the dependency. - auto eligible = [&] (ObjectSymbol cand) { - if(cand.symbol()->st_shndx == SHN_UNDEF) + auto eligible = [&](ObjectSymbol cand) { + if (cand.symbol()->st_shndx == SHN_UNDEF) return false; auto bind = ELF_ST_BIND(cand.symbol()->st_info); - if(bind != STB_GLOBAL && bind != STB_WEAK && bind != STB_GNU_UNIQUE) + if (bind != STB_GLOBAL && bind != STB_WEAK && bind != STB_GNU_UNIQUE) return false; return true; @@ -1211,17 +1305,20 @@ frg::optional resolveInObject(SharedObject *object, frg::string_vi auto bucket = elf64Hash(string) % num_buckets; auto index = hash_table[2 + bucket]; - while(index != 0) { - ObjectSymbol cand{object, (elf_sym *)(object->baseAddress - + object->symbolTableOffset + index * sizeof(elf_sym))}; - if(eligible(cand) && frg::string_view{cand.getString()} == string) + while (index != 0) { + ObjectSymbol cand{ + object, + (elf_sym *)(object->baseAddress + object->symbolTableOffset + + index * sizeof(elf_sym)) + }; + if (eligible(cand) && frg::string_view{cand.getString()} == string) return cand; index = hash_table[2 + num_buckets + index]; } return frg::optional{}; - }else{ + } else { __ensure(object->hashStyle == HashStyle::gnu); struct GnuTable { @@ -1231,15 +1328,16 @@ frg::optional resolveInObject(SharedObject *object, frg::string_vi uint32_t bloomShift; }; - auto hash_table = reinterpret_cast(object->baseAddress - + object->hashTableOffset); - auto buckets = reinterpret_cast(object->baseAddress - + object->hashTableOffset + sizeof(GnuTable) - + hash_table->bloomSize * sizeof(elf_addr)); - auto chains = reinterpret_cast(object->baseAddress - + object->hashTableOffset + sizeof(GnuTable) - + hash_table->bloomSize * sizeof(elf_addr) - + hash_table->nBuckets * sizeof(uint32_t)); + auto hash_table = + reinterpret_cast(object->baseAddress + object->hashTableOffset); + auto buckets = reinterpret_cast( + object->baseAddress + object->hashTableOffset + sizeof(GnuTable) + + hash_table->bloomSize * sizeof(elf_addr) + ); + auto chains = reinterpret_cast( + object->baseAddress + object->hashTableOffset + sizeof(GnuTable) + + hash_table->bloomSize * sizeof(elf_addr) + hash_table->nBuckets * sizeof(uint32_t) + ); // TODO: Use the bloom filter. @@ -1247,29 +1345,31 @@ frg::optional resolveInObject(SharedObject *object, frg::string_vi auto hash = gnuHash(string); auto index = buckets[hash % hash_table->nBuckets]; - if(!index) + if (!index) return frg::optional{}; - while(true) { + while (true) { // chains[] contains an array of hashes, parallel to the symbol table. auto chash = chains[index - hash_table->symbolOffset]; if ((chash & ~1) == (hash & ~1)) { - ObjectSymbol cand{object, (elf_sym *)(object->baseAddress - + object->symbolTableOffset + index * sizeof(elf_sym))}; - if(eligible(cand) && frg::string_view{cand.getString()} == string) + ObjectSymbol cand{ + object, + (elf_sym *)(object->baseAddress + object->symbolTableOffset + + index * sizeof(elf_sym)) + }; + if (eligible(cand) && frg::string_view{cand.getString()} == string) return cand; } // If we hit the end of the chain, the symbol is not present. - if(chash & 1) + if (chash & 1) return frg::optional{}; index++; } } } -frg::optional Scope::_resolveNext(frg::string_view string, - SharedObject *target) { +frg::optional Scope::_resolveNext(frg::string_view string, SharedObject *target) { // Skip objects until we find the target, and only look for symbols after that. size_t i; for (i = 0; i < _objects.size(); i++) { @@ -1278,24 +1378,24 @@ frg::optional Scope::_resolveNext(frg::string_view string, } if (i == _objects.size()) { - mlibc::infoLogger() << "rtld: object passed to Scope::resolveAfter was not found" << frg::endlog; + mlibc::infoLogger() << "rtld: object passed to Scope::resolveAfter was not found" + << frg::endlog; return frg::optional(); } for (i = i + 1; i < _objects.size(); i++) { - if(_objects[i]->isMainObject) + if (_objects[i]->isMainObject) continue; frg::optional p = resolveInObject(_objects[i], string); - if(p) + if (p) return p; } return frg::optional(); } -Scope::Scope(bool isGlobal) -: isGlobal{isGlobal}, _objects(getAllocator()) { } +Scope::Scope(bool isGlobal) : isGlobal{isGlobal}, _objects(getAllocator()) {} void Scope::appendObject(SharedObject *object) { // Don't insert duplicates. @@ -1307,41 +1407,47 @@ void Scope::appendObject(SharedObject *object) { _objects.push(object); } -frg::optional Scope::resolveGlobalOrLocal(Scope &globalScope, - Scope *localScope, frg::string_view string, uint64_t skipRts, ResolveFlags flags) { +frg::optional Scope::resolveGlobalOrLocal( + Scope &globalScope, + Scope *localScope, + frg::string_view string, + uint64_t skipRts, + ResolveFlags flags +) { auto sym = globalScope.resolveSymbol(string, skipRts, flags | skipGlobalAfterRts); - if(!sym && localScope) + if (!sym && localScope) sym = localScope->resolveSymbol(string, skipRts, flags | skipGlobalAfterRts); return sym; } -frg::optional Scope::resolveGlobalOrLocalNext(Scope &globalScope, - Scope *localScope, frg::string_view string, SharedObject *origin) { +frg::optional Scope::resolveGlobalOrLocalNext( + Scope &globalScope, Scope *localScope, frg::string_view string, SharedObject *origin +) { auto sym = globalScope._resolveNext(string, origin); - if(!sym && localScope) { + if (!sym && localScope) { sym = localScope->_resolveNext(string, origin); } return sym; } // TODO: let this return uintptr_t -frg::optional Scope::resolveSymbol(frg::string_view string, - uint64_t skipRts, ResolveFlags flags) { +frg::optional +Scope::resolveSymbol(frg::string_view string, uint64_t skipRts, ResolveFlags flags) { for (auto object : _objects) { - if((flags & resolveCopy) && object->isMainObject) + if ((flags & resolveCopy) && object->isMainObject) continue; - if((flags & skipGlobalAfterRts) && object->globalRts > skipRts) { + if ((flags & skipGlobalAfterRts) && object->globalRts > skipRts) { // globalRts should be monotone increasing for objects in the global scope, // so as an optimization we can break early here. // TODO: If we implement DT_SYMBOLIC, this assumption fails. - if(isGlobal) + if (isGlobal) break; else continue; } frg::optional p = resolveInObject(object, string); - if(p) + if (p) return p; } @@ -1353,20 +1459,23 @@ frg::optional Scope::resolveSymbol(frg::string_view string, // -------------------------------------------------------- Loader::Loader(Scope *scope, SharedObject *mainExecutable, bool is_initial_link, uint64_t rts) -: _mainExecutable{mainExecutable}, _loadScope{scope}, _isInitialLink{is_initial_link}, - _linkRts{rts}, _linkBfs{getAllocator()}, _initQueue{getAllocator()} { } + : _mainExecutable{mainExecutable}, + _loadScope{scope}, + _isInitialLink{is_initial_link}, + _linkRts{rts}, + _linkBfs{getAllocator()}, + _initQueue{getAllocator()} {} void Loader::_buildLinkBfs(SharedObject *root) { __ensure(_linkBfs.size() == 0); struct Token {}; - using Set = frg::hash_map, MemoryAllocator>; + using Set = frg::hash_map, MemoryAllocator>; Set set{frg::hash{}, getAllocator()}; _linkBfs.push(root); // Loop over indices (not iterators) here: We are adding elements in the loop! - for(size_t i = 0; i < _linkBfs.size(); i++) { + for (size_t i = 0; i < _linkBfs.size(); i++) { auto current = _linkBfs[i]; // At this point the object is loaded and we can fill in its debug struct, @@ -1395,7 +1504,7 @@ void Loader::linkObjects(SharedObject *root) { _buildTlsMaps(); // Promote objects to the desired scope. - for(auto object : _linkBfs) { + for (auto object : _linkBfs) { if (object->globalRts == 0 && _loadScope->isGlobal) object->globalRts = _linkRts; @@ -1403,54 +1512,54 @@ void Loader::linkObjects(SharedObject *root) { } // Process regular relocations. - for(auto object : _linkBfs) { + for (auto object : _linkBfs) { // Some objects have already been linked before. - if(object->objectRts < _linkRts) + if (object->objectRts < _linkRts) continue; - if(object->dynamic == nullptr) + if (object->dynamic == nullptr) continue; - if(verbose) + if (verbose) mlibc::infoLogger() << "rtld: Linking " << object->name << frg::endlog; __ensure(!object->wasLinked); // TODO: Support this. - if(object->symbolicResolution) + if (object->symbolicResolution) mlibc::infoLogger() << "\e[31mrtld: DT_SYMBOLIC is not implemented correctly!\e[39m" - << frg::endlog; + << frg::endlog; _processStaticRelocations(object); _processLazyRelocations(object); } // Process copy relocations. - for(auto object : _linkBfs) { - if(!object->isMainObject) + for (auto object : _linkBfs) { + if (!object->isMainObject) continue; // Some objects have already been linked before. - if(object->objectRts < _linkRts) + if (object->objectRts < _linkRts) continue; - if(object->dynamic == nullptr) + if (object->dynamic == nullptr) continue; processLateRelocations(object); } - for(auto object : _linkBfs) { + for (auto object : _linkBfs) { object->wasLinked = true; - if(object->inLinkMap) + if (object->inLinkMap) continue; - auto linkMap = reinterpret_cast(globalDebugInterface.head); + auto linkMap = reinterpret_cast(globalDebugInterface.head); object->linkMap.prev = linkMap; object->linkMap.next = linkMap->next; - if(linkMap->next) + if (linkMap->next) linkMap->next->prev = &(object->linkMap); linkMap->next = &(object->linkMap); object->inLinkMap = true; @@ -1458,17 +1567,17 @@ void Loader::linkObjects(SharedObject *root) { } void Loader::_buildTlsMaps() { - if(_isInitialLink) { + if (_isInitialLink) { __ensure(runtimeTlsMap->initialPtr == 0); __ensure(runtimeTlsMap->initialLimit == 0); __ensure(!_linkBfs.empty()); __ensure(_linkBfs.front()->isMainObject); - for(auto object : _linkBfs) { + for (auto object : _linkBfs) { __ensure(object->tlsModel == TlsModel::null); - if(object->tlsSegmentSize == 0) + if (object->tlsSegmentSize == 0) continue; // Allocate an index for the object. @@ -1479,7 +1588,7 @@ void Loader::_buildTlsMaps() { if constexpr (tlsAboveTp) { size_t misalign = runtimeTlsMap->initialPtr & (object->tlsAlignment - 1); - if(misalign) + if (misalign) runtimeTlsMap->initialPtr += object->tlsAlignment - misalign; object->tlsOffset = runtimeTlsMap->initialPtr; @@ -1488,26 +1597,26 @@ void Loader::_buildTlsMaps() { runtimeTlsMap->initialPtr += object->tlsSegmentSize; size_t misalign = runtimeTlsMap->initialPtr & (object->tlsAlignment - 1); - if(misalign) + if (misalign) runtimeTlsMap->initialPtr += object->tlsAlignment - misalign; object->tlsOffset = -runtimeTlsMap->initialPtr; } - if(verbose) - mlibc::infoLogger() << "rtld: TLS of " << object->name - << " mapped to 0x" << frg::hex_fmt{object->tlsOffset} - << ", size: " << object->tlsSegmentSize - << ", alignment: " << object->tlsAlignment << frg::endlog; + if (verbose) + mlibc::infoLogger() + << "rtld: TLS of " << object->name << " mapped to 0x" + << frg::hex_fmt{object->tlsOffset} << ", size: " << object->tlsSegmentSize + << ", alignment: " << object->tlsAlignment << frg::endlog; } // Reserve some additional space for future libraries. runtimeTlsMap->initialLimit = runtimeTlsMap->initialPtr + 64; - }else{ - for(auto object : _linkBfs) { - if(object->tlsModel != TlsModel::null) + } else { + for (auto object : _linkBfs) { + if (object->tlsModel != TlsModel::null) continue; - if(object->tlsSegmentSize == 0) + if (object->tlsSegmentSize == 0) continue; // Allocate an index for the object. @@ -1516,12 +1625,12 @@ void Loader::_buildTlsMaps() { // There are some libraries (e.g. Mesa) that require static TLS even though // they expect to be dynamically loaded. - if(object->haveStaticTls) { + if (object->haveStaticTls) { object->tlsModel = TlsModel::initial; if constexpr (tlsAboveTp) { size_t misalign = runtimeTlsMap->initialPtr & (object->tlsAlignment - 1); - if(misalign) + if (misalign) runtimeTlsMap->initialPtr += object->tlsAlignment - misalign; object->tlsOffset = runtimeTlsMap->initialPtr; @@ -1530,22 +1639,23 @@ void Loader::_buildTlsMaps() { runtimeTlsMap->initialPtr += object->tlsSegmentSize; size_t misalign = runtimeTlsMap->initialPtr & (object->tlsAlignment - 1); - if(misalign) + if (misalign) runtimeTlsMap->initialPtr += object->tlsAlignment - misalign; object->tlsOffset = -runtimeTlsMap->initialPtr; } - if(runtimeTlsMap->initialPtr > runtimeTlsMap->initialLimit) - mlibc::panicLogger() << "rtld: Static TLS space exhausted while while" - " allocating TLS for " << object->name << frg::endlog; + if (runtimeTlsMap->initialPtr > runtimeTlsMap->initialLimit) + mlibc::panicLogger() << "rtld: Static TLS space exhausted while while" + " allocating TLS for " + << object->name << frg::endlog; - if(verbose) - mlibc::infoLogger() << "rtld: TLS of " << object->name - << " mapped to 0x" << frg::hex_fmt{object->tlsOffset} - << ", size: " << object->tlsSegmentSize - << ", alignment: " << object->tlsAlignment << frg::endlog; - }else{ + if (verbose) + mlibc::infoLogger() + << "rtld: TLS of " << object->name << " mapped to 0x" + << frg::hex_fmt{object->tlsOffset} << ", size: " << object->tlsSegmentSize + << ", alignment: " << object->tlsAlignment << frg::endlog; + } else { object->tlsModel = TlsModel::dynamic; } } @@ -1562,19 +1672,19 @@ void Loader::initObjects(ObjectRepository *repository) { __ensure(_mainExecutable->isMainObject); __ensure(!_mainExecutable->wasInitialized); __ensure((_mainExecutable->preInitArraySize % sizeof(InitFuncPtr)) == 0); - for(size_t i = 0; i < _mainExecutable->preInitArraySize / sizeof(InitFuncPtr); i++) + for (size_t i = 0; i < _mainExecutable->preInitArraySize / sizeof(InitFuncPtr); i++) _mainExecutable->preInitArray[i](); } // Convert the breadth-first representation to a depth-first post-order representation, // so that every object is initialized *after* its dependencies. - for(auto object : _linkBfs) { - if(!object->scheduledForInit) + for (auto object : _linkBfs) { + if (!object->scheduledForInit) _scheduleInit(object); } - for(auto object : _initQueue) { - if(!object->wasInitialized) { + for (auto object : _initQueue) { + if (!object->wasInitialized) { doInitialize(object); repository->addObjectToDestructQueue(object); } @@ -1590,8 +1700,8 @@ void Loader::_scheduleInit(SharedObject *object) { __ensure(!object->scheduledForInit); object->scheduledForInit = true; - for(size_t i = 0; i < object->dependencies.size(); i++) { - if(!object->dependencies[i]->scheduledForInit) + for (size_t i = 0; i < object->dependencies.size(); i++) { + if (!object->dependencies[i]->scheduledForInit) _scheduleInit(object->dependencies[i]); } @@ -1601,30 +1711,31 @@ void Loader::_scheduleInit(SharedObject *object) { void Loader::_processRelocations(Relocation &rel) { // copy and irelative relocations have to be performed after all other relocations - if(rel.type() == R_COPY || rel.type() == R_IRELATIVE) + if (rel.type() == R_COPY || rel.type() == R_IRELATIVE) return; // resolve the symbol if there is a symbol frg::optional p; - if(rel.symbol_index()) { - auto symbol = (elf_sym *)(rel.object()->baseAddress + rel.object()->symbolTableOffset - + rel.symbol_index() * sizeof(elf_sym)); + if (rel.symbol_index()) { + auto symbol = (elf_sym *)(rel.object()->baseAddress + rel.object()->symbolTableOffset + + rel.symbol_index() * sizeof(elf_sym)); ObjectSymbol r(rel.object(), symbol); - p = Scope::resolveGlobalOrLocal(*globalScope, rel.object()->localScope, - r.getString(), rel.object()->objectRts, 0); - if(!p) { - if(ELF_ST_BIND(symbol->st_info) != STB_WEAK) - mlibc::panicLogger() << "Unresolved load-time symbol " - << r.getString() << " in object " << rel.object()->name << frg::endlog; - - if(verbose) - mlibc::infoLogger() << "rtld: Unresolved weak load-time symbol " - << r.getString() << " in object " << rel.object()->name << frg::endlog; + p = Scope::resolveGlobalOrLocal( + *globalScope, rel.object()->localScope, r.getString(), rel.object()->objectRts, 0 + ); + if (!p) { + if (ELF_ST_BIND(symbol->st_info) != STB_WEAK) + mlibc::panicLogger() << "Unresolved load-time symbol " << r.getString() + << " in object " << rel.object()->name << frg::endlog; + + if (verbose) + mlibc::infoLogger() << "rtld: Unresolved weak load-time symbol " << r.getString() + << " in object " << rel.object()->name << frg::endlog; } } - switch(rel.type()) { + switch (rel.type()) { case R_NONE: break; @@ -1660,13 +1771,13 @@ void Loader::_processRelocations(Relocation &rel) { // sets the first `sizeof(uintptr_t)` bytes of `struct __abi_tls_entry` // this means that we can just use the `SharedObject *` to resolve whatever we need __ensure(!rel.addend_rel()); - if(rel.symbol_index()) { + if (rel.symbol_index()) { __ensure(p); rel.relocate(elf_addr(p->object())); - }else{ - if(stillSlightlyVerbose) + } else { + if (stillSlightlyVerbose) mlibc::infoLogger() << "rtld: Warning: TLS_DTPMOD64 with no symbol in object " - << rel.object()->name << frg::endlog; + << rel.object()->name << frg::endlog; rel.relocate(elf_addr(rel.object())); } } break; @@ -1679,23 +1790,24 @@ void Loader::_processRelocations(Relocation &rel) { uintptr_t off = rel.addend_rel(); ssize_t tls_offset = 0; - if(rel.symbol_index()) { + if (rel.symbol_index()) { __ensure(p); - if(p->object()->tlsModel != TlsModel::initial) - mlibc::panicLogger() << "rtld: In object " << rel.object()->name - << ": Static TLS relocation to symbol " << p->getString() - << " in dynamically loaded object " - << p->object()->name << frg::endlog; + if (p->object()->tlsModel != TlsModel::initial) + mlibc::panicLogger() + << "rtld: In object " << rel.object()->name + << ": Static TLS relocation to symbol " << p->getString() + << " in dynamically loaded object " << p->object()->name << frg::endlog; off += p->symbol()->st_value; tls_offset = p->object()->tlsOffset; - }else{ - if(stillSlightlyVerbose) + } else { + if (stillSlightlyVerbose) mlibc::infoLogger() << "rtld: Warning: TPOFF64 with no symbol" - " in object " << rel.object()->name << frg::endlog; - if(rel.object()->tlsModel != TlsModel::initial) + " in object " + << rel.object()->name << frg::endlog; + if (rel.object()->tlsModel != TlsModel::initial) mlibc::panicLogger() << "rtld: In object " << rel.object()->name - << ": Static TLS relocation to dynamically loaded object " - << rel.object()->name << frg::endlog; + << ": Static TLS relocation to dynamically loaded object " + << rel.object()->name << frg::endlog; tls_offset = rel.object()->tlsOffset; } @@ -1703,8 +1815,7 @@ void Loader::_processRelocations(Relocation &rel) { rel.relocate(off); } break; default: - mlibc::panicLogger() << "Unexpected relocation type " - << (void *) rel.type() << frg::endlog; + mlibc::panicLogger() << "Unexpected relocation type " << (void *)rel.type() << frg::endlog; } } @@ -1718,10 +1829,10 @@ void Loader::_processStaticRelocations(SharedObject *object) { frg::optional relr_offset; frg::optional relr_length; - for(size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; object->dynamic[i].d_tag != DT_NULL; i++) { elf_dyn *dynamic = &object->dynamic[i]; - switch(dynamic->d_tag) { + switch (dynamic->d_tag) { case DT_RELA: rela_offset = dynamic->d_un.d_ptr; break; @@ -1752,19 +1863,19 @@ void Loader::_processStaticRelocations(SharedObject *object) { } } - if(rela_offset && rela_length) { + if (rela_offset && rela_length) { __ensure(!rel_offset && !rel_length); - for(size_t offset = 0; offset < *rela_length; offset += sizeof(elf_rela)) { + for (size_t offset = 0; offset < *rela_length; offset += sizeof(elf_rela)) { auto reloc = (elf_rela *)(object->baseAddress + *rela_offset + offset); auto r = Relocation(object, reloc); _processRelocations(r); } - }else if(rel_offset && rel_length) { + } else if (rel_offset && rel_length) { __ensure(!rela_offset && !rela_length); - for(size_t offset = 0; offset < *rel_length; offset += sizeof(elf_rel)) { + for (size_t offset = 0; offset < *rel_length; offset += sizeof(elf_rel)) { auto reloc = (elf_rel *)(object->baseAddress + *rel_offset + offset); auto r = Relocation(object, reloc); @@ -1772,26 +1883,27 @@ void Loader::_processStaticRelocations(SharedObject *object) { } } - if(relr_offset && relr_length) { + if (relr_offset && relr_length) { elf_addr *addr = nullptr; - for(size_t offset = 0; offset < *relr_length; offset += sizeof(elf_relr)) { + for (size_t offset = 0; offset < *relr_length; offset += sizeof(elf_relr)) { auto entry = *(elf_relr *)(object->baseAddress + *relr_offset + offset); // Even entry indicates the beginning address. - if(!(entry & 1)) { + if (!(entry & 1)) { addr = (elf_addr *)(object->baseAddress + entry); __ensure(addr); *addr++ += object->baseAddress; - }else { - // Odd entry indicates entry is a bitmap of the subsequent locations to be relocated. + } else { + // Odd entry indicates entry is a bitmap of the subsequent locations to be + // relocated. - // The first bit of an entry is always a marker about whether the entry is an address or a bitmap, - // discard it. + // The first bit of an entry is always a marker about whether the entry is an + // address or a bitmap, discard it. entry >>= 1; - for(int i = 0; entry; ++i) { - if(entry & 1) { + for (int i = 0; entry; ++i) { + if (entry & 1) { addr[i] += object->baseAddress; } entry >>= 1; @@ -1811,28 +1923,28 @@ extern "C" void *__mlibcTlsdescDynamic(void *); #endif void Loader::_processLazyRelocations(SharedObject *object) { - if(object->globalOffsetTable == nullptr) { + if (object->globalOffsetTable == nullptr) { __ensure(object->lazyRelocTableOffset == 0); return; } object->globalOffsetTable[1] = object; object->globalOffsetTable[2] = (void *)&pltRelocateStub; - if(!object->lazyTableSize) + if (!object->lazyTableSize) return; // adjust the addresses of JUMP_SLOT relocations __ensure(object->lazyExplicitAddend.has_value()); size_t rel_size = (*object->lazyExplicitAddend) ? sizeof(elf_rela) : sizeof(elf_rel); - for(size_t offset = 0; offset < object->lazyTableSize; offset += rel_size) { + for (size_t offset = 0; offset < object->lazyTableSize; offset += rel_size) { elf_info type; elf_info symbol_index; uintptr_t rel_addr; uintptr_t addend [[maybe_unused]] = 0; - if(*object->lazyExplicitAddend) { + if (*object->lazyExplicitAddend) { auto reloc = (elf_rela *)(object->baseAddress + object->lazyRelocTableOffset + offset); type = ELF_R_TYPE(reloc->r_info); symbol_index = ELF_R_SYM(reloc->r_info); @@ -1847,25 +1959,29 @@ void Loader::_processLazyRelocations(SharedObject *object) { switch (type) { case R_JUMP_SLOT: - if(eagerBinding) { - auto symbol = (elf_sym *)(object->baseAddress + object->symbolTableOffset - + symbol_index * sizeof(elf_sym)); + if (eagerBinding) { + auto symbol = (elf_sym *)(object->baseAddress + object->symbolTableOffset + + symbol_index * sizeof(elf_sym)); ObjectSymbol r(object, symbol); - auto p = Scope::resolveGlobalOrLocal(*globalScope, object->localScope, r.getString(), object->objectRts, 0); + auto p = Scope::resolveGlobalOrLocal( + *globalScope, object->localScope, r.getString(), object->objectRts, 0 + ); - if(!p) { - if(ELF_ST_BIND(symbol->st_info) != STB_WEAK) - mlibc::panicLogger() << "rtld: Unresolved JUMP_SLOT symbol " - << r.getString() << " in object " << object->name << frg::endlog; - - if(verbose) - mlibc::infoLogger() << "rtld: Unresolved weak JUMP_SLOT symbol " - << r.getString() << " in object " << object->name << frg::endlog; + if (!p) { + if (ELF_ST_BIND(symbol->st_info) != STB_WEAK) + mlibc::panicLogger() + << "rtld: Unresolved JUMP_SLOT symbol " << r.getString() + << " in object " << object->name << frg::endlog; + + if (verbose) + mlibc::infoLogger() + << "rtld: Unresolved weak JUMP_SLOT symbol " << r.getString() + << " in object " << object->name << frg::endlog; *((uintptr_t *)rel_addr) = 0; - }else{ + } else { *((uintptr_t *)rel_addr) = p->virtualAddress(); } - }else{ + } else { *((uintptr_t *)rel_addr) += object->baseAddress; } break; @@ -1884,15 +2000,17 @@ void Loader::_processLazyRelocations(SharedObject *object) { SharedObject *target = nullptr; if (symbol_index) { - auto symbol = (elf_sym *)(object->baseAddress + object->symbolTableOffset - + symbol_index * sizeof(elf_sym)); + auto symbol = (elf_sym *)(object->baseAddress + object->symbolTableOffset + + symbol_index * sizeof(elf_sym)); ObjectSymbol r(object, symbol); - auto p = Scope::resolveGlobalOrLocal(*globalScope, object->localScope, r.getString(), object->objectRts, 0); + auto p = Scope::resolveGlobalOrLocal( + *globalScope, object->localScope, r.getString(), object->objectRts, 0 + ); if (!p) { __ensure(ELF_ST_BIND(symbol->st_info) != STB_WEAK); - mlibc::panicLogger() << "rtld: Unresolved TLSDESC for symbol " - << r.getString() << " in object " << object->name << frg::endlog; + mlibc::panicLogger() << "rtld: Unresolved TLSDESC for symbol " << r.getString() + << " in object " << object->name << frg::endlog; } else { target = p->object(); if (p->symbol()) @@ -1935,4 +2053,3 @@ void Loader::_processLazyRelocations(SharedObject *object) { } } } - diff --git a/options/rtld/generic/linker.hpp b/options/rtld/generic/linker.hpp index d8017d204c..002f3c4fa6 100644 --- a/options/rtld/generic/linker.hpp +++ b/options/rtld/generic/linker.hpp @@ -1,10 +1,10 @@ +#include #include #include +#include #include #include -#include -#include #include #include @@ -17,11 +17,7 @@ struct SharedObject; extern uint64_t rtsCounter; -enum class TlsModel { - null, - initial, - dynamic -}; +enum class TlsModel { null, initial, dynamic }; enum class LinkerError { success, @@ -42,29 +38,48 @@ struct ObjectRepository { ObjectRepository(const ObjectRepository &) = delete; - ObjectRepository &operator= (const ObjectRepository &) = delete; + ObjectRepository &operator=(const ObjectRepository &) = delete; // This is primarily used to create a SharedObject for the RTLD itself. - SharedObject *injectObjectFromDts(frg::string_view name, - frg::string path, - uintptr_t base_address, elf_dyn *dynamic, uint64_t rts); + SharedObject *injectObjectFromDts( + frg::string_view name, + frg::string path, + uintptr_t base_address, + elf_dyn *dynamic, + uint64_t rts + ); // This is used to create a SharedObject for the executable that we want to link. - SharedObject *injectObjectFromPhdrs(frg::string_view name, - frg::string path, void *phdr_pointer, - size_t phdr_entry_size, size_t num_phdrs, void *entry_pointer, - uint64_t rts); - - SharedObject *injectStaticObject(frg::string_view name, - frg::string path, void *phdr_pointer, - size_t phdr_entry_size, size_t num_phdrs, void *entry_pointer, - uint64_t rts); - - frg::expected requestObjectWithName(frg::string_view name, - SharedObject *origin, Scope *localScope, bool createScope, uint64_t rts); - - frg::expected requestObjectAtPath(frg::string_view path, - Scope *localScope, bool createScope, uint64_t rts); + SharedObject *injectObjectFromPhdrs( + frg::string_view name, + frg::string path, + void *phdr_pointer, + size_t phdr_entry_size, + size_t num_phdrs, + void *entry_pointer, + uint64_t rts + ); + + SharedObject *injectStaticObject( + frg::string_view name, + frg::string path, + void *phdr_pointer, + size_t phdr_entry_size, + size_t num_phdrs, + void *entry_pointer, + uint64_t rts + ); + + frg::expected requestObjectWithName( + frg::string_view name, + SharedObject *origin, + Scope *localScope, + bool createScope, + uint64_t rts + ); + + frg::expected + requestObjectAtPath(frg::string_view path, Scope *localScope, bool createScope, uint64_t rts); SharedObject *findCaller(void *address); @@ -76,9 +91,14 @@ struct ObjectRepository { // Used by dl_iterate_phdr: stores objects in the order they are loaded. frg::vector loadedObjects; -private: - void _fetchFromPhdrs(SharedObject *object, void *phdr_pointer, - size_t phdr_entry_size, size_t num_phdrs, void *entry_pointer); + private: + void _fetchFromPhdrs( + SharedObject *object, + void *phdr_pointer, + size_t phdr_entry_size, + size_t num_phdrs, + void *entry_pointer + ); frg::expected _fetchFromFile(SharedObject *object, int fd); @@ -88,8 +108,8 @@ struct ObjectRepository { void _addLoadedObject(SharedObject *object); - frg::hash_map, MemoryAllocator> _nameMap; + frg::hash_map, MemoryAllocator> + _nameMap; // Used for destructing the objects, stores all the objects in the order they are initialized. frg::stack _destructQueue; @@ -99,11 +119,7 @@ struct ObjectRepository { // SharedObject // -------------------------------------------------------- -enum class HashStyle { - none, - systemV, - gnu -}; +enum class HashStyle { none, systemV, gnu }; using InitFuncPtr = void (*)(); @@ -126,11 +142,21 @@ struct LinkMap { struct SharedObject { // path is copied - SharedObject(const char *name, frg::string path, - bool is_main_object, Scope *localScope, uint64_t object_rts); - - SharedObject(const char *name, const char *path, bool is_main_object, - Scope *localScope, uint64_t object_rts); + SharedObject( + const char *name, + frg::string path, + bool is_main_object, + Scope *localScope, + uint64_t object_rts + ); + + SharedObject( + const char *name, + const char *path, + bool is_main_object, + Scope *localScope, + uint64_t object_rts + ); frg::string name; frg::string path; @@ -163,7 +189,6 @@ struct SharedObject { size_t finiArraySize = 0; size_t preInitArraySize = 0; - // TODO: read this from the PHDR size_t tlsSegmentSize, tlsAlignment, tlsImageSize; void *tlsImagePtr; @@ -209,67 +234,54 @@ struct SharedObject { }; struct Relocation { - Relocation(SharedObject *object, elf_rela *r) - : object_{object}, type_{Addend::Explicit} { + Relocation(SharedObject *object, elf_rela *r) : object_{object}, type_{Addend::Explicit} { offset_ = r->r_offset; info_ = r->r_info; addend_ = r->r_addend; } - Relocation(SharedObject *object, elf_rel *r) - : object_{object}, type_{Addend::Implicit} { + Relocation(SharedObject *object, elf_rel *r) : object_{object}, type_{Addend::Implicit} { offset_ = r->r_offset; info_ = r->r_info; } - SharedObject *object() { - return object_; - } + SharedObject *object() { return object_; } - elf_info type() const { - return ELF_R_TYPE(info_); - } + elf_info type() const { return ELF_R_TYPE(info_); } - elf_info symbol_index() const { - return ELF_R_SYM(info_); - } + elf_info symbol_index() const { return ELF_R_SYM(info_); } elf_addr addend_rel() { - switch(type_) { - case Addend::Explicit: - return addend_; - case Addend::Implicit: { - auto ptr = reinterpret_cast(object_->baseAddress + offset_); - return *ptr; - } + switch (type_) { + case Addend::Explicit: + return addend_; + case Addend::Implicit: { + auto ptr = reinterpret_cast(object_->baseAddress + offset_); + return *ptr; + } } __builtin_unreachable(); } elf_addr addend_norel() { - switch(type_) { - case Addend::Explicit: - return addend_; - case Addend::Implicit: - return 0; + switch (type_) { + case Addend::Explicit: + return addend_; + case Addend::Implicit: + return 0; } __builtin_unreachable(); } - void *destination() { - return reinterpret_cast(object_->baseAddress + offset_); - } + void *destination() { return reinterpret_cast(object_->baseAddress + offset_); } void relocate(elf_addr addr) { auto ptr = destination(); memcpy(ptr, &addr, sizeof(addr)); } -private: - enum class Addend { - Implicit, - Explicit - }; + private: + enum class Addend { Implicit, Explicit }; SharedObject *object_; Addend type_; @@ -301,7 +313,9 @@ struct RuntimeTlsMap { extern frg::manual_box runtimeTlsMap; Tcb *allocateTcb(); -void initTlsObjects(Tcb *tcb, const frg::vector &objects, bool checkInitialized); +void initTlsObjects( + Tcb *tcb, const frg::vector &objects, bool checkInitialized +); void *accessDtv(SharedObject *object); // Tries to access the DTV, if not allocated, or object doesn't have // PT_TLS, return nullptr. @@ -314,19 +328,15 @@ void *tryAccessDtv(SharedObject *object); struct ObjectSymbol { ObjectSymbol(SharedObject *object, const elf_sym *symbol); - SharedObject *object() { - return _object; - } + SharedObject *object() { return _object; } - const elf_sym *symbol() { - return _symbol; - } + const elf_sym *symbol() { return _symbol; } const char *getString(); uintptr_t virtualAddress(); -private: + private: SharedObject *_object; const elf_sym *_symbol; }; @@ -342,22 +352,30 @@ struct Scope { static inline constexpr ResolveFlags resolveCopy = 1; static inline constexpr ResolveFlags skipGlobalAfterRts = 1 << 1; - static frg::optional resolveGlobalOrLocal(Scope &globalScope, - Scope *localScope, frg::string_view string, uint64_t skipRts, ResolveFlags flags); - static frg::optional resolveGlobalOrLocalNext(Scope &globalScope, - Scope *localScope, frg::string_view string, SharedObject *origin); + static frg::optional resolveGlobalOrLocal( + Scope &globalScope, + Scope *localScope, + frg::string_view string, + uint64_t skipRts, + ResolveFlags flags + ); + static frg::optional resolveGlobalOrLocalNext( + Scope &globalScope, Scope *localScope, frg::string_view string, SharedObject *origin + ); Scope(bool isGlobal = false); void appendObject(SharedObject *object); - frg::optional resolveSymbol(frg::string_view string, uint64_t skipRts, ResolveFlags flags); + frg::optional + resolveSymbol(frg::string_view string, uint64_t skipRts, ResolveFlags flags); bool isGlobal; -private: + private: frg::optional _resolveNext(frg::string_view string, SharedObject *target); -public: // TODO: Make this private again. (Was made public for __dlapi_reverse()). + + public: // TODO: Make this private again. (Was made public for __dlapi_reverse()). frg::vector _objects; }; @@ -368,13 +386,13 @@ extern frg::manual_box globalScope; // -------------------------------------------------------- struct Loader { -public: + public: Loader(Scope *scope, SharedObject *mainExecutable, bool is_initial_link, uint64_t rts); -public: + public: void linkObjects(SharedObject *root); -private: + private: void _buildLinkBfs(SharedObject *root); void _buildTlsMaps(); @@ -383,13 +401,13 @@ struct Loader { void _processRelocations(Relocation &rel); -public: + public: void initObjects(ObjectRepository *repository); -private: + private: void _scheduleInit(SharedObject *object); -private: + private: SharedObject *_mainExecutable; Scope *_loadScope; bool _isInitialLink; @@ -411,4 +429,3 @@ extern "C" void pltRelocateStub() __attribute__((__visibility__("hidden"))); // -------------------------------------------------------- void *rtld_auxvector(); - diff --git a/options/rtld/generic/main.cpp b/options/rtld/generic/main.cpp index de7995b924..ca45a44717 100644 --- a/options/rtld/generic/main.cpp +++ b/options/rtld/generic/main.cpp @@ -6,13 +6,12 @@ #include #include +#include #include -#include -#include #include +#include +#include #include -#include -#include #include "elf.hpp" #include "linker.hpp" @@ -21,8 +20,8 @@ #include #endif -#define HIDDEN __attribute__((__visibility__("hidden"))) -#define EXPORT __attribute__((__visibility__("default"))) +#define HIDDEN __attribute__((__visibility__("hidden"))) +#define EXPORT __attribute__((__visibility__("default"))) static constexpr bool logEntryExit = false; static constexpr bool logStartup = false; @@ -34,9 +33,9 @@ extern HIDDEN elf_dyn _DYNAMIC[]; #endif namespace mlibc { - // Declared in options/internal/mlibc/tcb.hpp. - bool tcb_available_flag = false; -} +// Declared in options/internal/mlibc/tcb.hpp. +bool tcb_available_flag = false; +} // namespace mlibc mlibc::RtldConfig rtldConfig; @@ -49,7 +48,9 @@ frg::manual_box globalScope; frg::manual_box runtimeTlsMap; // We use a small vector to avoid memory allocation for the default library paths -frg::manual_box> libraryPaths; +frg::manual_box< + frg::small_vector> + libraryPaths; frg::manual_box> preloads; @@ -87,29 +88,41 @@ extern "C" void relocateSelf() { size_t rel_size = 0; size_t relr_offset = 0; size_t relr_size = 0; - for(size_t i = 0; _DYNAMIC[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; _DYNAMIC[i].d_tag != DT_NULL; i++) { auto ent = &_DYNAMIC[i]; - switch(ent->d_tag) { - case DT_REL: rel_offset = ent->d_un.d_ptr; break; - case DT_RELSZ: rel_size = ent->d_un.d_val; break; - case DT_RELA: rela_offset = ent->d_un.d_ptr; break; - case DT_RELASZ: rela_size = ent->d_un.d_val; break; - case DT_RELR: relr_offset = ent->d_un.d_ptr; break; - case DT_RELRSZ: relr_size = ent->d_un.d_val; break; + switch (ent->d_tag) { + case DT_REL: + rel_offset = ent->d_un.d_ptr; + break; + case DT_RELSZ: + rel_size = ent->d_un.d_val; + break; + case DT_RELA: + rela_offset = ent->d_un.d_ptr; + break; + case DT_RELASZ: + rela_size = ent->d_un.d_val; + break; + case DT_RELR: + relr_offset = ent->d_un.d_ptr; + break; + case DT_RELRSZ: + relr_size = ent->d_un.d_val; + break; } } auto ldso_base = getLdsoBase(); - for(size_t disp = 0; disp < rela_size; disp += sizeof(elf_rela)) { + for (size_t disp = 0; disp < rela_size; disp += sizeof(elf_rela)) { auto reloc = reinterpret_cast(ldso_base + rela_offset + disp); auto type = ELF_R_TYPE(reloc->r_info); - if(ELF_R_SYM(reloc->r_info)) + if (ELF_R_SYM(reloc->r_info)) __builtin_trap(); auto p = reinterpret_cast(ldso_base + reloc->r_offset); - switch(type) { + switch (type) { case R_RELATIVE: *p = ldso_base + reloc->r_addend; break; @@ -118,15 +131,15 @@ extern "C" void relocateSelf() { } } - for(size_t disp = 0; disp < rel_size; disp += sizeof(elf_rel)) { + for (size_t disp = 0; disp < rel_size; disp += sizeof(elf_rel)) { auto reloc = reinterpret_cast(ldso_base + rel_offset + disp); auto type = ELF_R_TYPE(reloc->r_info); - if(ELF_R_SYM(reloc->r_info)) + if (ELF_R_SYM(reloc->r_info)) __builtin_trap(); auto p = reinterpret_cast(ldso_base + reloc->r_offset); - switch(type) { + switch (type) { case R_RELATIVE: *p += ldso_base; break; @@ -136,23 +149,23 @@ extern "C" void relocateSelf() { } elf_addr *addr = nullptr; - for(size_t disp = 0; disp < relr_size; disp += sizeof(elf_relr)) { + for (size_t disp = 0; disp < relr_size; disp += sizeof(elf_relr)) { auto entry = *(elf_relr *)(ldso_base + relr_offset + disp); // Even entry indicates the beginning address. - if(!(entry & 1)) { + if (!(entry & 1)) { addr = (elf_addr *)(ldso_base + entry); __ensure(addr); *addr++ += ldso_base; - }else { + } else { // Odd entry indicates entry is a bitmap of the subsequent locations to be relocated. - // The first bit of an entry is always a marker about whether the entry is an address or a bitmap, - // discard it. + // The first bit of an entry is always a marker about whether the entry is an address or + // a bitmap, discard it. entry >>= 1; - for(int i = 0; entry; ++i) { - if(entry & 1) { + for (int i = 0; entry; ++i) { + if (entry & 1) { addr[i] += ldso_base; } entry >>= 1; @@ -168,20 +181,24 @@ extern "C" void relocateSelf() { extern "C" void relocateSelf68k(elf_dyn *dynamic, uintptr_t ldso_base) { size_t rela_offset = 0; size_t rela_size = 0; - for(size_t i = 0; dynamic[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; dynamic[i].d_tag != DT_NULL; i++) { auto ent = &dynamic[i]; - switch(ent->d_tag) { - case DT_RELA: rela_offset = ent->d_un.d_ptr; break; - case DT_RELASZ: rela_size = ent->d_un.d_val; break; + switch (ent->d_tag) { + case DT_RELA: + rela_offset = ent->d_un.d_ptr; + break; + case DT_RELASZ: + rela_size = ent->d_un.d_val; + break; } } - for(size_t disp = 0; disp < rela_size; disp += sizeof(elf_rela)) { + for (size_t disp = 0; disp < rela_size; disp += sizeof(elf_rela)) { auto reloc = reinterpret_cast(ldso_base + rela_offset + disp); auto type = ELF_R_TYPE(reloc->r_info); auto p = reinterpret_cast(ldso_base + reloc->r_offset); - switch(type) { + switch (type) { case R_NONE: break; @@ -199,74 +216,78 @@ extern "C" void relocateSelf68k(elf_dyn *dynamic, uintptr_t ldso_base) { extern "C" void *lazyRelocate(SharedObject *object, unsigned int rel_index) { __ensure(object->lazyExplicitAddend); - auto reloc = (elf_rela *)(object->baseAddress + object->lazyRelocTableOffset - + rel_index * sizeof(elf_rela)); + auto reloc = (elf_rela *)(object->baseAddress + object->lazyRelocTableOffset + + rel_index * sizeof(elf_rela)); auto type = ELF_R_TYPE(reloc->r_info); auto symbol_index = ELF_R_SYM(reloc->r_info); __ensure(type == R_X86_64_JUMP_SLOT); __ensure(ELF_CLASS == ELFCLASS64); - auto symbol = (elf_sym *)(object->baseAddress + object->symbolTableOffset - + symbol_index * sizeof(elf_sym)); + auto symbol = (elf_sym *)(object->baseAddress + object->symbolTableOffset + + symbol_index * sizeof(elf_sym)); ObjectSymbol r(object, symbol); - auto p = Scope::resolveGlobalOrLocal(*globalScope, object->localScope, r.getString(), object->objectRts, 0); - if(!p) + auto p = Scope::resolveGlobalOrLocal( + *globalScope, object->localScope, r.getString(), object->objectRts, 0 + ); + if (!p) mlibc::panicLogger() << "Unresolved JUMP_SLOT symbol" << frg::endlog; - //mlibc::infoLogger() << "Lazy relocation to " << symbol_str + // mlibc::infoLogger() << "Lazy relocation to " << symbol_str // << " resolved to " << pointer << frg::endlog; *(uint64_t *)(object->baseAddress + reloc->r_offset) = p->virtualAddress(); return (void *)p->virtualAddress(); } -extern "C" [[ gnu::visibility("default") ]] void *__rtld_allocateTcb() { +extern "C" [[gnu::visibility("default")]] void *__rtld_allocateTcb() { auto tcb = allocateTcb(); initTlsObjects(tcb, globalScope->_objects, false); return tcb; } extern "C" { - [[ gnu::visibility("hidden") ]] void dl_debug_state() { - // This function is used to signal changes in the debugging link map, - // GDB just sets a breakpoint on this function and we can call it - // everytime we update the link map. We don't need to implement - // anything besides defining and calling it. - } +[[gnu::visibility("hidden")]] void dl_debug_state() { + // This function is used to signal changes in the debugging link map, + // GDB just sets a breakpoint on this function and we can call it + // everytime we update the link map. We don't need to implement + // anything besides defining and calling it. +} } -extern "C" [[gnu::alias("dl_debug_state"), gnu::visibility("default")]] void _dl_debug_state() noexcept; +extern "C" [[gnu::alias("dl_debug_state"), gnu::visibility("default")]] void +_dl_debug_state() noexcept; // This symbol can be used by GDB to find the global interface structure -[[ gnu::visibility("default") ]] DebugInterface *_dl_debug_addr = &globalDebugInterface; +[[gnu::visibility("default")]] DebugInterface *_dl_debug_addr = &globalDebugInterface; -static frg::vector parseList(frg::string_view paths, frg::string_view separators) { +static frg::vector +parseList(frg::string_view paths, frg::string_view separators) { frg::vector list{getAllocator()}; size_t p = 0; - while(p < paths.size()) { + while (p < paths.size()) { size_t s; // Offset of next colon or end of string. - if(size_t cs = paths.find_first_of(separators, p); cs != size_t(-1)) { + if (size_t cs = paths.find_first_of(separators, p); cs != size_t(-1)) { s = cs; - }else{ + } else { s = paths.size(); } auto path = paths.sub_string(p, s - p); p = s + 1; - if(path.size() == 0) + if (path.size() == 0) continue; - if(path.ends_with("/")) { + if (path.ends_with("/")) { size_t i = path.size() - 1; - while(i > 0 && path[i] == '/') + while (i > 0 && path[i] == '/') i--; path = path.sub_string(0, i + 1); } - if(path == "/") + if (path == "/") path = ""; list.push_back(path); @@ -281,7 +302,7 @@ static constexpr uint64_t supportedDtFlags1 = DF_1_NOW; #endif extern "C" void *interpreterMain(uintptr_t *entry_stack) { - if(logEntryExit) + if (logEntryExit) mlibc::infoLogger() << "Entering ld.so" << frg::endlog; entryStack = entry_stack; runtimeTlsMap.initialize(); @@ -297,15 +318,15 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { const char *execfn = "(executable)"; #ifndef MLIBC_STATIC_BUILD - using ctor_fn = void(*)(void); + using ctor_fn = void (*)(void); ctor_fn *ldso_ctors = nullptr; size_t num_ldso_ctors = 0; auto ldso_base = getLdsoBase(); - if(logStartup) { - mlibc::infoLogger() << "ldso: Own base address is: 0x" - << frg::hex_fmt(ldso_base) << frg::endlog; + if (logStartup) { + mlibc::infoLogger() << "ldso: Own base address is: 0x" << frg::hex_fmt(ldso_base) + << frg::endlog; mlibc::infoLogger() << "ldso: Own dynamic section is at: " << _DYNAMIC << frg::endlog; } @@ -320,13 +341,21 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { // Here, we make sure that the dynamic linker does not need relocations itself. uintptr_t strtab_offset = 0; uintptr_t soname_str = 0; - for(size_t i = 0; _DYNAMIC[i].d_tag != DT_NULL; i++) { + for (size_t i = 0; _DYNAMIC[i].d_tag != DT_NULL; i++) { auto ent = &_DYNAMIC[i]; - switch(ent->d_tag) { - case DT_STRTAB: strtab_offset = ent->d_un.d_ptr; break; - case DT_SONAME: soname_str = ent->d_un.d_val; break; - case DT_INIT_ARRAY: ldso_ctors = reinterpret_cast(ent->d_un.d_ptr + ldso_base); break; - case DT_INIT_ARRAYSZ: num_ldso_ctors = ent->d_un.d_val / sizeof(ctor_fn); break; + switch (ent->d_tag) { + case DT_STRTAB: + strtab_offset = ent->d_un.d_ptr; + break; + case DT_SONAME: + soname_str = ent->d_un.d_val; + break; + case DT_INIT_ARRAY: + ldso_ctors = reinterpret_cast(ent->d_un.d_ptr + ldso_base); + break; + case DT_INIT_ARRAYSZ: + num_ldso_ctors = ent->d_un.d_val / sizeof(ctor_fn); + break; case DT_HASH: case DT_GNU_HASH: case DT_STRSZ: @@ -348,21 +377,26 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { case DT_BIND_NOW: continue; case DT_FLAGS: { - if((ent->d_un.d_val & ~supportedDtFlags) == 0) { + if ((ent->d_un.d_val & ~supportedDtFlags) == 0) { continue; } - mlibc::panicLogger() << "rtld: unexpected DT_FLAGS value of " << frg::hex_fmt(ent->d_un.d_val) << " in program interpreter" << frg::endlog; + mlibc::panicLogger() << "rtld: unexpected DT_FLAGS value of " + << frg::hex_fmt(ent->d_un.d_val) << " in program interpreter" + << frg::endlog; break; } case DT_FLAGS_1: { - if((ent->d_un.d_val & ~supportedDtFlags1) == 0) { + if ((ent->d_un.d_val & ~supportedDtFlags1) == 0) { continue; } - mlibc::panicLogger() << "rtld: unexpected DT_FLAGS_1 value of " << frg::hex_fmt(ent->d_un.d_val) << " in program interpreter" << frg::endlog; + mlibc::panicLogger() << "rtld: unexpected DT_FLAGS_1 value of " + << frg::hex_fmt(ent->d_un.d_val) << " in program interpreter" + << frg::endlog; break; } default: - mlibc::panicLogger() << "rtld: unexpected dynamic entry " << ent->d_tag << " in program interpreter" << frg::endlog; + mlibc::panicLogger() << "rtld: unexpected dynamic entry " << ent->d_tag + << " in program interpreter" << frg::endlog; } } __ensure(strtab_offset); @@ -373,23 +407,24 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { aux += *aux + 1; // First, we skip argc and all args. __ensure(!*aux); aux++; - while(*aux) { // Loop through the environment. + while (*aux) { // Loop through the environment. auto env = reinterpret_cast(*aux); frg::string_view view{env}; size_t s = view.find_first('='); - if(s == size_t(-1)) - mlibc::panicLogger() << "rtld: environment '" << env << "' is missing a '='" << frg::endlog; + if (s == size_t(-1)) + mlibc::panicLogger() << "rtld: environment '" << env << "' is missing a '='" + << frg::endlog; auto name = view.sub_string(0, s); auto value = const_cast(view.data() + s + 1); - if(name == "LD_SHOW_AUXV" && *value && *value != '0') { + if (name == "LD_SHOW_AUXV" && *value && *value != '0') { ldShowAuxv = true; - }else if(name == "LD_LIBRARY_PATH" && *value) { - for(auto path : parseList(value, ":;")) + } else if (name == "LD_LIBRARY_PATH" && *value) { + for (auto path : parseList(value, ":;")) libraryPaths->push_back(path); - }else if(name == "LD_PRELOAD" && *value) { + } else if (name == "LD_PRELOAD" && *value) { *preloads = parseList(value, " :"); } @@ -402,66 +437,122 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { } // Parse the actual vector. - while(true) { + while (true) { auto value = aux + 1; - if(!(*aux)) + if (!(*aux)) break; - if(ldShowAuxv) { - switch(*aux) { - case AT_PHDR: mlibc::infoLogger() << "AT_PHDR: 0x" << frg::hex_fmt{*value} << frg::endlog; break; - case AT_PHENT: mlibc::infoLogger() << "AT_PHENT: " << *value << frg::endlog; break; - case AT_PHNUM: mlibc::infoLogger() << "AT_PHNUM: " << *value << frg::endlog; break; - case AT_ENTRY: mlibc::infoLogger() << "AT_ENTRY: 0x" << frg::hex_fmt{*value} << frg::endlog; break; - case AT_PAGESZ: mlibc::infoLogger() << "AT_PAGESZ: " << *value << frg::endlog; break; - case AT_BASE: mlibc::infoLogger() << "AT_BASE: 0x" << frg::hex_fmt{*value} << frg::endlog; break; - case AT_FLAGS: mlibc::infoLogger() << "AT_FLAGS: 0x" << frg::hex_fmt{*value} << frg::endlog; break; - case AT_NOTELF: mlibc::infoLogger() << "AT_NOTELF: " << frg::hex_fmt{*value} << frg::endlog; break; - case AT_UID: mlibc::infoLogger() << "AT_UID: " << *value << frg::endlog; break; - case AT_EUID: mlibc::infoLogger() << "AT_EUID: " << *value << frg::endlog; break; - case AT_GID: mlibc::infoLogger() << "AT_GID: " << *value << frg::endlog; break; - case AT_EGID: mlibc::infoLogger() << "AT_EGID: " << *value << frg::endlog; break; + if (ldShowAuxv) { + switch (*aux) { + case AT_PHDR: + mlibc::infoLogger() << "AT_PHDR: 0x" << frg::hex_fmt{*value} << frg::endlog; + break; + case AT_PHENT: + mlibc::infoLogger() << "AT_PHENT: " << *value << frg::endlog; + break; + case AT_PHNUM: + mlibc::infoLogger() << "AT_PHNUM: " << *value << frg::endlog; + break; + case AT_ENTRY: + mlibc::infoLogger() << "AT_ENTRY: 0x" << frg::hex_fmt{*value} << frg::endlog; + break; + case AT_PAGESZ: + mlibc::infoLogger() << "AT_PAGESZ: " << *value << frg::endlog; + break; + case AT_BASE: + mlibc::infoLogger() << "AT_BASE: 0x" << frg::hex_fmt{*value} << frg::endlog; + break; + case AT_FLAGS: + mlibc::infoLogger() << "AT_FLAGS: 0x" << frg::hex_fmt{*value} << frg::endlog; + break; + case AT_NOTELF: + mlibc::infoLogger() << "AT_NOTELF: " << frg::hex_fmt{*value} << frg::endlog; + break; + case AT_UID: + mlibc::infoLogger() << "AT_UID: " << *value << frg::endlog; + break; + case AT_EUID: + mlibc::infoLogger() << "AT_EUID: " << *value << frg::endlog; + break; + case AT_GID: + mlibc::infoLogger() << "AT_GID: " << *value << frg::endlog; + break; + case AT_EGID: + mlibc::infoLogger() << "AT_EGID: " << *value << frg::endlog; + break; #ifdef AT_PLATFORM - case AT_PLATFORM: mlibc::infoLogger() << "AT_PLATFORM: " << reinterpret_cast(*value) << frg::endlog; break; + case AT_PLATFORM: + mlibc::infoLogger() + << "AT_PLATFORM: " << reinterpret_cast(*value) << frg::endlog; + break; #endif #ifdef AT_HWCAP - case AT_HWCAP: mlibc::infoLogger() << "AT_HWCAP: " << frg::hex_fmt{*value} << frg::endlog; break; + case AT_HWCAP: + mlibc::infoLogger() << "AT_HWCAP: " << frg::hex_fmt{*value} << frg::endlog; + break; #endif #ifdef AT_CLKTCK - case AT_CLKTCK: mlibc::infoLogger() << "AT_CLKTCK: " << *value << frg::endlog; break; + case AT_CLKTCK: + mlibc::infoLogger() << "AT_CLKTCK: " << *value << frg::endlog; + break; #endif #ifdef AT_FPUCW - case AT_FPUCW: mlibc::infoLogger() << "AT_FPUCW: " << frg::hex_fmt{*value} << frg::endlog; break; + case AT_FPUCW: + mlibc::infoLogger() << "AT_FPUCW: " << frg::hex_fmt{*value} << frg::endlog; + break; #endif #ifdef AT_SECURE - case AT_SECURE: mlibc::infoLogger() << "AT_SECURE: " << *value << frg::endlog; break; + case AT_SECURE: + mlibc::infoLogger() << "AT_SECURE: " << *value << frg::endlog; + break; #endif #ifdef AT_RANDOM - case AT_RANDOM: mlibc::infoLogger() << "AT_RANDOM: 0x" << frg::hex_fmt{*value} << frg::endlog; break; + case AT_RANDOM: + mlibc::infoLogger() << "AT_RANDOM: 0x" << frg::hex_fmt{*value} << frg::endlog; + break; #endif #ifdef AT_EXECFN - case AT_EXECFN: mlibc::infoLogger() << "AT_EXECFN: " << reinterpret_cast(*value) << frg::endlog; break; + case AT_EXECFN: + mlibc::infoLogger() + << "AT_EXECFN: " << reinterpret_cast(*value) << frg::endlog; + break; #endif #ifdef AT_SYSINFO_EHDR - case AT_SYSINFO_EHDR: mlibc::infoLogger() << "AT_SYSINFO_EHDR: 0x" << frg::hex_fmt{*value} << frg::endlog; break; + case AT_SYSINFO_EHDR: + mlibc::infoLogger() << "AT_SYSINFO_EHDR: 0x" << frg::hex_fmt{*value} << frg::endlog; + break; #endif } } // TODO: Whitelist auxiliary vector entries here? - switch(*aux) { - case AT_PHDR: phdr_pointer = reinterpret_cast(*value); break; - case AT_PHENT: phdr_entry_size = *value; break; - case AT_PHNUM: phdr_count = *value; break; - case AT_ENTRY: entry_pointer = reinterpret_cast(*value); break; - case AT_EXECFN: execfn = reinterpret_cast(*value); break; - case AT_RANDOM: stack_entropy = reinterpret_cast(*value); break; - case AT_SECURE: rtldConfig.secureRequired = reinterpret_cast(*value); break; + switch (*aux) { + case AT_PHDR: + phdr_pointer = reinterpret_cast(*value); + break; + case AT_PHENT: + phdr_entry_size = *value; + break; + case AT_PHNUM: + phdr_count = *value; + break; + case AT_ENTRY: + entry_pointer = reinterpret_cast(*value); + break; + case AT_EXECFN: + execfn = reinterpret_cast(*value); + break; + case AT_RANDOM: + stack_entropy = reinterpret_cast(*value); + break; + case AT_SECURE: + rtldConfig.secureRequired = reinterpret_cast(*value); + break; } aux += 2; } - globalDebugInterface.base = reinterpret_cast(ldso_base); + globalDebugInterface.base = reinterpret_cast(ldso_base); // This is here because libgcc will add a global constructor on glibc Linux // (which is what it believes we are due to the aarch64-linux-gnu toolchain) @@ -471,33 +562,31 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { // using the host toolchain. #if defined(__aarch64__) && defined(__gnu_linux__) for (size_t i = 0; i < num_ldso_ctors; i++) { - if(logStartup) + if (logStartup) mlibc::infoLogger() << "ldso: Running own constructor at " - << reinterpret_cast(ldso_ctors[i]) - << frg::endlog; + << reinterpret_cast(ldso_ctors[i]) << frg::endlog; ldso_ctors[i](); } #else if (num_ldso_ctors > 0) { - mlibc::panicLogger() << "ldso: Found unexpected own global constructor(s), init_array starts at: " - << ldso_ctors - << frg::endlog; + mlibc::panicLogger( + ) << "ldso: Found unexpected own global constructor(s), init_array starts at: " + << ldso_ctors << frg::endlog; } #endif #else - auto ehdr = reinterpret_cast(__ehdr_start); - phdr_pointer = reinterpret_cast((uintptr_t)ehdr->e_phoff + (uintptr_t)ehdr); + auto ehdr = reinterpret_cast(__ehdr_start); + phdr_pointer = reinterpret_cast((uintptr_t)ehdr->e_phoff + (uintptr_t)ehdr); phdr_entry_size = ehdr->e_phentsize; phdr_count = ehdr->e_phnum; - entry_pointer = reinterpret_cast(ehdr->e_entry); + entry_pointer = reinterpret_cast(ehdr->e_entry); #endif __ensure(phdr_pointer); __ensure(entry_pointer); - if(logStartup) - mlibc::infoLogger() << "ldso: Executable PHDRs are at " << phdr_pointer - << frg::endlog; + if (logStartup) + mlibc::infoLogger() << "ldso: Executable PHDRs are at " << phdr_pointer << frg::endlog; // perform the initial dynamic linking initialRepository.initialize(); @@ -507,9 +596,9 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { // Add the dynamic linker, as well as the exectuable to the repository. #ifndef MLIBC_STATIC_BUILD auto ldso_soname = reinterpret_cast(ldso_base + strtab_offset + soname_str); - auto ldso = initialRepository->injectObjectFromDts(ldso_soname, - frg::string { getAllocator() }, - ldso_base, _DYNAMIC, 1); + auto ldso = initialRepository->injectObjectFromDts( + ldso_soname, frg::string{getAllocator()}, ldso_base, _DYNAMIC, 1 + ); auto ldso_ehdr = reinterpret_cast(__ehdr_start); auto ldso_phdr = reinterpret_cast(ldso_base + ldso_ehdr->e_phoff); @@ -519,19 +608,31 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { ldso->phdrEntrySize = ldso_ehdr->e_phentsize; // TODO: support non-zero base addresses? - executableSO = initialRepository->injectObjectFromPhdrs(execfn, - frg::string { execfn, getAllocator() }, - phdr_pointer, phdr_entry_size, phdr_count, entry_pointer, 1); + executableSO = initialRepository->injectObjectFromPhdrs( + execfn, + frg::string{execfn, getAllocator()}, + phdr_pointer, + phdr_entry_size, + phdr_count, + entry_pointer, + 1 + ); // We can't initialise the ldso object after the executable SO, // so we have to set the ldso path after loading both. ldso->path = executableSO->interpreterPath; #else - executableSO = initialRepository->injectStaticObject(execfn, - frg::string{ execfn, getAllocator() }, - phdr_pointer, phdr_entry_size, phdr_count, entry_pointer, 1); - globalDebugInterface.base = (void*)executableSO->baseAddress; + executableSO = initialRepository->injectStaticObject( + execfn, + frg::string{execfn, getAllocator()}, + phdr_pointer, + phdr_entry_size, + phdr_count, + entry_pointer, + 1 + ); + globalDebugInterface.base = (void *)executableSO->baseAddress; #endif globalDebugInterface.head = &executableSO->linkMap; @@ -542,7 +643,7 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { mlibc::initStackGuard(stack_entropy); auto tcb = allocateTcb(); - if(mlibc::sys_tcb_set(tcb)) + if (mlibc::sys_tcb_set(tcb)) __ensure(!"sys_tcb_set() failed"); tcb->tid = mlibc::this_tid(); mlibc::tcb_available_flag = true; @@ -554,50 +655,49 @@ extern "C" void *interpreterMain(uintptr_t *entry_stack) { linker.initObjects(initialRepository.get()); - if(logEntryExit) - mlibc::infoLogger() << "Leaving ld.so, jump to " - << (void *)executableSO->entry << frg::endlog; + if (logEntryExit) + mlibc::infoLogger() << "Leaving ld.so, jump to " << (void *)executableSO->entry + << frg::endlog; return executableSO->entry; } const char *lastError; -extern "C" [[ gnu::visibility("default") ]] uintptr_t *__dlapi_entrystack() { - return entryStack; -} +extern "C" [[gnu::visibility("default")]] uintptr_t *__dlapi_entrystack() { return entryStack; } -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] const char *__dlapi_error() { auto error = lastError; lastError = nullptr; return error; } -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] void *__dlapi_get_tls(struct __abi_tls_entry *entry) { return reinterpret_cast(accessDtv(entry->object)) + entry->offset; } -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] const mlibc::RtldConfig &__dlapi_get_config() { return rtldConfig; } -extern "C" [[ gnu::visibility("default") ]] void __dlapi_exit() { +extern "C" [[gnu::visibility("default")]] void __dlapi_exit() { initialRepository->destructObjects(); } #if __MLIBC_POSIX_OPTION -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] void *__dlapi_open(const char *file, int flags, void *returnAddress) { if (logDlCalls) - mlibc::infoLogger() << "rtld: __dlapi_open(" << (file ? file : "nullptr") << ")" << frg::endlog; + mlibc::infoLogger() << "rtld: __dlapi_open(" << (file ? file : "nullptr") << ")" + << frg::endlog; if (flags & RTLD_DEEPBIND) mlibc::infoLogger() << "rtld: dlopen(RTLD_DEEPBIND) is unsupported" << frg::endlog; - if(!file) + if (!file) return executableSO; // TODO: Thread-safety! @@ -607,8 +707,8 @@ void *__dlapi_open(const char *file, int flags, void *returnAddress) { if (flags & RTLD_NOLOAD) { object = initialRepository->findLoadedObject(file); if (object && object->globalRts == 0 && (flags & RTLD_GLOBAL)) { - // The object was opened with RTLD_LOCAL, but we are called with RTLD_NOLOAD | RTLD_GLOBAL. - // According to the man page, we should promote to the global scope here. + // The object was opened with RTLD_LOCAL, but we are called with RTLD_NOLOAD | + // RTLD_GLOBAL. According to the man page, we should promote to the global scope here. object->globalRts = rts; globalScope->appendObject(object); } @@ -622,15 +722,16 @@ void *__dlapi_open(const char *file, int flags, void *returnAddress) { SharedObject *origin = initialRepository->findCaller(returnAddress); if (!origin) { mlibc::panicLogger() << "rtld: unable to determine calling object of dlopen " - << "(ra = " << returnAddress << ")" << frg::endlog; + << "(ra = " << returnAddress << ")" << frg::endlog; } - objectResult = initialRepository->requestObjectWithName(file, origin, newScope, !isGlobal, rts); + objectResult = + initialRepository->requestObjectWithName(file, origin, newScope, !isGlobal, rts); } else { objectResult = initialRepository->requestObjectAtPath(file, newScope, !isGlobal, rts); } - if(!objectResult) { + if (!objectResult) { switch (objectResult.error()) { case LinkerError::success: __builtin_unreachable(); @@ -667,7 +768,7 @@ void *__dlapi_open(const char *file, int flags, void *returnAddress) { return object; } -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] void *__dlapi_resolve(void *handle, const char *string, void *returnAddress) { if (logDlCalls) { const char *name; @@ -682,7 +783,7 @@ void *__dlapi_resolve(void *handle, const char *string, void *returnAddress) { } mlibc::infoLogger() << "rtld: __dlapi_resolve(" << (quote ? "\"" : "") << name - << (quote ? "\"" : "") << ", \"" << string << "\")" << frg::endlog; + << (quote ? "\"" : "") << ", \"" << string << "\")" << frg::endlog; } frg::optional target; @@ -693,7 +794,7 @@ void *__dlapi_resolve(void *handle, const char *string, void *returnAddress) { SharedObject *origin = initialRepository->findCaller(returnAddress); if (!origin) { mlibc::panicLogger() << "rtld: unable to determine calling object of dlsym " - << "(ra = " << returnAddress << ")" << frg::endlog; + << "(ra = " << returnAddress << ")" << frg::endlog; } target = Scope::resolveGlobalOrLocalNext(*globalScope, origin->localScope, string, origin); @@ -713,25 +814,24 @@ void *__dlapi_resolve(void *handle, const char *string, void *returnAddress) { frg::vector queue{getAllocator()}; - struct Token { }; - frg::hash_map< - SharedObject *, Token, - frg::hash, MemoryAllocator - > visited{frg::hash{}, getAllocator()}; + struct Token {}; + frg::hash_map, MemoryAllocator> visited{ + frg::hash{}, getAllocator() + }; auto root = reinterpret_cast(handle); visited.insert(root, Token{}); queue.push_back(root); - for(size_t i = 0; i < queue.size(); i++) { + for (size_t i = 0; i < queue.size(); i++) { auto current = queue[i]; target = resolveInObject(current, string); - if(target) + if (target) break; - for(auto dep : current->dependencies) { - if(visited.get(dep)) + for (auto dep : current->dependencies) { + if (visited.get(dep)) continue; visited.insert(dep, Token{}); queue.push_back(dep); @@ -758,20 +858,20 @@ struct __dlapi_symbol { void *link_map; }; -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] int __dlapi_reverse(const void *ptr, __dlapi_symbol *info) { if (logDlCalls) mlibc::infoLogger() << "rtld: __dlapi_reverse(" << ptr << ")" << frg::endlog; - for(size_t i = 0; i < initialRepository->loadedObjects.size(); i++) { + for (size_t i = 0; i < initialRepository->loadedObjects.size(); i++) { auto object = initialRepository->loadedObjects[i]; - auto eligible = [&] (ObjectSymbol cand) { - if(cand.symbol()->st_shndx == SHN_UNDEF) + auto eligible = [&](ObjectSymbol cand) { + if (cand.symbol()->st_shndx == SHN_UNDEF) return false; auto bind = ELF_ST_BIND(cand.symbol()->st_info); - if(bind != STB_GLOBAL && bind != STB_WEAK) + if (bind != STB_GLOBAL && bind != STB_WEAK) return false; return true; @@ -779,13 +879,15 @@ int __dlapi_reverse(const void *ptr, __dlapi_symbol *info) { auto hash_table = (Elf64_Word *)(object->baseAddress + object->hashTableOffset); auto num_symbols = hash_table[1]; - for(size_t i = 0; i < num_symbols; i++) { - ObjectSymbol cand{object, (elf_sym *)(object->baseAddress - + object->symbolTableOffset + i * sizeof(elf_sym))}; - if(eligible(cand) && cand.virtualAddress() == reinterpret_cast(ptr)) { + for (size_t i = 0; i < num_symbols; i++) { + ObjectSymbol cand{ + object, + (elf_sym *)(object->baseAddress + object->symbolTableOffset + i * sizeof(elf_sym)) + }; + if (eligible(cand) && cand.virtualAddress() == reinterpret_cast(ptr)) { if (logDlCalls) - mlibc::infoLogger() << "rtld: Found symbol " << cand.getString() << " in object " - << object->path << frg::endlog; + mlibc::infoLogger() << "rtld: Found symbol " << cand.getString() + << " in object " << object->path << frg::endlog; info->file = object->path.data(); info->base = reinterpret_cast(object->baseAddress); @@ -799,17 +901,18 @@ int __dlapi_reverse(const void *ptr, __dlapi_symbol *info) { } // Not found, find the DSO it should be in. - for(size_t i = 0; i < initialRepository->loadedObjects.size(); i++) { + for (size_t i = 0; i < initialRepository->loadedObjects.size(); i++) { auto object = initialRepository->loadedObjects[i]; - for(size_t j = 0; j < object->phdrCount; j++) { + for (size_t j = 0; j < object->phdrCount; j++) { auto phdr = (elf_phdr *)((uintptr_t)object->phdrPointer + j * object->phdrEntrySize); - if(phdr->p_type != PT_LOAD) { + if (phdr->p_type != PT_LOAD) { continue; } uintptr_t start = object->baseAddress + phdr->p_vaddr; uintptr_t end = start + phdr->p_memsz; - if(reinterpret_cast(ptr) >= start && reinterpret_cast(ptr) < end) { + if (reinterpret_cast(ptr) >= start && + reinterpret_cast(ptr) < end) { mlibc::infoLogger() << "rtld: Found DSO " << object->path << frg::endlog; info->file = object->path.data(); info->base = reinterpret_cast(object->baseAddress); @@ -828,7 +931,7 @@ int __dlapi_reverse(const void *ptr, __dlapi_symbol *info) { return -1; } -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] int __dlapi_close(void *) { if (logDlCalls) mlibc::infoLogger() << "mlibc: dlclose() is a no-op" << frg::endlog; @@ -837,20 +940,20 @@ int __dlapi_close(void *) { #endif -extern "C" [[ gnu::visibility("default") ]] -int __dlapi_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void*), void *data) { +extern "C" [[gnu::visibility("default")]] +int __dlapi_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void *), void *data) { int last_return = 0; for (auto object : initialRepository->loadedObjects) { struct dl_phdr_info info; info.dlpi_addr = object->baseAddress; info.dlpi_name = object->name.data(); - if(object->isMainObject) { + if (object->isMainObject) { info.dlpi_name = ""; } else { info.dlpi_name = object->name.data(); } - info.dlpi_phdr = static_cast(object->phdrPointer); + info.dlpi_phdr = static_cast(object->phdrPointer); info.dlpi_phnum = object->phdrCount; info.dlpi_adds = rtsCounter; info.dlpi_subs = 0; // TODO(geert): implement dlclose(). @@ -861,14 +964,14 @@ int __dlapi_iterate_phdr(int (*callback)(struct dl_phdr_info *, size_t, void*), info.dlpi_tls_data = tryAccessDtv(object); last_return = callback(&info, sizeof(struct dl_phdr_info), data); - if(last_return) + if (last_return) return last_return; } return last_return; } -extern "C" [[ gnu::visibility("default") ]] +extern "C" [[gnu::visibility("default")]] void __dlapi_enter(uintptr_t *entry_stack) { #if MLIBC_STATIC_BUILD interpreterMain(entry_stack); @@ -879,30 +982,31 @@ void __dlapi_enter(uintptr_t *entry_stack) { #if __MLIBC_GLIBC_OPTION -extern "C" [[gnu::visibility("default")]] int _dl_find_object(void *address, dl_find_object *result) { - for(const SharedObject *object : initialRepository->loadedObjects) { - if(object->baseAddress > reinterpret_cast(address)) +extern "C" [[gnu::visibility("default")]] int +_dl_find_object(void *address, dl_find_object *result) { + for (const SharedObject *object : initialRepository->loadedObjects) { + if (object->baseAddress > reinterpret_cast(address)) continue; - if(object->inLinkMap) + if (object->inLinkMap) result->dlfo_link_map = (link_map *)&object->linkMap; else result->dlfo_link_map = nullptr; uintptr_t end_addr = 0; - for(size_t j = 0; j < object->phdrCount; j++) { + for (size_t j = 0; j < object->phdrCount; j++) { auto phdr = (elf_phdr *)((uintptr_t)object->phdrPointer + j * object->phdrEntrySize); - if(phdr->p_type == DLFO_EH_SEGMENT_TYPE) { + if (phdr->p_type == DLFO_EH_SEGMENT_TYPE) { result->dlfo_eh_frame = (void *)(object->baseAddress + phdr->p_vaddr); continue; } - if(phdr->p_type != PT_LOAD) { + if (phdr->p_type != PT_LOAD) { continue; } end_addr = frg::max(end_addr, phdr->p_vaddr + phdr->p_memsz); } - if(reinterpret_cast(address) > object->baseAddress + end_addr) + if (reinterpret_cast(address) > object->baseAddress + end_addr) continue; result->dlfo_flags = 0; @@ -911,11 +1015,15 @@ extern "C" [[gnu::visibility("default")]] int _dl_find_object(void *address, dl_ // TODO: fill these fields with proper values #if DLFO_STRUCT_HAS_EH_DBASE - mlibc::infoLogger() << "mlibc: _dl_find_object dlfo_eh_dbase is not implemented and always returns NULL" << frg::endlog; + mlibc::infoLogger( + ) << "mlibc: _dl_find_object dlfo_eh_dbase is not implemented and always returns NULL" + << frg::endlog; result->dlfo_eh_dbase = nullptr; #endif // DLFO_STRUCT_HAS_EH_DBASE #if DLFO_STRUCT_HAS_EH_COUNT - mlibc::infoLogger() << "mlibc: _dl_find_object dlfo_eh_count is not implemented and always returns 0" << frg::endlog; + mlibc::infoLogger( + ) << "mlibc: _dl_find_object dlfo_eh_count is not implemented and always returns 0" + << frg::endlog; result->dlfo_eh_count = 0; #endif // DLFO_STRUCT_HAS_EH_COUNT @@ -944,16 +1052,16 @@ extern "C" unsigned long __getauxval(unsigned long type) { aux += *aux + 1; // Skip argc and all arguments __ensure(!*aux); aux++; - while(*aux) // Now, we skip the environment. + while (*aux) // Now, we skip the environment. aux++; aux++; // Parse the auxiliary vector. - while(true) { + while (true) { auto value = aux + 1; - if(*aux == AT_NULL) { + if (*aux == AT_NULL) { return 0; - }else if(*aux == type) { + } else if (*aux == type) { return *value; } aux += 2; diff --git a/options/rtld/include/mlibc/rtld-abi.hpp b/options/rtld/include/mlibc/rtld-abi.hpp index efe3e608cc..d9364bb8c3 100644 --- a/options/rtld/include/mlibc/rtld-abi.hpp +++ b/options/rtld/include/mlibc/rtld-abi.hpp @@ -3,7 +3,8 @@ #include -#if defined(__x86_64__) || defined(__aarch64__) || defined(__i386__) || defined(__riscv) || defined (__m68k__) +#if defined(__x86_64__) || defined(__aarch64__) || defined(__i386__) || defined(__riscv) || \ + defined(__m68k__) struct __abi_tls_entry { struct SharedObject *object; diff --git a/options/rtld/include/mlibc/rtld-config.hpp b/options/rtld/include/mlibc/rtld-config.hpp index 9e4488c260..7fec1e8b41 100644 --- a/options/rtld/include/mlibc/rtld-config.hpp +++ b/options/rtld/include/mlibc/rtld-config.hpp @@ -7,7 +7,7 @@ struct RtldConfig { bool secureRequired; }; -} +} // namespace mlibc #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" @@ -17,11 +17,9 @@ extern "C" const mlibc::RtldConfig &__dlapi_get_config(); #ifndef MLIBC_BUILDING_RTLD namespace mlibc { -inline const RtldConfig &rtldConfig() { - return __dlapi_get_config(); -} +inline const RtldConfig &rtldConfig() { return __dlapi_get_config(); } -} +} // namespace mlibc #endif #endif // MLIBC_RTLD_CONFIG diff --git a/sysdeps/aero/.clang-format b/sysdeps/aero/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/aero/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/astral/.clang-format b/sysdeps/astral/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/astral/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/dripos/.clang-format b/sysdeps/dripos/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/dripos/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/generic-helpers/include/generic-helpers/netlink.hpp b/sysdeps/generic-helpers/include/generic-helpers/netlink.hpp index 6237aeb446..1b40a99897 100644 --- a/sysdeps/generic-helpers/include/generic-helpers/netlink.hpp +++ b/sysdeps/generic-helpers/include/generic-helpers/netlink.hpp @@ -20,14 +20,15 @@ namespace { */ struct NetlinkHelper { ~NetlinkHelper() { - if(fd_) + if (fd_) close(*fd_); } bool send_request(int type) { - if(!fd_ || *fd_ == -1) { + if (!fd_ || *fd_ == -1) { int fd; - if(int e = mlibc::sys_socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE, &fd); e) + if (int e = mlibc::sys_socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE, &fd); + e) return false; fd_ = fd; } @@ -43,22 +44,26 @@ struct NetlinkHelper { request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(request) - sizeof(nlmsghdr)); request.msg.rtgen_family = AF_UNSPEC; - return send(fd_.value(), reinterpret_cast(&request), sizeof(request), 0) == sizeof(request); + return send(fd_.value(), reinterpret_cast(&request), sizeof(request), 0) == + sizeof(request); } bool recv(void cb(void *, nlmsghdr *), void *ctx) { ssize_t read; - while((read = ::recv(fd_.value(), reinterpret_cast(data_.data()), data_.size(), 0)) > 0) { + while ((read = + ::recv(fd_.value(), reinterpret_cast(data_.data()), data_.size(), 0) + ) > 0) { auto hdr = reinterpret_cast(data_.data()); - for(; NLMSG_OK(hdr, static_cast(read)); hdr = NLMSG_NEXT(hdr, read)) { - if(hdr->nlmsg_type == NLMSG_DONE) + for (; NLMSG_OK(hdr, static_cast(read)); hdr = NLMSG_NEXT(hdr, read)) { + if (hdr->nlmsg_type == NLMSG_DONE) return true; - if(hdr->nlmsg_type == NLMSG_ERROR) { + if (hdr->nlmsg_type == NLMSG_ERROR) { nlmsgerr *err = reinterpret_cast(NLMSG_DATA(hdr)); - mlibc::infoLogger() << "mlibc: NetlinkHelper received NLMSG_ERROR " << -err->error << ": " - << strerror(-err->error) << frg::endlog; + mlibc::infoLogger() + << "mlibc: NetlinkHelper received NLMSG_ERROR " << -err->error << ": " + << strerror(-err->error) << frg::endlog; return false; } @@ -68,7 +73,8 @@ struct NetlinkHelper { return false; } -private: + + private: frg::optional fd_; frg::array data_; }; @@ -90,13 +96,13 @@ struct IfaddrHelper { char name_[IFNAMSIZ + 1]; -public: + public: explicit IfaddrHelper(ifaddrs **list) { // append ourselves to the end of the chain ifaddrs *last = *list; - if(last) { - while(last->ifa_next) + if (last) { + while (last->ifa_next) last = last->ifa_next; last->ifa_next = &this->ifa; @@ -116,7 +122,7 @@ struct IfaddrHelper { * it is not separately specified, via IFA_LOCAL and its handler. */ void set_addr(int family, const void *data, size_t bytes) { - if(ifa.ifa_addr == nullptr) + if (ifa.ifa_addr == nullptr) ifa.ifa_addr = copy_addr(family, data, bytes, &addr_); ifa.ifa_dstaddr = copy_addr(family, data, bytes, &dest_addr_); @@ -136,8 +142,9 @@ struct IfaddrHelper { // - while for a normally configured broadcast interface, it is the same as IFA_LOCAL. // if we already have an ifa_addr, move it over to ifa_dstaddr - if(ifa.ifa_addr != nullptr) - ifa.ifa_dstaddr = reinterpret_cast(memcpy(&dest_addr_, &addr_, sizeof(addr_))); + if (ifa.ifa_addr != nullptr) + ifa.ifa_dstaddr = + reinterpret_cast(memcpy(&dest_addr_, &addr_, sizeof(addr_))); ifa.ifa_addr = copy_addr(family, data, byteCount, &addr_); } @@ -150,8 +157,8 @@ struct IfaddrHelper { memset(dst.data(), 0xFF, prefix_length / 8); // if needed, set the last partial byte to its correct mask - if(prefix_length % 8) - dst[prefix_length/8] = (0xFF << (8 - (prefix_length % 8))) & 0xFF; + if (prefix_length % 8) + dst[prefix_length / 8] = (0xFF << (8 - (prefix_length % 8))) & 0xFF; ifa.ifa_netmask = reinterpret_cast(&netmask_); } @@ -163,17 +170,18 @@ struct IfaddrHelper { sll->sll_halen = halen; } -private: + private: /** * Copy an address to its storage, and return a pointer to that. */ - sockaddr *copy_addr(sa_family_t family, const void *data, size_t byteCount, sockaddr_storage *ss) { + sockaddr * + copy_addr(sa_family_t family, const void *data, size_t byteCount, sockaddr_storage *ss) { ss->ss_family = family; auto sb = sockaddr_bytes(family, ss); memcpy(sb.data(), data, frg::min(byteCount, sb.size())); - if(family == AF_INET6 && (IN6_IS_ADDR_LINKLOCAL(data) || IN6_IS_ADDR_MC_LINKLOCAL(data))) { + if (family == AF_INET6 && (IN6_IS_ADDR_LINKLOCAL(data) || IN6_IS_ADDR_MC_LINKLOCAL(data))) { reinterpret_cast(ss)->sin6_scope_id = if_index_; } @@ -184,13 +192,13 @@ struct IfaddrHelper { * Retrieve an appropriately sized span for the sockaddr's addr */ frg::span sockaddr_bytes(int family, sockaddr_storage *ss) { - if(family == AF_INET) { + if (family == AF_INET) { sockaddr_in *ss4 = reinterpret_cast(ss); return {reinterpret_cast(&ss4->sin_addr), sizeof(ss4->sin_addr)}; - } else if(family == AF_INET6) { + } else if (family == AF_INET6) { sockaddr_in6 *ss6 = reinterpret_cast(ss); return {reinterpret_cast(&ss6->sin6_addr), sizeof(ss6->sin6_addr)}; - } else if(family == AF_PACKET) { + } else if (family == AF_PACKET) { sockaddr_ll *sll = reinterpret_cast(ss); return {reinterpret_cast(&sll->sll_addr), sizeof(sll->sll_addr)}; } else { @@ -204,12 +212,13 @@ struct IfaddrHelper { static_assert(offsetof(IfaddrHelper, ifa) == 0); /** - * Callback function to be used with NetlinkHelper for implementing `sys_getifaddrs` by using rtnetlink. + * Callback function to be used with NetlinkHelper for implementing `sys_getifaddrs` by using + * rtnetlink. */ void getifaddrs_callback(void *context, nlmsghdr *hdr) { ifaddrs **out = reinterpret_cast(context); - if(hdr->nlmsg_type == RTM_NEWLINK) { + if (hdr->nlmsg_type == RTM_NEWLINK) { ifinfomsg *ifi = reinterpret_cast(NLMSG_DATA(hdr)); auto new_addr = frg::construct(getAllocator(), out); @@ -219,19 +228,19 @@ void getifaddrs_callback(void *context, nlmsghdr *hdr) { rtattr *rta = IFLA_RTA(ifi); size_t rta_len = IFLA_PAYLOAD(hdr); - while(RTA_OK(rta, rta_len)) { - if(rta->rta_type == IFLA_ADDRESS) { - if(RTA_PAYLOAD(rta) < sizeof(new_addr->addr_)) { + while (RTA_OK(rta, rta_len)) { + if (rta->rta_type == IFLA_ADDRESS) { + if (RTA_PAYLOAD(rta) < sizeof(new_addr->addr_)) { new_addr->set_addr(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta)); new_addr->set_packet_attrs(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta)); } - } else if(rta->rta_type == IFLA_BROADCAST) { - if(RTA_PAYLOAD(rta) < sizeof(new_addr->broadcast_)) { + } else if (rta->rta_type == IFLA_BROADCAST) { + if (RTA_PAYLOAD(rta) < sizeof(new_addr->broadcast_)) { new_addr->set_broadcast_addr(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta)); new_addr->set_packet_attrs(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta)); } - } else if(rta->rta_type == IFLA_IFNAME) { - if(RTA_PAYLOAD(rta) < sizeof(new_addr->name_)) { + } else if (rta->rta_type == IFLA_IFNAME) { + if (RTA_PAYLOAD(rta) < sizeof(new_addr->name_)) { memcpy(new_addr->name_, RTA_DATA(rta), RTA_PAYLOAD(rta)); new_addr->ifa.ifa_name = new_addr->name_; } @@ -239,18 +248,18 @@ void getifaddrs_callback(void *context, nlmsghdr *hdr) { rta = RTA_NEXT(rta, rta_len); } - } else if(hdr->nlmsg_type == RTM_NEWADDR) { - ifaddrmsg *msg = reinterpret_cast(NLMSG_DATA(hdr)); + } else if (hdr->nlmsg_type == RTM_NEWADDR) { + ifaddrmsg *msg = reinterpret_cast(NLMSG_DATA(hdr)); const IfaddrHelper *current = reinterpret_cast(*out); while (current != nullptr && current->if_index_ != static_cast(msg->ifa_index)) { - current = reinterpret_cast(current->ifa.ifa_next); + current = reinterpret_cast(current->ifa.ifa_next); } IfaddrHelper *new_addr = frg::construct(getAllocator(), out); new_addr->if_index_ = static_cast(msg->ifa_index); - if(current != nullptr) { + if (current != nullptr) { strcpy(new_addr->name_, current->name_); new_addr->ifa.ifa_name = new_addr->name_; new_addr->ifa.ifa_flags = current->ifa.ifa_flags; @@ -259,25 +268,25 @@ void getifaddrs_callback(void *context, nlmsghdr *hdr) { rtattr *rta = IFA_RTA(msg); size_t rta_len = IFA_PAYLOAD(hdr); - while(RTA_OK(rta, rta_len)) { - if(rta->rta_type == IFA_ADDRESS) { - if(msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) { + while (RTA_OK(rta, rta_len)) { + if (rta->rta_type == IFA_ADDRESS) { + if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) { new_addr->set_addr(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta)); new_addr->set_netmask(msg->ifa_family, msg->ifa_prefixlen); } - } else if(rta->rta_type == IFA_BROADCAST) { - if(msg->ifa_family == AF_INET) { + } else if (rta->rta_type == IFA_BROADCAST) { + if (msg->ifa_family == AF_INET) { new_addr->set_broadcast_addr(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta)); - if(current == nullptr) { + if (current == nullptr) { new_addr->ifa.ifa_flags |= IFF_BROADCAST; } } - } else if(rta->rta_type == IFA_LOCAL) { - if(msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) { + } else if (rta->rta_type == IFA_LOCAL) { + if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) { new_addr->set_local_address(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta)); } - } else if(rta->rta_type == IFA_LABEL) { - if(RTA_PAYLOAD(rta) < sizeof(new_addr->name_)) { + } else if (rta->rta_type == IFA_LABEL) { + if (RTA_PAYLOAD(rta) < sizeof(new_addr->name_)) { memcpy(new_addr->name_, RTA_DATA(rta), RTA_PAYLOAD(rta)); new_addr->ifa.ifa_name = new_addr->name_; } diff --git a/sysdeps/ironclad/.clang-format b/sysdeps/ironclad/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/ironclad/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/keyronex/.clang-format b/sysdeps/keyronex/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/keyronex/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/lemon/.clang-format b/sysdeps/lemon/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/lemon/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/linux/aarch64/arch-syscall.cpp b/sysdeps/linux/aarch64/arch-syscall.cpp index b178538f5b..efd557265b 100644 --- a/sysdeps/linux/aarch64/arch-syscall.cpp +++ b/sysdeps/linux/aarch64/arch-syscall.cpp @@ -1,79 +1,62 @@ -#include #include +#include using sc_word_t = __sc_word_t; sc_word_t __do_syscall0(long sc) { register int sc_reg asm("x8") = sc; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : "r"(sc_reg) : "memory"); + asm volatile("svc 0" : "=r"(ret) : "r"(sc_reg) : "memory"); return ret; } -sc_word_t __do_syscall1(long sc, - sc_word_t arg1) { +sc_word_t __do_syscall1(long sc, sc_word_t arg1) { register int sc_reg asm("x8") = sc; register sc_word_t arg1_reg asm("x0") = arg1; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg) - : "memory"); + asm volatile("svc 0" : "=r"(ret) : "r"(sc_reg), "r"(arg1_reg) : "memory"); return ret; } -sc_word_t __do_syscall2(long sc, - sc_word_t arg1, sc_word_t arg2) { +sc_word_t __do_syscall2(long sc, sc_word_t arg1, sc_word_t arg2) { register int sc_reg asm("x8") = sc; register sc_word_t arg1_reg asm("x0") = arg1; register sc_word_t arg2_reg asm("x1") = arg2; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg) - : "memory"); + asm volatile("svc 0" : "=r"(ret) : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg) : "memory"); return ret; } -sc_word_t __do_syscall3(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { +sc_word_t __do_syscall3(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { register int sc_reg asm("x8") = sc; register sc_word_t arg1_reg asm("x0") = arg1; register sc_word_t arg2_reg asm("x1") = arg2; register sc_word_t arg3_reg asm("x2") = arg3; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg) - : "memory"); + asm volatile("svc 0" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg) + : "memory"); return ret; } -sc_word_t __do_syscall4(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4) { +sc_word_t __do_syscall4(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { register int sc_reg asm("x8") = sc; register sc_word_t arg1_reg asm("x0") = arg1; register sc_word_t arg2_reg asm("x1") = arg2; register sc_word_t arg3_reg asm("x2") = arg3; register sc_word_t arg4_reg asm("x3") = arg4; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg) - : "memory"); + asm volatile("svc 0" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg), "r"(arg4_reg) + : "memory"); return ret; } -sc_word_t __do_syscall5(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5) { +sc_word_t __do_syscall5( + long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { register int sc_reg asm("x8") = sc; register sc_word_t arg1_reg asm("x0") = arg1; register sc_word_t arg2_reg asm("x1") = arg2; @@ -81,20 +64,24 @@ sc_word_t __do_syscall5(long sc, register sc_word_t arg4_reg asm("x3") = arg4; register sc_word_t arg5_reg asm("x4") = arg5; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg), - "r"(arg5_reg) - : "memory"); + asm volatile( + "svc 0" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg), "r"(arg4_reg), "r"(arg5_reg) + : "memory" + ); return ret; } -sc_word_t __do_syscall6(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5, sc_word_t arg6) { +sc_word_t __do_syscall6( + long sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { register int sc_reg asm("x8") = sc; register sc_word_t arg1_reg asm("x0") = arg1; register sc_word_t arg2_reg asm("x1") = arg2; @@ -103,15 +90,15 @@ sc_word_t __do_syscall6(long sc, register sc_word_t arg5_reg asm("x4") = arg5; register sc_word_t arg6_reg asm("x5") = arg6; register sc_word_t ret asm("x0"); - asm volatile ("svc 0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg), - "r"(arg5_reg), - "r"(arg6_reg) - : "memory" - ); + asm volatile("svc 0" + : "=r"(ret) + : "r"(sc_reg), + "r"(arg1_reg), + "r"(arg2_reg), + "r"(arg3_reg), + "r"(arg4_reg), + "r"(arg5_reg), + "r"(arg6_reg) + : "memory"); return ret; } diff --git a/sysdeps/linux/generic/cxx-syscall.hpp b/sysdeps/linux/generic/cxx-syscall.hpp index afc76481a9..75bc36398d 100644 --- a/sysdeps/linux/generic/cxx-syscall.hpp +++ b/sysdeps/linux/generic/cxx-syscall.hpp @@ -1,118 +1,132 @@ #pragma once #include +#include #include #include -#include #include -#include #include +#include using sc_word_t = __sc_word_t; extern "C" { - extern sc_word_t __mlibc_do_asm_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, - sc_word_t arg3, sc_word_t arg4, sc_word_t arg5, sc_word_t arg6); +extern sc_word_t __mlibc_do_asm_cp_syscall( + int sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +); - extern void __mlibc_do_cancel(); +extern void __mlibc_do_cancel(); } namespace mlibc { - // C++ wrappers for the extern "C" functions. - inline sc_word_t do_nargs_syscall(int sc) { - return __do_syscall0(sc); - } - inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1) { - return __do_syscall1(sc, arg1); - } - inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2) { - return __do_syscall2(sc, arg1, arg2); - } - inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { - return __do_syscall3(sc, arg1, arg2, arg3); - } - inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4) { - return __do_syscall4(sc, arg1, arg2, arg3, arg4); - } - inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5) { - return __do_syscall5(sc, arg1, arg2, arg3, arg4, arg5); - } - inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5, sc_word_t arg6) { - return __do_syscall6(sc, arg1, arg2, arg3, arg4, arg5, arg6); - } +// C++ wrappers for the extern "C" functions. +inline sc_word_t do_nargs_syscall(int sc) { return __do_syscall0(sc); } +inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1) { return __do_syscall1(sc, arg1); } +inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2) { + return __do_syscall2(sc, arg1, arg2); +} +inline sc_word_t do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { + return __do_syscall3(sc, arg1, arg2, arg3); +} +inline sc_word_t +do_nargs_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { + return __do_syscall4(sc, arg1, arg2, arg3, arg4); +} +inline sc_word_t do_nargs_syscall( + int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { + return __do_syscall5(sc, arg1, arg2, arg3, arg4, arg5); +} +inline sc_word_t do_nargs_syscall( + int sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { + return __do_syscall6(sc, arg1, arg2, arg3, arg4, arg5, arg6); +} - inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1) { - return __mlibc_do_asm_cp_syscall(sc, arg1, 0, 0, 0, 0, 0); - } - inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2) { - return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, 0, 0, 0, 0); - } - inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, - sc_word_t arg3) { - return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, 0, 0, 0); - } - inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4) { - return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, arg4, 0, 0); - } - inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5) { - return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, arg4, arg5, 0); - } - inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5, sc_word_t arg6) { - return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, arg4, arg5, arg6); - } +inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1) { + return __mlibc_do_asm_cp_syscall(sc, arg1, 0, 0, 0, 0, 0); +} +inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2) { + return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, 0, 0, 0, 0); +} +inline sc_word_t do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { + return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, 0, 0, 0); +} +inline sc_word_t +do_nargs_cp_syscall(int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { + return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, arg4, 0, 0); +} +inline sc_word_t do_nargs_cp_syscall( + int sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { + return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, arg4, arg5, 0); +} +inline sc_word_t do_nargs_cp_syscall( + int sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { + return __mlibc_do_asm_cp_syscall(sc, arg1, arg2, arg3, arg4, arg5, arg6); +} - // Type-safe syscall result type. - enum class sc_result_t : sc_word_t { }; +// Type-safe syscall result type. +enum class sc_result_t : sc_word_t {}; - // Cast to the argument type of the extern "C" functions. - inline sc_word_t sc_cast(long x) { return x; } - inline sc_word_t sc_cast(const void *x) { return reinterpret_cast(x); } +// Cast to the argument type of the extern "C" functions. +inline sc_word_t sc_cast(long x) { return x; } +inline sc_word_t sc_cast(const void *x) { return reinterpret_cast(x); } - template - sc_result_t do_syscall(int sc, T... args) { - return static_cast(do_nargs_syscall(sc, sc_cast(args)...)); - } +template sc_result_t do_syscall(int sc, T... args) { + return static_cast(do_nargs_syscall(sc, sc_cast(args)...)); +} - inline int sc_error(sc_result_t ret) { - auto v = static_cast(ret); - if(static_cast(v) > -4096UL) - return -v; - return 0; - } +inline int sc_error(sc_result_t ret) { + auto v = static_cast(ret); + if (static_cast(v) > -4096UL) + return -v; + return 0; +} - template - sc_result_t do_cp_syscall(int sc, T... args) { +template sc_result_t do_cp_syscall(int sc, T... args) { #if __MLIBC_POSIX_OPTION && !MLIBC_BUILDING_RTLD - auto result = static_cast(do_nargs_cp_syscall(sc, sc_cast(args)...)); - if (int e = sc_error(result); e) { - auto tcb = reinterpret_cast(get_current_tcb()); - if (tcb_cancelled(tcb->cancelBits) && e == EINTR) { - __mlibc_do_cancel(); - __builtin_unreachable(); - } + auto result = static_cast(do_nargs_cp_syscall(sc, sc_cast(args)...)); + if (int e = sc_error(result); e) { + auto tcb = reinterpret_cast(get_current_tcb()); + if (tcb_cancelled(tcb->cancelBits) && e == EINTR) { + __mlibc_do_cancel(); + __builtin_unreachable(); } - return result; + } + return result; #else - return do_syscall(sc, std::forward(args)...); + return do_syscall(sc, std::forward(args)...); #endif // __MLIBC_POSIX_OPTION || !MLIBC_BUILDING_RTLD - } - // Cast from the syscall result type. - template - T sc_int_result(sc_result_t ret) { - auto v = static_cast(ret); - return v; - } +} +// Cast from the syscall result type. +template T sc_int_result(sc_result_t ret) { + auto v = static_cast(ret); + return v; +} - template - T *sc_ptr_result(sc_result_t ret) { - auto v = static_cast(ret); - return reinterpret_cast(v); - } +template T *sc_ptr_result(sc_result_t ret) { + auto v = static_cast(ret); + return reinterpret_cast(v); } +} // namespace mlibc diff --git a/sysdeps/linux/generic/entry.cpp b/sysdeps/linux/generic/entry.cpp index aa049ce375..b23e74cb52 100644 --- a/sysdeps/linux/generic/entry.cpp +++ b/sysdeps/linux/generic/entry.cpp @@ -1,7 +1,7 @@ -#include -#include #include #include +#include +#include #include // defined by the POSIX library @@ -26,11 +26,13 @@ LibraryGuard::LibraryGuard() { // Parse the exec() stack. mlibc::parse_exec_stack(__dlapi_entrystack(), &__mlibc_stack_data); - mlibc::set_startup_data(__mlibc_stack_data.argc, __mlibc_stack_data.argv, - __mlibc_stack_data.envp); + mlibc::set_startup_data( + __mlibc_stack_data.argc, __mlibc_stack_data.argv, __mlibc_stack_data.envp + ); } -extern "C" void __mlibc_entry(uintptr_t *entry_stack, int (*main_fn)(int argc, char *argv[], char *env[])) { +extern "C" void +__mlibc_entry(uintptr_t *entry_stack, int (*main_fn)(int argc, char *argv[], char *env[])) { __dlapi_enter(entry_stack); __hwcap = getauxval(AT_HWCAP); auto result = main_fn(__mlibc_stack_data.argc, __mlibc_stack_data.argv, environ); diff --git a/sysdeps/linux/generic/sysdeps.cpp b/sysdeps/linux/generic/sysdeps.cpp index 1db9a7ef54..5f4d73c6cd 100644 --- a/sysdeps/linux/generic/sysdeps.cpp +++ b/sysdeps/linux/generic/sysdeps.cpp @@ -4,18 +4,18 @@ #include -#include -#include +#include "cxx-syscall.hpp" #include #include #include +#include +#include +#include +#include #include #include -#include #include -#include #include -#include "cxx-syscall.hpp" #if __MLIBC_LINUX_OPTION && !defined(MLIBC_BUILDING_RTLD) @@ -23,12 +23,16 @@ #endif -#define STUB_ONLY { __ensure(!"STUB_ONLY function was called"); __builtin_unreachable(); } +#define STUB_ONLY \ + { \ + __ensure(!"STUB_ONLY function was called"); \ + __builtin_unreachable(); \ + } #define UNUSED(x) (void)(x); #ifndef MLIBC_BUILDING_RTLD extern "C" long __do_syscall_ret(unsigned long ret) { - if(ret > -4096UL) { + if (ret > -4096UL) { errno = -ret; return -1; } @@ -40,16 +44,14 @@ namespace mlibc { void sys_libc_log(const char *message) { size_t n = 0; - while(message[n]) + while (message[n]) n++; do_syscall(SYS_write, 2, message, n); char lf = '\n'; do_syscall(SYS_write, 2, &lf, 1); } -void sys_libc_panic() { - __builtin_trap(); -} +void sys_libc_panic() { __builtin_trap(); } #if defined(__i386__) @@ -57,12 +59,12 @@ struct user_desc { unsigned int entry_number; unsigned long base_addr; unsigned int limit; - unsigned int seg_32bit: 1; - unsigned int contents: 2; - unsigned int read_exec_only: 1; - unsigned int limit_in_pages: 1; - unsigned int seg_not_present: 1; - unsigned int useable: 1; + unsigned int seg_32bit : 1; + unsigned int contents : 2; + unsigned int read_exec_only : 1; + unsigned int limit_in_pages : 1; + unsigned int seg_not_present : 1; + unsigned int useable : 1; }; #endif @@ -77,32 +79,32 @@ extern "C" void *__m68k_read_tp() { int sys_tcb_set(void *pointer) { #if defined(__x86_64__) auto ret = do_syscall(SYS_arch_prctl, 0x1002 /* ARCH_SET_FS */, pointer); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; #elif defined(__i386__) struct user_desc desc = { - .entry_number = static_cast(-1), - .base_addr = uintptr_t(pointer), - .limit = 0xfffff, - .seg_32bit = 1, - .contents = 0, - .read_exec_only = 0, - .limit_in_pages = 1, - .seg_not_present = 0, - .useable = 1, + .entry_number = static_cast(-1), + .base_addr = uintptr_t(pointer), + .limit = 0xfffff, + .seg_32bit = 1, + .contents = 0, + .read_exec_only = 0, + .limit_in_pages = 1, + .seg_not_present = 0, + .useable = 1, }; auto ret = do_syscall(SYS_set_thread_area, &desc); __ensure(!sc_error(ret)); - asm volatile ("movw %w0, %%gs" : : "q"(desc.entry_number * 8 + 3) :); + asm volatile("movw %w0, %%gs" : : "q"(desc.entry_number * 8 + 3) :); #elif defined(__riscv) uintptr_t thread_data = reinterpret_cast(pointer) + sizeof(Tcb); - asm volatile ("mv tp, %0" :: "r"(thread_data)); -#elif defined (__aarch64__) + asm volatile("mv tp, %0" ::"r"(thread_data)); +#elif defined(__aarch64__) uintptr_t thread_data = reinterpret_cast(pointer) + sizeof(Tcb) - 0x10; - asm volatile ("msr tpidr_el0, %0" :: "r"(thread_data)); -#elif defined (__m68k__) + asm volatile("msr tpidr_el0, %0" ::"r"(thread_data)); +#elif defined(__m68k__) auto ret = do_syscall(__NR_set_thread_area, (uintptr_t)pointer + 0x7000 + sizeof(Tcb)); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; #else #error "Missing architecture specific code." @@ -111,23 +113,22 @@ int sys_tcb_set(void *pointer) { } int sys_anon_allocate(size_t size, void **pointer) { - return sys_vm_map(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, - -1, 0, pointer); -} -int sys_anon_free(void *pointer, size_t size) { - return sys_vm_unmap(pointer, size); + return sys_vm_map( + nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0, pointer + ); } +int sys_anon_free(void *pointer, size_t size) { return sys_vm_unmap(pointer, size); } int sys_fadvise(int fd, off_t offset, off_t length, int advice) { auto ret = do_syscall(SYS_fadvise64, fd, offset, length, advice); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } int sys_open(const char *path, int flags, mode_t mode, int *fd) { auto ret = do_cp_syscall(SYS_openat, AT_FDCWD, path, flags, mode); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *fd = sc_int_result(ret); return 0; @@ -143,21 +144,21 @@ int sys_openat(int dirfd, const char *path, int flags, mode_t mode, int *fd) { int sys_close(int fd) { auto ret = do_cp_syscall(SYS_close, fd); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } int sys_dup2(int fd, int flags, int newfd) { auto ret = do_cp_syscall(SYS_dup3, fd, newfd, flags); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } int sys_read(int fd, void *buffer, size_t size, ssize_t *bytes_read) { auto ret = do_cp_syscall(SYS_read, fd, buffer, size); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *bytes_read = sc_int_result(ret); return 0; @@ -165,7 +166,7 @@ int sys_read(int fd, void *buffer, size_t size, ssize_t *bytes_read) { int sys_readv(int fd, const struct iovec *iovs, int iovc, ssize_t *bytes_read) { auto ret = do_cp_syscall(SYS_readv, fd, iovs, iovc); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *bytes_read = sc_int_result(ret); return 0; @@ -173,16 +174,16 @@ int sys_readv(int fd, const struct iovec *iovs, int iovc, ssize_t *bytes_read) { int sys_write(int fd, const void *buffer, size_t size, ssize_t *bytes_written) { auto ret = do_cp_syscall(SYS_write, fd, buffer, size); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; - if(bytes_written) + if (bytes_written) *bytes_written = sc_int_result(ret); return 0; } int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { auto ret = do_syscall(SYS_lseek, fd, offset, whence); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *new_offset = sc_int_result(ret); return 0; @@ -190,28 +191,28 @@ int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { int sys_chmod(const char *pathname, mode_t mode) { auto ret = do_cp_syscall(SYS_fchmodat, AT_FDCWD, pathname, mode); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } int sys_fchmod(int fd, mode_t mode) { auto ret = do_cp_syscall(SYS_fchmod, fd, mode); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } int sys_fchmodat(int fd, const char *pathname, mode_t mode, int flags) { auto ret = do_cp_syscall(SYS_fchmodat, fd, pathname, mode, flags); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } int sys_fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags) { auto ret = do_cp_syscall(SYS_fchownat, dirfd, pathname, owner, group, flags); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } @@ -223,19 +224,18 @@ int sys_utimensat(int dirfd, const char *pathname, const struct timespec times[2 return 0; } -int sys_vm_map(void *hint, size_t size, int prot, int flags, - int fd, off_t offset, void **window) { - if(offset % 4096) +int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offset, void **window) { + if (offset % 4096) return EINVAL; - if(size >= PTRDIFF_MAX) + if (size >= PTRDIFF_MAX) return ENOMEM; #if defined(SYS_mmap2) - auto ret = do_syscall(SYS_mmap2, hint, size, prot, flags, fd, offset/4096); + auto ret = do_syscall(SYS_mmap2, hint, size, prot, flags, fd, offset / 4096); #else auto ret = do_syscall(SYS_mmap, hint, size, prot, flags, fd, offset); #endif // TODO: musl fixes up EPERM errors from the kernel. - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *window = sc_ptr_result(ret); return 0; @@ -243,7 +243,7 @@ int sys_vm_map(void *hint, size_t size, int prot, int flags, int sys_vm_unmap(void *pointer, size_t size) { auto ret = do_syscall(SYS_munmap, pointer, size); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return 0; } @@ -326,8 +326,7 @@ int sys_fstatfs(int fd, struct statfs *buf) { extern "C" void __mlibc_signal_restore(void); extern "C" void __mlibc_signal_restore_rt(void); -int sys_sigaction(int signum, const struct sigaction *act, - struct sigaction *oldact) { +int sys_sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { struct ksigaction { void (*handler)(int); unsigned long flags; @@ -339,15 +338,20 @@ int sys_sigaction(int signum, const struct sigaction *act, if (act) { kernel_act.handler = act->sa_handler; kernel_act.flags = act->sa_flags | SA_RESTORER; - kernel_act.restorer = (act->sa_flags & SA_SIGINFO) ? __mlibc_signal_restore_rt : __mlibc_signal_restore; + kernel_act.restorer = + (act->sa_flags & SA_SIGINFO) ? __mlibc_signal_restore_rt : __mlibc_signal_restore; memcpy(&kernel_act.mask, &act->sa_mask, sizeof(kernel_act.mask)); } static_assert(sizeof(kernel_act.mask) == 8); - auto ret = do_syscall(SYS_rt_sigaction, signum, act ? - &kernel_act : NULL, oldact ? - &kernel_oldact : NULL, sizeof(kernel_act.mask)); + auto ret = do_syscall( + SYS_rt_sigaction, + signum, + act ? &kernel_act : NULL, + oldact ? &kernel_oldact : NULL, + sizeof(kernel_act.mask) + ); if (int e = sc_error(ret); e) return e; @@ -361,33 +365,49 @@ int sys_sigaction(int signum, const struct sigaction *act, } int sys_socket(int domain, int type, int protocol, int *fd) { - auto ret = do_syscall(SYS_socket, domain, type, protocol); - if (int e = sc_error(ret); e) - return e; - *fd = sc_int_result(ret); - return 0; + auto ret = do_syscall(SYS_socket, domain, type, protocol); + if (int e = sc_error(ret); e) + return e; + *fd = sc_int_result(ret); + return 0; } int sys_msg_send(int sockfd, const struct msghdr *msg, int flags, ssize_t *length) { - auto ret = do_cp_syscall(SYS_sendmsg, sockfd, msg, flags); - if (int e = sc_error(ret); e) - return e; - *length = sc_int_result(ret); - return 0; + auto ret = do_cp_syscall(SYS_sendmsg, sockfd, msg, flags); + if (int e = sc_error(ret); e) + return e; + *length = sc_int_result(ret); + return 0; } -ssize_t sys_sendto(int fd, const void *buffer, size_t size, int flags, const struct sockaddr *sock_addr, socklen_t addr_length, ssize_t *length) { +ssize_t sys_sendto( + int fd, + const void *buffer, + size_t size, + int flags, + const struct sockaddr *sock_addr, + socklen_t addr_length, + ssize_t *length +) { auto ret = do_cp_syscall(SYS_sendto, fd, buffer, size, flags, sock_addr, addr_length); - if(int e = sc_error(ret); e) { + if (int e = sc_error(ret); e) { return e; } *length = sc_int_result(ret); return 0; } -ssize_t sys_recvfrom(int fd, void *buffer, size_t size, int flags, struct sockaddr *sock_addr, socklen_t *addr_length, ssize_t *length) { +ssize_t sys_recvfrom( + int fd, + void *buffer, + size_t size, + int flags, + struct sockaddr *sock_addr, + socklen_t *addr_length, + ssize_t *length +) { auto ret = do_cp_syscall(SYS_recvfrom, fd, buffer, size, flags, sock_addr, addr_length); - if(int e = sc_error(ret); e) { + if (int e = sc_error(ret); e) { return e; } *length = sc_int_result(ret); @@ -395,24 +415,24 @@ ssize_t sys_recvfrom(int fd, void *buffer, size_t size, int flags, struct sockad } int sys_msg_recv(int sockfd, struct msghdr *msg, int flags, ssize_t *length) { - auto ret = do_cp_syscall(SYS_recvmsg, sockfd, msg, flags); - if (int e = sc_error(ret); e) - return e; - *length = sc_int_result(ret); - return 0; + auto ret = do_cp_syscall(SYS_recvmsg, sockfd, msg, flags); + if (int e = sc_error(ret); e) + return e; + *length = sc_int_result(ret); + return 0; } int sys_fcntl(int fd, int cmd, va_list args, int *result) { - auto arg = va_arg(args, unsigned long); - // TODO: the api for linux differs for each command so fcntl()s might fail with -EINVAL - // we should implement all the different fcntl()s + auto arg = va_arg(args, unsigned long); + // TODO: the api for linux differs for each command so fcntl()s might fail with -EINVAL + // we should implement all the different fcntl()s // TODO(geert): only some fcntl()s can fail with -EINTR, making do_cp_syscall useless // on most fcntls(). Another reason to handle different fcntl()s seperately. - auto ret = do_cp_syscall(SYS_fcntl, fd, cmd, arg); - if (int e = sc_error(ret); e) - return e; - *result = sc_int_result(ret); - return 0; + auto ret = do_cp_syscall(SYS_fcntl, fd, cmd, arg); + if (int e = sc_error(ret); e) + return e; + *result = sc_int_result(ret); + return 0; } int sys_getcwd(char *buf, size_t size) { @@ -431,15 +451,12 @@ int sys_unlinkat(int dfd, const char *path, int flags) { } int sys_sleep(time_t *secs, long *nanos) { - struct timespec req = { - .tv_sec = *secs, - .tv_nsec = *nanos - }; + struct timespec req = {.tv_sec = *secs, .tv_nsec = *nanos}; struct timespec rem = {}; auto ret = do_cp_syscall(SYS_nanosleep, &req, &rem); - if (int e = sc_error(ret); e) - return e; + if (int e = sc_error(ret); e) + return e; *secs = rem.tv_sec; *nanos = rem.tv_nsec; @@ -452,25 +469,26 @@ int sys_isatty(int fd) { if (int e = sc_error(ret); e) return e; auto res = sc_int_result(ret); - if(!res) return 0; + if (!res) + return 0; return 1; } #if __MLIBC_POSIX_OPTION +#include #include +#include +#include +#include +#include #include #include -#include -#include #include #include +#include +#include #include -#include -#include -#include -#include -#include int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { auto ret = do_syscall(SYS_ioctl, fd, request, arg); @@ -482,17 +500,24 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { } int sys_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { - auto ret = do_cp_syscall(SYS_connect, sockfd, addr, addrlen); - if (int e = sc_error(ret); e) - return e; - return 0; + auto ret = do_cp_syscall(SYS_connect, sockfd, addr, addrlen); + if (int e = sc_error(ret); e) + return e; + return 0; } -int sys_pselect(int nfds, fd_set *readfds, fd_set *writefds, - fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask, int *num_events) { +int sys_pselect( + int nfds, + fd_set *readfds, + fd_set *writefds, + fd_set *exceptfds, + const struct timespec *timeout, + const sigset_t *sigmask, + int *num_events +) { // The Linux kernel sometimes modifies the timeout argument. struct timespec local_timeout; - if(timeout) + if (timeout) local_timeout = *timeout; // The Linux kernel really wants 7 arguments, even tho this is not supported @@ -505,8 +530,9 @@ int sys_pselect(int nfds, fd_set *readfds, fd_set *writefds, data.sigmask = sigmask; data.ss_len = NSIG / 8; - auto ret = do_cp_syscall(SYS_pselect6, nfds, readfds, writefds, - exceptfds, timeout ? &local_timeout : nullptr, &data); + auto ret = do_cp_syscall( + SYS_pselect6, nfds, readfds, writefds, exceptfds, timeout ? &local_timeout : nullptr, &data + ); if (int e = sc_error(ret); e) return e; *num_events = sc_int_result(ret); @@ -514,23 +540,23 @@ int sys_pselect(int nfds, fd_set *readfds, fd_set *writefds, } int sys_pipe(int *fds, int flags) { - if(flags) { - auto ret = do_syscall(SYS_pipe2, fds, flags); - if (int e = sc_error(ret); e) - return e; - return 0; - } else { - auto ret = do_syscall(SYS_pipe2, fds, 0); - if (int e = sc_error(ret); e) - return e; - return 0; - } + if (flags) { + auto ret = do_syscall(SYS_pipe2, fds, flags); + if (int e = sc_error(ret); e) + return e; + return 0; + } else { + auto ret = do_syscall(SYS_pipe2, fds, 0); + if (int e = sc_error(ret); e) + return e; + return 0; + } } int sys_fork(pid_t *child) { auto ret = do_syscall(SYS_clone, SIGCHLD, 0); if (int e = sc_error(ret); e) - return e; + return e; *child = sc_int_result(ret); return 0; } @@ -538,50 +564,50 @@ int sys_fork(pid_t *child) { int sys_waitpid(pid_t pid, int *status, int flags, struct rusage *ru, pid_t *ret_pid) { auto ret = do_syscall(SYS_wait4, pid, status, flags, ru); if (int e = sc_error(ret); e) - return e; + return e; *ret_pid = sc_int_result(ret); return 0; } int sys_execve(const char *path, char *const argv[], char *const envp[]) { - auto ret = do_syscall(SYS_execve, path, argv, envp); - if (int e = sc_error(ret); e) - return e; - return 0; + auto ret = do_syscall(SYS_execve, path, argv, envp); + if (int e = sc_error(ret); e) + return e; + return 0; } int sys_sigprocmask(int how, const sigset_t *set, sigset_t *old) { - auto ret = do_syscall(SYS_rt_sigprocmask, how, set, old, NSIG / 8); - if (int e = sc_error(ret); e) - return e; + auto ret = do_syscall(SYS_rt_sigprocmask, how, set, old, NSIG / 8); + if (int e = sc_error(ret); e) + return e; return 0; } int sys_setresuid(uid_t ruid, uid_t euid, uid_t suid) { auto ret = do_syscall(SYS_setresuid, ruid, euid, suid); - if (int e = sc_error(ret); e) - return e; + if (int e = sc_error(ret); e) + return e; return 0; } int sys_setresgid(gid_t rgid, gid_t egid, gid_t sgid) { auto ret = do_syscall(SYS_setresgid, rgid, egid, sgid); - if (int e = sc_error(ret); e) - return e; + if (int e = sc_error(ret); e) + return e; return 0; } int sys_getresuid(uid_t *ruid, uid_t *euid, uid_t *suid) { auto ret = do_syscall(SYS_getresuid, &ruid, &euid, &suid); - if (int e = sc_error(ret); e) - return e; + if (int e = sc_error(ret); e) + return e; return 0; } int sys_getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid) { auto ret = do_syscall(SYS_getresgid, &rgid, &egid, &sgid); - if (int e = sc_error(ret); e) - return e; + if (int e = sc_error(ret); e) + return e; return 0; } @@ -601,19 +627,16 @@ int sys_setregid(gid_t rgid, gid_t egid) { int sys_sysinfo(struct sysinfo *info) { auto ret = do_syscall(SYS_sysinfo, info); - if (int e = sc_error(ret); e) - return e; + if (int e = sc_error(ret); e) + return e; return 0; } -void sys_yield() { - do_syscall(SYS_sched_yield); -} +void sys_yield() { do_syscall(SYS_sched_yield); } int sys_clone(void *tcb, pid_t *pid_out, void *stack) { - unsigned long flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND - | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS - | CLONE_PARENT_SETTID; + unsigned long flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | + CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID; #if defined(__riscv) // TP should point to the address immediately after the TCB. @@ -630,7 +653,8 @@ int sys_clone(void *tcb, pid_t *pid_out, void *stack) { uint32_t gs; asm volatile("movw %%gs, %w0" : "=q"(gs)); - auto user_desc = reinterpret_cast(getAllocator().allocate(sizeof(struct user_desc))); + auto user_desc = + reinterpret_cast(getAllocator().allocate(sizeof(struct user_desc))); user_desc->entry_number = (gs & 0xffff) >> 3; user_desc->base_addr = uintptr_t(tcb); @@ -662,15 +686,15 @@ extern "C" const char __mlibc_syscall_end[1]; #endif int sys_before_cancellable_syscall(ucontext_t *uct) { #if defined(__x86_64__) - auto pc = reinterpret_cast(uct->uc_mcontext.gregs[REG_RIP]); + auto pc = reinterpret_cast(uct->uc_mcontext.gregs[REG_RIP]); #elif defined(__i386__) - auto pc = reinterpret_cast(uct->uc_mcontext.gregs[REG_EIP]); + auto pc = reinterpret_cast(uct->uc_mcontext.gregs[REG_EIP]); #elif defined(__riscv) - auto pc = reinterpret_cast(uct->uc_mcontext.gregs[REG_PC]); + auto pc = reinterpret_cast(uct->uc_mcontext.gregs[REG_PC]); #elif defined(__aarch64__) - auto pc = reinterpret_cast(uct->uc_mcontext.pc); + auto pc = reinterpret_cast(uct->uc_mcontext.pc); #elif defined(__m68k__) - auto pc = reinterpret_cast(uct->uc_mcontext.gregs[R_PC]); + auto pc = reinterpret_cast(uct->uc_mcontext.gregs[R_PC]); #else #error "Missing architecture specific code." #endif @@ -697,10 +721,17 @@ int sys_tcsetattr(int fd, int optional_action, const struct termios *attr) { int req; switch (optional_action) { - case TCSANOW: req = TCSETS; break; - case TCSADRAIN: req = TCSETSW; break; - case TCSAFLUSH: req = TCSETSF; break; - default: return EINVAL; + case TCSANOW: + req = TCSETS; + break; + case TCSADRAIN: + req = TCSETSW; + break; + case TCSAFLUSH: + req = TCSETSF; + break; + default: + return EINVAL; } auto ret = do_syscall(SYS_ioctl, fd, req, attr); @@ -766,8 +797,9 @@ int sys_setsockopt(int fd, int layer, int number, const void *buffer, socklen_t return 0; } -int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, - socklen_t *actual_length) { +int sys_sockname( + int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, socklen_t *actual_length +) { auto ret = do_syscall(SYS_getsockname, fd, addr_ptr, &max_addr_length); if (int e = sc_error(ret); e) return e; @@ -775,8 +807,9 @@ int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, return 0; } -int sys_peername(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, - socklen_t *actual_length) { +int sys_peername( + int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, socklen_t *actual_length +) { auto ret = do_syscall(SYS_getpeername, fd, addr_ptr, &max_addr_length); if (int e = sc_error(ret); e) return e; @@ -835,35 +868,37 @@ int sys_timer_create(clockid_t clk, struct sigevent *__restrict evp, timer_t *__ struct linux_uapi_sigevent *ksevp = 0; int timer_id; - switch(evp ? evp->sigev_notify : SIGEV_SIGNAL) { - case SIGEV_NONE: - case SIGEV_SIGNAL: { - if(evp) { - ksev.sigev_value = evp->sigev_value; - ksev.sigev_signo = evp->sigev_signo; - ksev.sigev_notify = evp->sigev_notify; - ksev.sigev_tid = 0; - ksevp = &ksev; - } - - auto ret = do_syscall(SYS_timer_create, clk, ksevp, &timer_id); - if (int e = sc_error(ret); e) { - return e; - } - *res = (void *) (intptr_t) timer_id; - break; + switch (evp ? evp->sigev_notify : SIGEV_SIGNAL) { + case SIGEV_NONE: + case SIGEV_SIGNAL: { + if (evp) { + ksev.sigev_value = evp->sigev_value; + ksev.sigev_signo = evp->sigev_signo; + ksev.sigev_notify = evp->sigev_notify; + ksev.sigev_tid = 0; + ksevp = &ksev; } - case SIGEV_THREAD: - __ensure(!"sys_timer_create with evp->sigev_notify == SIGEV_THREAD is unimplemented"); - [[fallthrough]]; - default: - return EINVAL; + + auto ret = do_syscall(SYS_timer_create, clk, ksevp, &timer_id); + if (int e = sc_error(ret); e) { + return e; + } + *res = (void *)(intptr_t)timer_id; + break; + } + case SIGEV_THREAD: + __ensure(!"sys_timer_create with evp->sigev_notify == SIGEV_THREAD is unimplemented"); + [[fallthrough]]; + default: + return EINVAL; } return 0; } -int sys_timer_settime(timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old) { +int sys_timer_settime( + timer_t t, int flags, const struct itimerspec *__restrict val, struct itimerspec *__restrict old +) { auto ret = do_syscall(SYS_timer_settime, t, flags, val, old); if (int e = sc_error(ret); e) { return e; @@ -872,7 +907,7 @@ int sys_timer_settime(timer_t t, int flags, const struct itimerspec *__restrict } int sys_timer_delete(timer_t t) { - __ensure((intptr_t) t >= 0); + __ensure((intptr_t)t >= 0); auto ret = do_syscall(SYS_timer_delete, t); if (int e = sc_error(ret); e) { return e; @@ -888,13 +923,11 @@ int sys_ptrace(long req, pid_t pid, void *addr, void *data, long *out) { return 0; } -int sys_open_dir(const char *path, int *fd) { - return sys_open(path, O_DIRECTORY, 0, fd); -} +int sys_open_dir(const char *path, int *fd) { return sys_open(path, O_DIRECTORY, 0, fd); } int sys_read_entries(int handle, void *buffer, size_t max_size, size_t *bytes_read) { auto ret = do_syscall(SYS_getdents64, handle, buffer, max_size); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *bytes_read = sc_int_result(ret); return 0; @@ -902,7 +935,7 @@ int sys_read_entries(int handle, void *buffer, size_t max_size, size_t *bytes_re int sys_prctl(int op, va_list ap, int *out) { unsigned long x[4]; - for(int i = 0; i < 4; i++) + for (int i = 0; i < 4; i++) x[i] = va_arg(ap, unsigned long); auto ret = do_syscall(SYS_prctl, op, x[0], x[1], x[2], x[3]); @@ -1002,8 +1035,13 @@ int sys_getaffinity(pid_t pid, size_t cpusetsize, cpu_set_t *mask) { return 0; } -int sys_mount(const char *source, const char *target, - const char *fstype, unsigned long flags, const void *data) { +int sys_mount( + const char *source, + const char *target, + const char *fstype, + unsigned long flags, + const void *data +) { auto ret = do_syscall(SYS_mount, source, target, fstype, flags, data); if (int e = sc_error(ret); e) return e; @@ -1039,7 +1077,9 @@ int sys_epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) { return 0; } -int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, int timeout, const sigset_t *sigmask, int *raised) { +int sys_epoll_pwait( + int epfd, struct epoll_event *ev, int n, int timeout, const sigset_t *sigmask, int *raised +) { auto ret = do_syscall(SYS_epoll_pwait, epfd, ev, n, timeout, sigmask, NSIG / 8); if (int e = sc_error(ret); e) return e; @@ -1071,7 +1111,9 @@ int sys_timerfd_create(int clockid, int flags, int *fd) { return 0; } -int sys_timerfd_settime(int fd, int flags, const struct itimerspec *value, struct itimerspec *oldvalue) { +int sys_timerfd_settime( + int fd, int flags, const struct itimerspec *value, struct itimerspec *oldvalue +) { auto ret = do_syscall(SYS_timerfd_settime, fd, flags, value, oldvalue); if (int e = sc_error(ret); e) return e; @@ -1122,7 +1164,8 @@ int sys_socketpair(int domain, int type_and_flags, int proto, int *fds) { return 0; } -int sys_getsockopt(int fd, int layer, int number, void *__restrict buffer, socklen_t *__restrict size) { +int +sys_getsockopt(int fd, int layer, int number, void *__restrict buffer, socklen_t *__restrict size) { auto ret = do_syscall(SYS_getsockopt, fd, layer, number, buffer, size, 0); if (int e = sc_error(ret); e) return e; @@ -1149,7 +1192,7 @@ int sys_ttyname(int fd, char *buf, size_t size) { return errno; char *procname; - if(int e = asprintf(&procname, "/proc/self/fd/%i", fd); e) + if (int e = asprintf(&procname, "/proc/self/fd/%i", fd); e) return ENOMEM; __ensure(procname); @@ -1203,7 +1246,7 @@ int sys_get_min_priority(int policy, int *out) { int sys_getschedparam(void *tcb, int *policy, struct sched_param *param) { auto t = reinterpret_cast(tcb); - if(!t->tid) { + if (!t->tid) { return ESRCH; } @@ -1222,7 +1265,7 @@ int sys_getschedparam(void *tcb, int *policy, struct sched_param *param) { int sys_setschedparam(void *tcb, int policy, const struct sched_param *param) { auto t = reinterpret_cast(tcb); - if(!t->tid) { + if (!t->tid) { return ESRCH; } @@ -1236,7 +1279,7 @@ int sys_if_indextoname(unsigned int index, char *name) { int fd = 0; int r = sys_socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, AF_UNSPEC, &fd); - if(r) + if (r) return r; struct ifreq ifr; @@ -1245,8 +1288,8 @@ int sys_if_indextoname(unsigned int index, char *name) { int ret = sys_ioctl(fd, SIOCGIFNAME, &ifr, NULL); close(fd); - if(ret) { - if(ret == ENODEV) + if (ret) { + if (ret == ENODEV) return ENXIO; return ret; } @@ -1260,7 +1303,7 @@ int sys_if_nametoindex(const char *name, unsigned int *ret) { int fd = 0; int r = sys_socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, AF_UNSPEC, &fd); - if(r) + if (r) return r; struct ifreq ifr; @@ -1269,7 +1312,7 @@ int sys_if_nametoindex(const char *name, unsigned int *ret) { r = sys_ioctl(fd, SIOCGIFINDEX, &ifr, NULL); close(fd); - if(r) { + if (r) { return r; } @@ -1280,9 +1323,9 @@ int sys_if_nametoindex(const char *name, unsigned int *ret) { int sys_ptsname(int fd, char *buffer, size_t length) { int index; - if(int e = sys_ioctl(fd, TIOCGPTN, &index, NULL); e) + if (int e = sys_ioctl(fd, TIOCGPTN, &index, NULL); e) return e; - if((size_t)snprintf(buffer, length, "/dev/pts/%d", index) >= length) { + if ((size_t)snprintf(buffer, length, "/dev/pts/%d", index) >= length) { return ERANGE; } return 0; @@ -1291,14 +1334,14 @@ int sys_ptsname(int fd, char *buffer, size_t length) { int sys_unlockpt(int fd) { int unlock = 0; - if(int e = sys_ioctl(fd, TIOCSPTLCK, &unlock, NULL); e) + if (int e = sys_ioctl(fd, TIOCSPTLCK, &unlock, NULL); e) return e; return 0; } int sys_thread_setname(void *tcb, const char *name) { - if(strlen(name) > 15) { + if (strlen(name) > 15) { return ERANGE; } @@ -1306,18 +1349,18 @@ int sys_thread_setname(void *tcb, const char *name) { char *path; int cs = 0; - if(asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { + if (asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { return ENOMEM; } pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); int fd; - if(int e = sys_open(path, O_WRONLY, 0, &fd); e) { + if (int e = sys_open(path, O_WRONLY, 0, &fd); e) { return e; } - if(int e = sys_write(fd, name, strlen(name) + 1, NULL)) { + if (int e = sys_write(fd, name, strlen(name) + 1, NULL)) { return e; } @@ -1334,18 +1377,18 @@ int sys_thread_getname(void *tcb, char *name, size_t size) { int cs = 0; ssize_t real_size = 0; - if(asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { + if (asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { return ENOMEM; } pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); int fd; - if(int e = sys_open(path, O_RDONLY | O_CLOEXEC, 0, &fd); e) { + if (int e = sys_open(path, O_RDONLY | O_CLOEXEC, 0, &fd); e) { return e; } - if(int e = sys_read(fd, name, size, &real_size)) { + if (int e = sys_read(fd, name, size, &real_size)) { return e; } @@ -1354,7 +1397,7 @@ int sys_thread_getname(void *tcb, char *name, size_t size) { pthread_setcancelstate(cs, 0); - if(static_cast(size) <= real_size) { + if (static_cast(size) <= real_size) { return ERANGE; } @@ -1411,14 +1454,12 @@ int sys_flock(int fd, int options) { return 0; } -int sys_seteuid(uid_t euid) { - return sys_setresuid(-1, euid, -1); -} +int sys_seteuid(uid_t euid) { return sys_setresuid(-1, euid, -1); } int sys_vm_remap(void *pointer, size_t size, size_t new_size, void **window) { auto ret = do_syscall(SYS_mremap, pointer, size, new_size, MREMAP_MAYMOVE); // TODO: musl fixes up EPERM errors from the kernel. - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *window = sc_ptr_result(ret); return 0; @@ -1441,23 +1482,23 @@ int sys_link(const char *old_path, const char *new_path) { // Inspired by musl (src/stat/statvfs.c:28 fixup function) static void statfs_to_statvfs(struct statfs *from, struct statvfs *to) { *to = { - .f_bsize = from->f_bsize, - .f_frsize = from->f_frsize ? from->f_frsize : from->f_bsize, - .f_blocks = from->f_blocks, - .f_bfree = from->f_bfree, - .f_bavail = from->f_bavail, - .f_files = from->f_files, - .f_ffree = from->f_ffree, - .f_favail = from->f_ffree, - .f_fsid = (unsigned long) from->f_fsid.__val[0], - .f_flag = from->f_flags, - .f_namemax = from->f_namelen, + .f_bsize = from->f_bsize, + .f_frsize = from->f_frsize ? from->f_frsize : from->f_bsize, + .f_blocks = from->f_blocks, + .f_bfree = from->f_bfree, + .f_bavail = from->f_bavail, + .f_files = from->f_files, + .f_ffree = from->f_ffree, + .f_favail = from->f_ffree, + .f_fsid = (unsigned long)from->f_fsid.__val[0], + .f_flag = from->f_flags, + .f_namemax = from->f_namelen, }; } int sys_statvfs(const char *path, struct statvfs *out) { struct statfs buf; - if(auto ret = sys_statfs(path, &buf); ret != 0) { + if (auto ret = sys_statfs(path, &buf); ret != 0) { return ret; } statfs_to_statvfs(&buf, out); @@ -1466,7 +1507,7 @@ int sys_statvfs(const char *path, struct statvfs *out) { int sys_fstatvfs(int fd, struct statvfs *out) { struct statfs buf; - if(auto ret = sys_fstatfs(fd, &buf); ret != 0) { + if (auto ret = sys_fstatfs(fd, &buf); ret != 0) { return ret; } statfs_to_statvfs(&buf, out); @@ -1474,48 +1515,48 @@ int sys_fstatvfs(int fd, struct statvfs *out) { } int sys_sysconf(int num, long *ret) { - switch(num) { - case _SC_OPEN_MAX: { - struct rlimit ru; - if(int e = sys_getrlimit(RLIMIT_NOFILE, &ru); e) { - return e; - } - *ret = (ru.rlim_cur == RLIM_INFINITY) ? -1 : ru.rlim_cur; - break; - } - case _SC_NPROCESSORS_ONLN: { - cpu_set_t set; - CPU_ZERO(&set); - if(int e = sys_getaffinity(0, sizeof(set), &set); e) { - return e; - } - *ret = CPU_COUNT(&set); - break; - } - case _SC_PHYS_PAGES: { - struct sysinfo info; - if(int e = sys_sysinfo(&info); e) { - return e; - } - unsigned unit = (info.mem_unit) ? info.mem_unit : 1; - *ret = std::min(long((info.totalram * unit) / PAGE_SIZE), LONG_MAX); - break; + switch (num) { + case _SC_OPEN_MAX: { + struct rlimit ru; + if (int e = sys_getrlimit(RLIMIT_NOFILE, &ru); e) { + return e; } - case _SC_CHILD_MAX: { - struct rlimit ru; - if(int e = sys_getrlimit(RLIMIT_NPROC, &ru); e) { - return e; - } - *ret = (ru.rlim_cur == RLIM_INFINITY) ? -1 : ru.rlim_cur; - break; + *ret = (ru.rlim_cur == RLIM_INFINITY) ? -1 : ru.rlim_cur; + break; + } + case _SC_NPROCESSORS_ONLN: { + cpu_set_t set; + CPU_ZERO(&set); + if (int e = sys_getaffinity(0, sizeof(set), &set); e) { + return e; } - case _SC_LINE_MAX: { - *ret = -1; - break; + *ret = CPU_COUNT(&set); + break; + } + case _SC_PHYS_PAGES: { + struct sysinfo info; + if (int e = sys_sysinfo(&info); e) { + return e; } - default: { - return EINVAL; + unsigned unit = (info.mem_unit) ? info.mem_unit : 1; + *ret = std::min(long((info.totalram * unit) / PAGE_SIZE), LONG_MAX); + break; + } + case _SC_CHILD_MAX: { + struct rlimit ru; + if (int e = sys_getrlimit(RLIMIT_NPROC, &ru); e) { + return e; } + *ret = (ru.rlim_cur == RLIM_INFINITY) ? -1 : ru.rlim_cur; + break; + } + case _SC_LINE_MAX: { + *ret = -1; + break; + } + default: { + return EINVAL; + } } return 0; @@ -1523,7 +1564,7 @@ int sys_sysconf(int num, long *ret) { int sys_semget(key_t key, int n, int fl, int *id) { auto ret = do_syscall(SYS_semget, key, n, fl); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *id = sc_int_result(ret); return 0; @@ -1531,7 +1572,7 @@ int sys_semget(key_t key, int n, int fl, int *id) { int sys_semctl(int semid, int semnum, int cmd, void *semun, int *out) { auto ret = do_syscall(SYS_semctl, semid, semnum, cmd | IPC_64, semun); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; *out = sc_int_result(ret); return 0; @@ -1539,7 +1580,7 @@ int sys_semctl(int semid, int semnum, int cmd, void *semun, int *out) { int sys_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { auto ret = do_syscall(SYS_waitid, idtype, id, info, options, 0); - if(int e = sc_error(ret); e) + if (int e = sc_error(ret); e) return e; return sc_int_result(ret); } @@ -1685,7 +1726,6 @@ int sys_mkdir(const char *path, mode_t mode) { return 0; } - int sys_mkdirat(int dirfd, const char *path, mode_t mode) { auto ret = do_syscall(SYS_mkdirat, dirfd, path, mode); if (int e = sc_error(ret); e) @@ -1859,9 +1899,7 @@ int sys_dup(int fd, int flags, int *newfd) { return 0; } -void sys_sync() { - do_syscall(SYS_sync); -} +void sys_sync() { do_syscall(SYS_sync); } int sys_fsync(int fd) { auto ret = do_syscall(SYS_fsync, fd); @@ -1890,26 +1928,22 @@ int sys_getentropy(void *buffer, size_t length) { return sys_getrandom(buffer, length, 0, &written); } -int sys_setxattr(const char *path, const char *name, const void *val, - size_t size, int flags) { +int sys_setxattr(const char *path, const char *name, const void *val, size_t size, int flags) { auto ret = do_syscall(SYS_setxattr, path, name, val, size, flags); return sc_error(ret); } -int sys_lsetxattr(const char *path, const char *name, const void *val, - size_t size, int flags) { +int sys_lsetxattr(const char *path, const char *name, const void *val, size_t size, int flags) { auto ret = do_syscall(SYS_lsetxattr, path, name, val, size, flags); return sc_error(ret); } -int sys_fsetxattr(int fd, const char *name, const void *val, - size_t size, int flags) { +int sys_fsetxattr(int fd, const char *name, const void *val, size_t size, int flags) { auto ret = do_syscall(SYS_fsetxattr, fd, name, val, size, flags); return sc_error(ret); } -int sys_getxattr(const char *path, const char *name, void *val, size_t size, - ssize_t *nread) { +int sys_getxattr(const char *path, const char *name, void *val, size_t size, ssize_t *nread) { auto ret = do_syscall(SYS_getxattr, path, name, val, size); if (int e = sc_error(ret); e) { return e; @@ -1919,8 +1953,7 @@ int sys_getxattr(const char *path, const char *name, void *val, size_t size, return 0; } -int sys_lgetxattr(const char *path, const char *name, void *val, size_t size, - ssize_t *nread) { +int sys_lgetxattr(const char *path, const char *name, void *val, size_t size, ssize_t *nread) { auto ret = do_syscall(SYS_lgetxattr, path, name, val, size); if (int e = sc_error(ret); e) { return e; @@ -1930,8 +1963,7 @@ int sys_lgetxattr(const char *path, const char *name, void *val, size_t size, return 0; } -int sys_fgetxattr(int fd, const char *name, void *val, size_t size, - ssize_t *nread) { +int sys_fgetxattr(int fd, const char *name, void *val, size_t size, ssize_t *nread) { auto ret = do_syscall(SYS_fgetxattr, fd, name, val, size); if (int e = sc_error(ret); e) { return e; @@ -1986,7 +2018,12 @@ int sys_flistxattr(int fd, char *list, size_t size, ssize_t *nread) { return 0; } -int sys_sigtimedwait(const sigset_t *__restrict set, siginfo_t *__restrict info, const struct timespec *__restrict timeout, int *out_signal) { +int sys_sigtimedwait( + const sigset_t *__restrict set, + siginfo_t *__restrict info, + const struct timespec *__restrict timeout, + int *out_signal +) { auto ret = do_syscall(SYS_rt_sigtimedwait, set, info, timeout, NSIG / 8); if (int e = sc_error(ret); e) @@ -2000,11 +2037,11 @@ int sys_sigtimedwait(const sigset_t *__restrict set, siginfo_t *__restrict info, #if __MLIBC_BSD_OPTION int sys_brk(void **out) { auto ret = do_syscall(SYS_brk, 0); - if(int e = sc_error(ret); e) { + if (int e = sc_error(ret); e) { return e; } - *out = (void *) sc_int_result(ret); + *out = (void *)sc_int_result(ret); return 0; } #endif // __MLIBC_BSD_OPTION @@ -2014,7 +2051,7 @@ int sys_brk(void **out) { int sys_personality(unsigned long persona, int *out) { auto ret = do_syscall(SYS_personality, persona); - if(int e = sc_error(ret); e) { + if (int e = sc_error(ret); e) { return e; } @@ -2026,15 +2063,15 @@ int sys_ioperm(unsigned long int from, unsigned long int num, int turn_on) { #if defined(SYS_ioperm) auto ret = do_syscall(SYS_ioperm, from, num, turn_on); - if(int e = sc_error(ret); e) { + if (int e = sc_error(ret); e) { return e; } return 0; #else - (void) from; - (void) num; - (void) turn_on; + (void)from; + (void)num; + (void)turn_on; return ENOSYS; #endif } @@ -2043,13 +2080,13 @@ int sys_iopl(int level) { #if defined(SYS_iopl) auto ret = do_syscall(SYS_iopl, level); - if(int e = sc_error(ret); e) { + if (int e = sc_error(ret); e) { return e; } return 0; #else - (void) level; + (void)level; return ENOSYS; #endif } diff --git a/sysdeps/linux/generic/thread.cpp b/sysdeps/linux/generic/thread.cpp index e413e4ff25..5994aef5ad 100644 --- a/sysdeps/linux/generic/thread.cpp +++ b/sysdeps/linux/generic/thread.cpp @@ -1,18 +1,18 @@ -#include +#include +#include #include +#include #include -#include -#include -#include #include -#include +#include +#include extern "C" void __mlibc_enter_thread(void *entry, void *user_arg) { // The linux kernel already sets the TCB in sys_clone(). auto tcb = mlibc::get_current_tcb(); // Wait until our parent sets up the TID. - while(!__atomic_load_n(&tcb->tid, __ATOMIC_RELAXED)) + while (!__atomic_load_n(&tcb->tid, __ATOMIC_RELAXED)) mlibc::sys_futex_wait(&tcb->tid, 0, nullptr); tcb->invokeThreadFunc(entry, user_arg); @@ -27,7 +27,15 @@ namespace mlibc { static constexpr size_t default_stacksize = 0x200000; -int sys_prepare_stack(void **stack, void *entry, void *user_arg, void *tcb, size_t *stack_size, size_t *guard_size, void **stack_base) { +int sys_prepare_stack( + void **stack, + void *entry, + void *user_arg, + void *tcb, + size_t *stack_size, + size_t *guard_size, + void **stack_base +) { (void)tcb; if (!*stack_size) *stack_size = default_stacksize; @@ -38,23 +46,22 @@ int sys_prepare_stack(void **stack, void *entry, void *user_arg, void *tcb, size *guard_size = 0; } else { map = reinterpret_cast( - mmap(nullptr, *stack_size + *guard_size, - PROT_NONE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) - ); - if (reinterpret_cast(map) == MAP_FAILED) + mmap(nullptr, *stack_size + *guard_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) + ); + if (reinterpret_cast(map) == MAP_FAILED) return EAGAIN; - int ret = mprotect(reinterpret_cast(map + *guard_size), *stack_size, - PROT_READ | PROT_WRITE); - if(ret) + int ret = mprotect( + reinterpret_cast(map + *guard_size), *stack_size, PROT_READ | PROT_WRITE + ); + if (ret) return EAGAIN; } - *stack_base = reinterpret_cast(map); - auto sp = reinterpret_cast(map + *guard_size + *stack_size); + *stack_base = reinterpret_cast(map); + auto sp = reinterpret_cast(map + *guard_size + *stack_size); *--sp = reinterpret_cast(user_arg); *--sp = reinterpret_cast(entry); - *stack = reinterpret_cast(sp); + *stack = reinterpret_cast(sp); return 0; } } // namespace mlibc diff --git a/sysdeps/linux/include/bits/syscall.h b/sysdeps/linux/include/bits/syscall.h index 680bb8c299..563d40c1bf 100644 --- a/sysdeps/linux/include/bits/syscall.h +++ b/sysdeps/linux/include/bits/syscall.h @@ -13,12 +13,12 @@ __sc_word_t __do_syscall1(long, __sc_word_t); __sc_word_t __do_syscall2(long, __sc_word_t, __sc_word_t); __sc_word_t __do_syscall3(long, __sc_word_t, __sc_word_t, __sc_word_t); __sc_word_t __do_syscall4(long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t); -__sc_word_t __do_syscall5(long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, - __sc_word_t); -__sc_word_t __do_syscall6(long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, - __sc_word_t, __sc_word_t); -__sc_word_t __do_syscall7(long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, - __sc_word_t, __sc_word_t, __sc_word_t); +__sc_word_t __do_syscall5(long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t); +__sc_word_t +__do_syscall6(long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t); +__sc_word_t __do_syscall7( + long, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t, __sc_word_t +); long __do_syscall_ret(unsigned long); #ifdef __cplusplus @@ -27,36 +27,43 @@ extern "C++" { /* Defining a syscall as a macro is more problematic in C++, since there's a high chance of * a name collision e.g foo.syscall() or foo::syscall. */ -inline long syscall(long n) { - return __do_syscall_ret(__do_syscall0(n)); -} -template -long syscall(long n, Arg0 a0) { +inline long syscall(long n) { return __do_syscall_ret(__do_syscall0(n)); } +template long syscall(long n, Arg0 a0) { return __do_syscall_ret(__do_syscall1(n, (long)a0)); } -template -long syscall(long n, Arg0 a0, Arg1 a1) { +template long syscall(long n, Arg0 a0, Arg1 a1) { return __do_syscall_ret(__do_syscall2(n, (long)a0, (long)a1)); } -template +template long syscall(long n, Arg0 a0, Arg1 a1, Arg2 a2) { return __do_syscall_ret(__do_syscall3(n, (long)a0, (long)a1, (long)a2)); } -template +template long syscall(long n, Arg0 a0, Arg1 a1, Arg2 a2, Arg3 a3) { return __do_syscall_ret(__do_syscall4(n, (long)a0, (long)a1, (long)a2, (long)a3)); } -template +template long syscall(long n, Arg0 a0, Arg1 a1, Arg2 a2, Arg3 a3, Arg4 a4) { return __do_syscall_ret(__do_syscall5(n, (long)a0, (long)a1, (long)a2, (long)a3, (long)a4)); } -template +template long syscall(long n, Arg0 a0, Arg1 a1, Arg2 a2, Arg3 a3, Arg4 a4, Arg5 a5) { - return __do_syscall_ret(__do_syscall6(n, (long)a0, (long)a1, (long)a2, (long)a3, (long)a4, (long)a5)); + return __do_syscall_ret( + __do_syscall6(n, (long)a0, (long)a1, (long)a2, (long)a3, (long)a4, (long)a5) + ); } -template +template < + typename Arg0, + typename Arg1, + typename Arg2, + typename Arg3, + typename Arg4, + typename Arg5, + typename Arg6> long syscall(long n, Arg0 a0, Arg1 a1, Arg2 a2, Arg3 a3, Arg4 a4, Arg5 a5, Arg6 a6) { - return __do_syscall_ret(__do_syscall7(n, (long)a0, (long)a1, (long)a2, (long)a3, (long)a4, (long)a5, (long)a6)); + return __do_syscall_ret( + __do_syscall7(n, (long)a0, (long)a1, (long)a2, (long)a3, (long)a4, (long)a5, (long)a6) + ); } } /* extern C++ */ @@ -74,19 +81,22 @@ long syscall(long n, Arg0 a0, Arg1 a1, Arg2 a2, Arg3 a3, Arg4 a4, Arg5 a5, Arg6 /* These syscall macros were copied from musl. */ #define __scc(x) ((__sc_word_t)(x)) #define __syscall0(n) __do_syscall0(n) -#define __syscall1(n,a) __do_syscall1(n,__scc(a)) -#define __syscall2(n,a,b) __do_syscall2(n,__scc(a),__scc(b)) -#define __syscall3(n,a,b,c) __do_syscall3(n,__scc(a),__scc(b),__scc(c)) -#define __syscall4(n,a,b,c,d) __do_syscall4(n,__scc(a),__scc(b),__scc(c),__scc(d)) -#define __syscall5(n,a,b,c,d,e) __do_syscall5(n,__scc(a),__scc(b),__scc(c),__scc(d),__scc(e)) -#define __syscall6(n,a,b,c,d,e,f) __do_syscall6(n,__scc(a),__scc(b),__scc(c),__scc(d),__scc(e),__scc(f)) -#define __syscall7(n,a,b,c,d,e,f,g) __do_syscall7(n,__scc(a),__scc(b),__scc(c),__scc(d),__scc(e),__scc(f),__scc(g)) -#define __SYSCALL_NARGS_X(a,b,c,d,e,f,g,h,n,...) n -#define __SYSCALL_NARGS(...) __SYSCALL_NARGS_X(__VA_ARGS__,7,6,5,4,3,2,1,0,) -#define __SYSCALL_CONCAT_X(a,b) a##b -#define __SYSCALL_CONCAT(a,b) __SYSCALL_CONCAT_X(a,b) -#define __SYSCALL_DISP(b,...) __SYSCALL_CONCAT(b,__SYSCALL_NARGS(__VA_ARGS__))(__VA_ARGS__) -#define __syscall(...) __SYSCALL_DISP(__syscall,__VA_ARGS__) +#define __syscall1(n, a) __do_syscall1(n, __scc(a)) +#define __syscall2(n, a, b) __do_syscall2(n, __scc(a), __scc(b)) +#define __syscall3(n, a, b, c) __do_syscall3(n, __scc(a), __scc(b), __scc(c)) +#define __syscall4(n, a, b, c, d) __do_syscall4(n, __scc(a), __scc(b), __scc(c), __scc(d)) +#define __syscall5(n, a, b, c, d, e) \ + __do_syscall5(n, __scc(a), __scc(b), __scc(c), __scc(d), __scc(e)) +#define __syscall6(n, a, b, c, d, e, f) \ + __do_syscall6(n, __scc(a), __scc(b), __scc(c), __scc(d), __scc(e), __scc(f)) +#define __syscall7(n, a, b, c, d, e, f, g) \ + __do_syscall7(n, __scc(a), __scc(b), __scc(c), __scc(d), __scc(e), __scc(f), __scc(g)) +#define __SYSCALL_NARGS_X(a, b, c, d, e, f, g, h, n, ...) n +#define __SYSCALL_NARGS(...) __SYSCALL_NARGS_X(__VA_ARGS__, 7, 6, 5, 4, 3, 2, 1, 0, ) +#define __SYSCALL_CONCAT_X(a, b) a##b +#define __SYSCALL_CONCAT(a, b) __SYSCALL_CONCAT_X(a, b) +#define __SYSCALL_DISP(b, ...) __SYSCALL_CONCAT(b, __SYSCALL_NARGS(__VA_ARGS__))(__VA_ARGS__) +#define __syscall(...) __SYSCALL_DISP(__syscall, __VA_ARGS__) #define syscall(...) __do_syscall_ret(__syscall(__VA_ARGS__)) #pragma GCC diagnostic pop diff --git a/sysdeps/linux/include/bits/syscall_aliases.h b/sysdeps/linux/include/bits/syscall_aliases.h index b929efc7c2..02aa02353e 100644 --- a/sysdeps/linux/include/bits/syscall_aliases.h +++ b/sysdeps/linux/include/bits/syscall_aliases.h @@ -2,1822 +2,1822 @@ #define __MLIBC_SYSCALL_ALIAS_BIT /* This file is autogenerated. Don't bother. */ /* Generator script: sysdeps/linux/update-syscall-list.py. */ -#ifdef __NR__llseek -# define SYS__llseek __NR__llseek +#ifdef __NR__llseek +#define SYS__llseek __NR__llseek #endif -#ifdef __NR__newselect -# define SYS__newselect __NR__newselect +#ifdef __NR__newselect +#define SYS__newselect __NR__newselect #endif -#ifdef __NR__sysctl -# define SYS__sysctl __NR__sysctl +#ifdef __NR__sysctl +#define SYS__sysctl __NR__sysctl #endif -#ifdef __NR_accept -# define SYS_accept __NR_accept +#ifdef __NR_accept +#define SYS_accept __NR_accept #endif -#ifdef __NR_accept4 -# define SYS_accept4 __NR_accept4 +#ifdef __NR_accept4 +#define SYS_accept4 __NR_accept4 #endif -#ifdef __NR_access -# define SYS_access __NR_access +#ifdef __NR_access +#define SYS_access __NR_access #endif -#ifdef __NR_acct -# define SYS_acct __NR_acct +#ifdef __NR_acct +#define SYS_acct __NR_acct #endif -#ifdef __NR_add_key -# define SYS_add_key __NR_add_key +#ifdef __NR_add_key +#define SYS_add_key __NR_add_key #endif -#ifdef __NR_adjtimex -# define SYS_adjtimex __NR_adjtimex +#ifdef __NR_adjtimex +#define SYS_adjtimex __NR_adjtimex #endif -#ifdef __NR_alarm -# define SYS_alarm __NR_alarm +#ifdef __NR_alarm +#define SYS_alarm __NR_alarm #endif -#ifdef __NR_arc_gettls -# define SYS_arc_gettls __NR_arc_gettls +#ifdef __NR_arc_gettls +#define SYS_arc_gettls __NR_arc_gettls #endif -#ifdef __NR_arc_settls -# define SYS_arc_settls __NR_arc_settls +#ifdef __NR_arc_settls +#define SYS_arc_settls __NR_arc_settls #endif -#ifdef __NR_arc_usr_cmpxchg -# define SYS_arc_usr_cmpxchg __NR_arc_usr_cmpxchg +#ifdef __NR_arc_usr_cmpxchg +#define SYS_arc_usr_cmpxchg __NR_arc_usr_cmpxchg #endif -#ifdef __NR_arch_prctl -# define SYS_arch_prctl __NR_arch_prctl +#ifdef __NR_arch_prctl +#define SYS_arch_prctl __NR_arch_prctl #endif -#ifdef __NR_arch_specific_syscall -# define SYS_arch_specific_syscall __NR_arch_specific_syscall +#ifdef __NR_arch_specific_syscall +#define SYS_arch_specific_syscall __NR_arch_specific_syscall #endif -#ifdef __NR_arm_fadvise64_64 -# define SYS_arm_fadvise64_64 __NR_arm_fadvise64_64 +#ifdef __NR_arm_fadvise64_64 +#define SYS_arm_fadvise64_64 __NR_arm_fadvise64_64 #endif -#ifdef __NR_atomic_barrier -# define SYS_atomic_barrier __NR_atomic_barrier +#ifdef __NR_atomic_barrier +#define SYS_atomic_barrier __NR_atomic_barrier #endif -#ifdef __NR_atomic_cmpxchg_32 -# define SYS_atomic_cmpxchg_32 __NR_atomic_cmpxchg_32 +#ifdef __NR_atomic_cmpxchg_32 +#define SYS_atomic_cmpxchg_32 __NR_atomic_cmpxchg_32 #endif -#ifdef __NR_bdflush -# define SYS_bdflush __NR_bdflush +#ifdef __NR_bdflush +#define SYS_bdflush __NR_bdflush #endif -#ifdef __NR_bind -# define SYS_bind __NR_bind +#ifdef __NR_bind +#define SYS_bind __NR_bind #endif -#ifdef __NR_bpf -# define SYS_bpf __NR_bpf +#ifdef __NR_bpf +#define SYS_bpf __NR_bpf #endif -#ifdef __NR_brk -# define SYS_brk __NR_brk +#ifdef __NR_brk +#define SYS_brk __NR_brk #endif -#ifdef __NR_cachectl -# define SYS_cachectl __NR_cachectl +#ifdef __NR_cachectl +#define SYS_cachectl __NR_cachectl #endif -#ifdef __NR_cacheflush -# define SYS_cacheflush __NR_cacheflush +#ifdef __NR_cacheflush +#define SYS_cacheflush __NR_cacheflush #endif -#ifdef __NR_capget -# define SYS_capget __NR_capget +#ifdef __NR_capget +#define SYS_capget __NR_capget #endif -#ifdef __NR_capset -# define SYS_capset __NR_capset +#ifdef __NR_capset +#define SYS_capset __NR_capset #endif -#ifdef __NR_chdir -# define SYS_chdir __NR_chdir +#ifdef __NR_chdir +#define SYS_chdir __NR_chdir #endif -#ifdef __NR_chmod -# define SYS_chmod __NR_chmod +#ifdef __NR_chmod +#define SYS_chmod __NR_chmod #endif -#ifdef __NR_chown -# define SYS_chown __NR_chown +#ifdef __NR_chown +#define SYS_chown __NR_chown #endif -#ifdef __NR_chown32 -# define SYS_chown32 __NR_chown32 +#ifdef __NR_chown32 +#define SYS_chown32 __NR_chown32 #endif -#ifdef __NR_chroot -# define SYS_chroot __NR_chroot +#ifdef __NR_chroot +#define SYS_chroot __NR_chroot #endif -#ifdef __NR_clock_adjtime -# define SYS_clock_adjtime __NR_clock_adjtime +#ifdef __NR_clock_adjtime +#define SYS_clock_adjtime __NR_clock_adjtime #endif -#ifdef __NR_clock_adjtime64 -# define SYS_clock_adjtime64 __NR_clock_adjtime64 +#ifdef __NR_clock_adjtime64 +#define SYS_clock_adjtime64 __NR_clock_adjtime64 #endif -#ifdef __NR_clock_getres -# define SYS_clock_getres __NR_clock_getres +#ifdef __NR_clock_getres +#define SYS_clock_getres __NR_clock_getres #endif -#ifdef __NR_clock_getres_time64 -# define SYS_clock_getres_time64 __NR_clock_getres_time64 +#ifdef __NR_clock_getres_time64 +#define SYS_clock_getres_time64 __NR_clock_getres_time64 #endif -#ifdef __NR_clock_gettime -# define SYS_clock_gettime __NR_clock_gettime +#ifdef __NR_clock_gettime +#define SYS_clock_gettime __NR_clock_gettime #endif -#ifdef __NR_clock_gettime64 -# define SYS_clock_gettime64 __NR_clock_gettime64 +#ifdef __NR_clock_gettime64 +#define SYS_clock_gettime64 __NR_clock_gettime64 #endif -#ifdef __NR_clock_nanosleep -# define SYS_clock_nanosleep __NR_clock_nanosleep +#ifdef __NR_clock_nanosleep +#define SYS_clock_nanosleep __NR_clock_nanosleep #endif -#ifdef __NR_clock_nanosleep_time64 -# define SYS_clock_nanosleep_time64 __NR_clock_nanosleep_time64 +#ifdef __NR_clock_nanosleep_time64 +#define SYS_clock_nanosleep_time64 __NR_clock_nanosleep_time64 #endif -#ifdef __NR_clock_settime -# define SYS_clock_settime __NR_clock_settime +#ifdef __NR_clock_settime +#define SYS_clock_settime __NR_clock_settime #endif -#ifdef __NR_clock_settime64 -# define SYS_clock_settime64 __NR_clock_settime64 +#ifdef __NR_clock_settime64 +#define SYS_clock_settime64 __NR_clock_settime64 #endif -#ifdef __NR_clone -# define SYS_clone __NR_clone +#ifdef __NR_clone +#define SYS_clone __NR_clone #endif -#ifdef __NR_clone2 -# define SYS_clone2 __NR_clone2 +#ifdef __NR_clone2 +#define SYS_clone2 __NR_clone2 #endif -#ifdef __NR_clone3 -# define SYS_clone3 __NR_clone3 +#ifdef __NR_clone3 +#define SYS_clone3 __NR_clone3 #endif -#ifdef __NR_close -# define SYS_close __NR_close +#ifdef __NR_close +#define SYS_close __NR_close #endif -#ifdef __NR_close_range -# define SYS_close_range __NR_close_range +#ifdef __NR_close_range +#define SYS_close_range __NR_close_range #endif -#ifdef __NR_connect -# define SYS_connect __NR_connect +#ifdef __NR_connect +#define SYS_connect __NR_connect #endif -#ifdef __NR_copy_file_range -# define SYS_copy_file_range __NR_copy_file_range +#ifdef __NR_copy_file_range +#define SYS_copy_file_range __NR_copy_file_range #endif -#ifdef __NR_creat -# define SYS_creat __NR_creat +#ifdef __NR_creat +#define SYS_creat __NR_creat #endif -#ifdef __NR_create_module -# define SYS_create_module __NR_create_module +#ifdef __NR_create_module +#define SYS_create_module __NR_create_module #endif -#ifdef __NR_delete_module -# define SYS_delete_module __NR_delete_module +#ifdef __NR_delete_module +#define SYS_delete_module __NR_delete_module #endif -#ifdef __NR_dipc -# define SYS_dipc __NR_dipc +#ifdef __NR_dipc +#define SYS_dipc __NR_dipc #endif -#ifdef __NR_dup -# define SYS_dup __NR_dup +#ifdef __NR_dup +#define SYS_dup __NR_dup #endif -#ifdef __NR_dup2 -# define SYS_dup2 __NR_dup2 +#ifdef __NR_dup2 +#define SYS_dup2 __NR_dup2 #endif -#ifdef __NR_dup3 -# define SYS_dup3 __NR_dup3 +#ifdef __NR_dup3 +#define SYS_dup3 __NR_dup3 #endif -#ifdef __NR_epoll_create -# define SYS_epoll_create __NR_epoll_create +#ifdef __NR_epoll_create +#define SYS_epoll_create __NR_epoll_create #endif -#ifdef __NR_epoll_create1 -# define SYS_epoll_create1 __NR_epoll_create1 +#ifdef __NR_epoll_create1 +#define SYS_epoll_create1 __NR_epoll_create1 #endif -#ifdef __NR_epoll_ctl -# define SYS_epoll_ctl __NR_epoll_ctl +#ifdef __NR_epoll_ctl +#define SYS_epoll_ctl __NR_epoll_ctl #endif -#ifdef __NR_epoll_ctl_old -# define SYS_epoll_ctl_old __NR_epoll_ctl_old +#ifdef __NR_epoll_ctl_old +#define SYS_epoll_ctl_old __NR_epoll_ctl_old #endif -#ifdef __NR_epoll_pwait -# define SYS_epoll_pwait __NR_epoll_pwait +#ifdef __NR_epoll_pwait +#define SYS_epoll_pwait __NR_epoll_pwait #endif -#ifdef __NR_epoll_pwait2 -# define SYS_epoll_pwait2 __NR_epoll_pwait2 +#ifdef __NR_epoll_pwait2 +#define SYS_epoll_pwait2 __NR_epoll_pwait2 #endif -#ifdef __NR_epoll_wait -# define SYS_epoll_wait __NR_epoll_wait +#ifdef __NR_epoll_wait +#define SYS_epoll_wait __NR_epoll_wait #endif -#ifdef __NR_epoll_wait_old -# define SYS_epoll_wait_old __NR_epoll_wait_old +#ifdef __NR_epoll_wait_old +#define SYS_epoll_wait_old __NR_epoll_wait_old #endif -#ifdef __NR_eventfd -# define SYS_eventfd __NR_eventfd +#ifdef __NR_eventfd +#define SYS_eventfd __NR_eventfd #endif -#ifdef __NR_eventfd2 -# define SYS_eventfd2 __NR_eventfd2 +#ifdef __NR_eventfd2 +#define SYS_eventfd2 __NR_eventfd2 #endif -#ifdef __NR_exec_with_loader -# define SYS_exec_with_loader __NR_exec_with_loader +#ifdef __NR_exec_with_loader +#define SYS_exec_with_loader __NR_exec_with_loader #endif -#ifdef __NR_execv -# define SYS_execv __NR_execv +#ifdef __NR_execv +#define SYS_execv __NR_execv #endif -#ifdef __NR_execve -# define SYS_execve __NR_execve +#ifdef __NR_execve +#define SYS_execve __NR_execve #endif -#ifdef __NR_execveat -# define SYS_execveat __NR_execveat +#ifdef __NR_execveat +#define SYS_execveat __NR_execveat #endif -#ifdef __NR_exit -# define SYS_exit __NR_exit +#ifdef __NR_exit +#define SYS_exit __NR_exit #endif -#ifdef __NR_exit_group -# define SYS_exit_group __NR_exit_group +#ifdef __NR_exit_group +#define SYS_exit_group __NR_exit_group #endif -#ifdef __NR_faccessat -# define SYS_faccessat __NR_faccessat +#ifdef __NR_faccessat +#define SYS_faccessat __NR_faccessat #endif -#ifdef __NR_faccessat2 -# define SYS_faccessat2 __NR_faccessat2 +#ifdef __NR_faccessat2 +#define SYS_faccessat2 __NR_faccessat2 #endif -#ifdef __NR_fadvise64 -# define SYS_fadvise64 __NR_fadvise64 +#ifdef __NR_fadvise64 +#define SYS_fadvise64 __NR_fadvise64 #endif -#ifdef __NR_fadvise64_64 -# define SYS_fadvise64_64 __NR_fadvise64_64 +#ifdef __NR_fadvise64_64 +#define SYS_fadvise64_64 __NR_fadvise64_64 #endif -#ifdef __NR_fallocate -# define SYS_fallocate __NR_fallocate +#ifdef __NR_fallocate +#define SYS_fallocate __NR_fallocate #endif -#ifdef __NR_fanotify_init -# define SYS_fanotify_init __NR_fanotify_init +#ifdef __NR_fanotify_init +#define SYS_fanotify_init __NR_fanotify_init #endif -#ifdef __NR_fanotify_mark -# define SYS_fanotify_mark __NR_fanotify_mark +#ifdef __NR_fanotify_mark +#define SYS_fanotify_mark __NR_fanotify_mark #endif -#ifdef __NR_fchdir -# define SYS_fchdir __NR_fchdir +#ifdef __NR_fchdir +#define SYS_fchdir __NR_fchdir #endif -#ifdef __NR_fchmod -# define SYS_fchmod __NR_fchmod +#ifdef __NR_fchmod +#define SYS_fchmod __NR_fchmod #endif -#ifdef __NR_fchmodat -# define SYS_fchmodat __NR_fchmodat +#ifdef __NR_fchmodat +#define SYS_fchmodat __NR_fchmodat #endif -#ifdef __NR_fchown -# define SYS_fchown __NR_fchown +#ifdef __NR_fchown +#define SYS_fchown __NR_fchown #endif -#ifdef __NR_fchown32 -# define SYS_fchown32 __NR_fchown32 +#ifdef __NR_fchown32 +#define SYS_fchown32 __NR_fchown32 #endif -#ifdef __NR_fchownat -# define SYS_fchownat __NR_fchownat +#ifdef __NR_fchownat +#define SYS_fchownat __NR_fchownat #endif -#ifdef __NR_fcntl -# define SYS_fcntl __NR_fcntl +#ifdef __NR_fcntl +#define SYS_fcntl __NR_fcntl #endif -#ifdef __NR_fcntl64 -# define SYS_fcntl64 __NR_fcntl64 +#ifdef __NR_fcntl64 +#define SYS_fcntl64 __NR_fcntl64 #endif -#ifdef __NR_fdatasync -# define SYS_fdatasync __NR_fdatasync +#ifdef __NR_fdatasync +#define SYS_fdatasync __NR_fdatasync #endif -#ifdef __NR_fgetxattr -# define SYS_fgetxattr __NR_fgetxattr +#ifdef __NR_fgetxattr +#define SYS_fgetxattr __NR_fgetxattr #endif -#ifdef __NR_finit_module -# define SYS_finit_module __NR_finit_module +#ifdef __NR_finit_module +#define SYS_finit_module __NR_finit_module #endif -#ifdef __NR_flistxattr -# define SYS_flistxattr __NR_flistxattr +#ifdef __NR_flistxattr +#define SYS_flistxattr __NR_flistxattr #endif -#ifdef __NR_flock -# define SYS_flock __NR_flock +#ifdef __NR_flock +#define SYS_flock __NR_flock #endif -#ifdef __NR_fork -# define SYS_fork __NR_fork +#ifdef __NR_fork +#define SYS_fork __NR_fork #endif -#ifdef __NR_fremovexattr -# define SYS_fremovexattr __NR_fremovexattr +#ifdef __NR_fremovexattr +#define SYS_fremovexattr __NR_fremovexattr #endif -#ifdef __NR_fsconfig -# define SYS_fsconfig __NR_fsconfig +#ifdef __NR_fsconfig +#define SYS_fsconfig __NR_fsconfig #endif -#ifdef __NR_fsetxattr -# define SYS_fsetxattr __NR_fsetxattr +#ifdef __NR_fsetxattr +#define SYS_fsetxattr __NR_fsetxattr #endif -#ifdef __NR_fsmount -# define SYS_fsmount __NR_fsmount +#ifdef __NR_fsmount +#define SYS_fsmount __NR_fsmount #endif -#ifdef __NR_fsopen -# define SYS_fsopen __NR_fsopen +#ifdef __NR_fsopen +#define SYS_fsopen __NR_fsopen #endif -#ifdef __NR_fspick -# define SYS_fspick __NR_fspick +#ifdef __NR_fspick +#define SYS_fspick __NR_fspick #endif -#ifdef __NR_fstat -# define SYS_fstat __NR_fstat +#ifdef __NR_fstat +#define SYS_fstat __NR_fstat #endif -#ifdef __NR_fstat64 -# define SYS_fstat64 __NR_fstat64 +#ifdef __NR_fstat64 +#define SYS_fstat64 __NR_fstat64 #endif -#ifdef __NR_fstatat64 -# define SYS_fstatat64 __NR_fstatat64 +#ifdef __NR_fstatat64 +#define SYS_fstatat64 __NR_fstatat64 #endif -#ifdef __NR_fstatfs -# define SYS_fstatfs __NR_fstatfs +#ifdef __NR_fstatfs +#define SYS_fstatfs __NR_fstatfs #endif -#ifdef __NR_fstatfs64 -# define SYS_fstatfs64 __NR_fstatfs64 +#ifdef __NR_fstatfs64 +#define SYS_fstatfs64 __NR_fstatfs64 #endif -#ifdef __NR_fsync -# define SYS_fsync __NR_fsync +#ifdef __NR_fsync +#define SYS_fsync __NR_fsync #endif -#ifdef __NR_ftruncate -# define SYS_ftruncate __NR_ftruncate +#ifdef __NR_ftruncate +#define SYS_ftruncate __NR_ftruncate #endif -#ifdef __NR_ftruncate64 -# define SYS_ftruncate64 __NR_ftruncate64 +#ifdef __NR_ftruncate64 +#define SYS_ftruncate64 __NR_ftruncate64 #endif -#ifdef __NR_futex -# define SYS_futex __NR_futex +#ifdef __NR_futex +#define SYS_futex __NR_futex #endif -#ifdef __NR_futex_time64 -# define SYS_futex_time64 __NR_futex_time64 +#ifdef __NR_futex_time64 +#define SYS_futex_time64 __NR_futex_time64 #endif -#ifdef __NR_futex_waitv -# define SYS_futex_waitv __NR_futex_waitv +#ifdef __NR_futex_waitv +#define SYS_futex_waitv __NR_futex_waitv #endif -#ifdef __NR_futimesat -# define SYS_futimesat __NR_futimesat +#ifdef __NR_futimesat +#define SYS_futimesat __NR_futimesat #endif -#ifdef __NR_get_kernel_syms -# define SYS_get_kernel_syms __NR_get_kernel_syms +#ifdef __NR_get_kernel_syms +#define SYS_get_kernel_syms __NR_get_kernel_syms #endif -#ifdef __NR_get_mempolicy -# define SYS_get_mempolicy __NR_get_mempolicy +#ifdef __NR_get_mempolicy +#define SYS_get_mempolicy __NR_get_mempolicy #endif -#ifdef __NR_get_robust_list -# define SYS_get_robust_list __NR_get_robust_list +#ifdef __NR_get_robust_list +#define SYS_get_robust_list __NR_get_robust_list #endif -#ifdef __NR_get_thread_area -# define SYS_get_thread_area __NR_get_thread_area +#ifdef __NR_get_thread_area +#define SYS_get_thread_area __NR_get_thread_area #endif -#ifdef __NR_getcpu -# define SYS_getcpu __NR_getcpu +#ifdef __NR_getcpu +#define SYS_getcpu __NR_getcpu #endif -#ifdef __NR_getcwd -# define SYS_getcwd __NR_getcwd +#ifdef __NR_getcwd +#define SYS_getcwd __NR_getcwd #endif -#ifdef __NR_getdents -# define SYS_getdents __NR_getdents +#ifdef __NR_getdents +#define SYS_getdents __NR_getdents #endif -#ifdef __NR_getdents64 -# define SYS_getdents64 __NR_getdents64 +#ifdef __NR_getdents64 +#define SYS_getdents64 __NR_getdents64 #endif -#ifdef __NR_getdomainname -# define SYS_getdomainname __NR_getdomainname +#ifdef __NR_getdomainname +#define SYS_getdomainname __NR_getdomainname #endif -#ifdef __NR_getdtablesize -# define SYS_getdtablesize __NR_getdtablesize +#ifdef __NR_getdtablesize +#define SYS_getdtablesize __NR_getdtablesize #endif -#ifdef __NR_getegid -# define SYS_getegid __NR_getegid +#ifdef __NR_getegid +#define SYS_getegid __NR_getegid #endif -#ifdef __NR_getegid32 -# define SYS_getegid32 __NR_getegid32 +#ifdef __NR_getegid32 +#define SYS_getegid32 __NR_getegid32 #endif -#ifdef __NR_geteuid -# define SYS_geteuid __NR_geteuid +#ifdef __NR_geteuid +#define SYS_geteuid __NR_geteuid #endif -#ifdef __NR_geteuid32 -# define SYS_geteuid32 __NR_geteuid32 +#ifdef __NR_geteuid32 +#define SYS_geteuid32 __NR_geteuid32 #endif -#ifdef __NR_getgid -# define SYS_getgid __NR_getgid +#ifdef __NR_getgid +#define SYS_getgid __NR_getgid #endif -#ifdef __NR_getgid32 -# define SYS_getgid32 __NR_getgid32 +#ifdef __NR_getgid32 +#define SYS_getgid32 __NR_getgid32 #endif -#ifdef __NR_getgroups -# define SYS_getgroups __NR_getgroups +#ifdef __NR_getgroups +#define SYS_getgroups __NR_getgroups #endif -#ifdef __NR_getgroups32 -# define SYS_getgroups32 __NR_getgroups32 +#ifdef __NR_getgroups32 +#define SYS_getgroups32 __NR_getgroups32 #endif -#ifdef __NR_gethostname -# define SYS_gethostname __NR_gethostname +#ifdef __NR_gethostname +#define SYS_gethostname __NR_gethostname #endif -#ifdef __NR_getitimer -# define SYS_getitimer __NR_getitimer +#ifdef __NR_getitimer +#define SYS_getitimer __NR_getitimer #endif -#ifdef __NR_getpagesize -# define SYS_getpagesize __NR_getpagesize +#ifdef __NR_getpagesize +#define SYS_getpagesize __NR_getpagesize #endif -#ifdef __NR_getpeername -# define SYS_getpeername __NR_getpeername +#ifdef __NR_getpeername +#define SYS_getpeername __NR_getpeername #endif -#ifdef __NR_getpgid -# define SYS_getpgid __NR_getpgid +#ifdef __NR_getpgid +#define SYS_getpgid __NR_getpgid #endif -#ifdef __NR_getpgrp -# define SYS_getpgrp __NR_getpgrp +#ifdef __NR_getpgrp +#define SYS_getpgrp __NR_getpgrp #endif -#ifdef __NR_getpid -# define SYS_getpid __NR_getpid +#ifdef __NR_getpid +#define SYS_getpid __NR_getpid #endif -#ifdef __NR_getpmsg -# define SYS_getpmsg __NR_getpmsg +#ifdef __NR_getpmsg +#define SYS_getpmsg __NR_getpmsg #endif -#ifdef __NR_getppid -# define SYS_getppid __NR_getppid +#ifdef __NR_getppid +#define SYS_getppid __NR_getppid #endif -#ifdef __NR_getpriority -# define SYS_getpriority __NR_getpriority +#ifdef __NR_getpriority +#define SYS_getpriority __NR_getpriority #endif -#ifdef __NR_getrandom -# define SYS_getrandom __NR_getrandom +#ifdef __NR_getrandom +#define SYS_getrandom __NR_getrandom #endif -#ifdef __NR_getresgid -# define SYS_getresgid __NR_getresgid +#ifdef __NR_getresgid +#define SYS_getresgid __NR_getresgid #endif -#ifdef __NR_getresgid32 -# define SYS_getresgid32 __NR_getresgid32 +#ifdef __NR_getresgid32 +#define SYS_getresgid32 __NR_getresgid32 #endif -#ifdef __NR_getresuid -# define SYS_getresuid __NR_getresuid +#ifdef __NR_getresuid +#define SYS_getresuid __NR_getresuid #endif -#ifdef __NR_getresuid32 -# define SYS_getresuid32 __NR_getresuid32 +#ifdef __NR_getresuid32 +#define SYS_getresuid32 __NR_getresuid32 #endif -#ifdef __NR_getrlimit -# define SYS_getrlimit __NR_getrlimit +#ifdef __NR_getrlimit +#define SYS_getrlimit __NR_getrlimit #endif -#ifdef __NR_getrusage -# define SYS_getrusage __NR_getrusage +#ifdef __NR_getrusage +#define SYS_getrusage __NR_getrusage #endif -#ifdef __NR_getsid -# define SYS_getsid __NR_getsid +#ifdef __NR_getsid +#define SYS_getsid __NR_getsid #endif -#ifdef __NR_getsockname -# define SYS_getsockname __NR_getsockname +#ifdef __NR_getsockname +#define SYS_getsockname __NR_getsockname #endif -#ifdef __NR_getsockopt -# define SYS_getsockopt __NR_getsockopt +#ifdef __NR_getsockopt +#define SYS_getsockopt __NR_getsockopt #endif -#ifdef __NR_gettid -# define SYS_gettid __NR_gettid +#ifdef __NR_gettid +#define SYS_gettid __NR_gettid #endif -#ifdef __NR_gettimeofday -# define SYS_gettimeofday __NR_gettimeofday +#ifdef __NR_gettimeofday +#define SYS_gettimeofday __NR_gettimeofday #endif -#ifdef __NR_getuid -# define SYS_getuid __NR_getuid +#ifdef __NR_getuid +#define SYS_getuid __NR_getuid #endif -#ifdef __NR_getuid32 -# define SYS_getuid32 __NR_getuid32 +#ifdef __NR_getuid32 +#define SYS_getuid32 __NR_getuid32 #endif -#ifdef __NR_getunwind -# define SYS_getunwind __NR_getunwind +#ifdef __NR_getunwind +#define SYS_getunwind __NR_getunwind #endif -#ifdef __NR_getxattr -# define SYS_getxattr __NR_getxattr +#ifdef __NR_getxattr +#define SYS_getxattr __NR_getxattr #endif -#ifdef __NR_getxgid -# define SYS_getxgid __NR_getxgid +#ifdef __NR_getxgid +#define SYS_getxgid __NR_getxgid #endif -#ifdef __NR_getxpid -# define SYS_getxpid __NR_getxpid +#ifdef __NR_getxpid +#define SYS_getxpid __NR_getxpid #endif -#ifdef __NR_getxuid -# define SYS_getxuid __NR_getxuid +#ifdef __NR_getxuid +#define SYS_getxuid __NR_getxuid #endif -#ifdef __NR_idle -# define SYS_idle __NR_idle +#ifdef __NR_idle +#define SYS_idle __NR_idle #endif -#ifdef __NR_init_module -# define SYS_init_module __NR_init_module +#ifdef __NR_init_module +#define SYS_init_module __NR_init_module #endif -#ifdef __NR_inotify_add_watch -# define SYS_inotify_add_watch __NR_inotify_add_watch +#ifdef __NR_inotify_add_watch +#define SYS_inotify_add_watch __NR_inotify_add_watch #endif -#ifdef __NR_inotify_init -# define SYS_inotify_init __NR_inotify_init +#ifdef __NR_inotify_init +#define SYS_inotify_init __NR_inotify_init #endif -#ifdef __NR_inotify_init1 -# define SYS_inotify_init1 __NR_inotify_init1 +#ifdef __NR_inotify_init1 +#define SYS_inotify_init1 __NR_inotify_init1 #endif -#ifdef __NR_inotify_rm_watch -# define SYS_inotify_rm_watch __NR_inotify_rm_watch +#ifdef __NR_inotify_rm_watch +#define SYS_inotify_rm_watch __NR_inotify_rm_watch #endif -#ifdef __NR_io_cancel -# define SYS_io_cancel __NR_io_cancel +#ifdef __NR_io_cancel +#define SYS_io_cancel __NR_io_cancel #endif -#ifdef __NR_io_destroy -# define SYS_io_destroy __NR_io_destroy +#ifdef __NR_io_destroy +#define SYS_io_destroy __NR_io_destroy #endif -#ifdef __NR_io_getevents -# define SYS_io_getevents __NR_io_getevents +#ifdef __NR_io_getevents +#define SYS_io_getevents __NR_io_getevents #endif -#ifdef __NR_io_pgetevents -# define SYS_io_pgetevents __NR_io_pgetevents +#ifdef __NR_io_pgetevents +#define SYS_io_pgetevents __NR_io_pgetevents #endif -#ifdef __NR_io_pgetevents_time64 -# define SYS_io_pgetevents_time64 __NR_io_pgetevents_time64 +#ifdef __NR_io_pgetevents_time64 +#define SYS_io_pgetevents_time64 __NR_io_pgetevents_time64 #endif -#ifdef __NR_io_setup -# define SYS_io_setup __NR_io_setup +#ifdef __NR_io_setup +#define SYS_io_setup __NR_io_setup #endif -#ifdef __NR_io_submit -# define SYS_io_submit __NR_io_submit +#ifdef __NR_io_submit +#define SYS_io_submit __NR_io_submit #endif -#ifdef __NR_io_uring_enter -# define SYS_io_uring_enter __NR_io_uring_enter +#ifdef __NR_io_uring_enter +#define SYS_io_uring_enter __NR_io_uring_enter #endif -#ifdef __NR_io_uring_register -# define SYS_io_uring_register __NR_io_uring_register +#ifdef __NR_io_uring_register +#define SYS_io_uring_register __NR_io_uring_register #endif -#ifdef __NR_io_uring_setup -# define SYS_io_uring_setup __NR_io_uring_setup +#ifdef __NR_io_uring_setup +#define SYS_io_uring_setup __NR_io_uring_setup #endif -#ifdef __NR_ioctl -# define SYS_ioctl __NR_ioctl +#ifdef __NR_ioctl +#define SYS_ioctl __NR_ioctl #endif -#ifdef __NR_ioperm -# define SYS_ioperm __NR_ioperm +#ifdef __NR_ioperm +#define SYS_ioperm __NR_ioperm #endif -#ifdef __NR_iopl -# define SYS_iopl __NR_iopl +#ifdef __NR_iopl +#define SYS_iopl __NR_iopl #endif -#ifdef __NR_ioprio_get -# define SYS_ioprio_get __NR_ioprio_get +#ifdef __NR_ioprio_get +#define SYS_ioprio_get __NR_ioprio_get #endif -#ifdef __NR_ioprio_set -# define SYS_ioprio_set __NR_ioprio_set +#ifdef __NR_ioprio_set +#define SYS_ioprio_set __NR_ioprio_set #endif -#ifdef __NR_ipc -# define SYS_ipc __NR_ipc +#ifdef __NR_ipc +#define SYS_ipc __NR_ipc #endif -#ifdef __NR_kcmp -# define SYS_kcmp __NR_kcmp +#ifdef __NR_kcmp +#define SYS_kcmp __NR_kcmp #endif -#ifdef __NR_kern_features -# define SYS_kern_features __NR_kern_features +#ifdef __NR_kern_features +#define SYS_kern_features __NR_kern_features #endif -#ifdef __NR_kexec_file_load -# define SYS_kexec_file_load __NR_kexec_file_load +#ifdef __NR_kexec_file_load +#define SYS_kexec_file_load __NR_kexec_file_load #endif -#ifdef __NR_kexec_load -# define SYS_kexec_load __NR_kexec_load +#ifdef __NR_kexec_load +#define SYS_kexec_load __NR_kexec_load #endif -#ifdef __NR_keyctl -# define SYS_keyctl __NR_keyctl +#ifdef __NR_keyctl +#define SYS_keyctl __NR_keyctl #endif -#ifdef __NR_kill -# define SYS_kill __NR_kill +#ifdef __NR_kill +#define SYS_kill __NR_kill #endif -#ifdef __NR_landlock_add_rule -# define SYS_landlock_add_rule __NR_landlock_add_rule +#ifdef __NR_landlock_add_rule +#define SYS_landlock_add_rule __NR_landlock_add_rule #endif -#ifdef __NR_landlock_create_ruleset -# define SYS_landlock_create_ruleset __NR_landlock_create_ruleset +#ifdef __NR_landlock_create_ruleset +#define SYS_landlock_create_ruleset __NR_landlock_create_ruleset #endif -#ifdef __NR_landlock_restrict_self -# define SYS_landlock_restrict_self __NR_landlock_restrict_self +#ifdef __NR_landlock_restrict_self +#define SYS_landlock_restrict_self __NR_landlock_restrict_self #endif -#ifdef __NR_lchown -# define SYS_lchown __NR_lchown +#ifdef __NR_lchown +#define SYS_lchown __NR_lchown #endif -#ifdef __NR_lchown32 -# define SYS_lchown32 __NR_lchown32 +#ifdef __NR_lchown32 +#define SYS_lchown32 __NR_lchown32 #endif -#ifdef __NR_lgetxattr -# define SYS_lgetxattr __NR_lgetxattr +#ifdef __NR_lgetxattr +#define SYS_lgetxattr __NR_lgetxattr #endif -#ifdef __NR_link -# define SYS_link __NR_link +#ifdef __NR_link +#define SYS_link __NR_link #endif -#ifdef __NR_linkat -# define SYS_linkat __NR_linkat +#ifdef __NR_linkat +#define SYS_linkat __NR_linkat #endif -#ifdef __NR_listen -# define SYS_listen __NR_listen +#ifdef __NR_listen +#define SYS_listen __NR_listen #endif -#ifdef __NR_listxattr -# define SYS_listxattr __NR_listxattr +#ifdef __NR_listxattr +#define SYS_listxattr __NR_listxattr #endif -#ifdef __NR_llistxattr -# define SYS_llistxattr __NR_llistxattr +#ifdef __NR_llistxattr +#define SYS_llistxattr __NR_llistxattr #endif -#ifdef __NR_llseek -# define SYS_llseek __NR_llseek +#ifdef __NR_llseek +#define SYS_llseek __NR_llseek #endif -#ifdef __NR_lookup_dcookie -# define SYS_lookup_dcookie __NR_lookup_dcookie +#ifdef __NR_lookup_dcookie +#define SYS_lookup_dcookie __NR_lookup_dcookie #endif -#ifdef __NR_lremovexattr -# define SYS_lremovexattr __NR_lremovexattr +#ifdef __NR_lremovexattr +#define SYS_lremovexattr __NR_lremovexattr #endif -#ifdef __NR_lseek -# define SYS_lseek __NR_lseek +#ifdef __NR_lseek +#define SYS_lseek __NR_lseek #endif -#ifdef __NR_lsetxattr -# define SYS_lsetxattr __NR_lsetxattr +#ifdef __NR_lsetxattr +#define SYS_lsetxattr __NR_lsetxattr #endif -#ifdef __NR_lstat -# define SYS_lstat __NR_lstat +#ifdef __NR_lstat +#define SYS_lstat __NR_lstat #endif -#ifdef __NR_lstat64 -# define SYS_lstat64 __NR_lstat64 +#ifdef __NR_lstat64 +#define SYS_lstat64 __NR_lstat64 #endif -#ifdef __NR_madvise -# define SYS_madvise __NR_madvise +#ifdef __NR_madvise +#define SYS_madvise __NR_madvise #endif -#ifdef __NR_mbind -# define SYS_mbind __NR_mbind +#ifdef __NR_mbind +#define SYS_mbind __NR_mbind #endif -#ifdef __NR_membarrier -# define SYS_membarrier __NR_membarrier +#ifdef __NR_membarrier +#define SYS_membarrier __NR_membarrier #endif -#ifdef __NR_memfd_create -# define SYS_memfd_create __NR_memfd_create +#ifdef __NR_memfd_create +#define SYS_memfd_create __NR_memfd_create #endif -#ifdef __NR_memfd_secret -# define SYS_memfd_secret __NR_memfd_secret +#ifdef __NR_memfd_secret +#define SYS_memfd_secret __NR_memfd_secret #endif -#ifdef __NR_memory_ordering -# define SYS_memory_ordering __NR_memory_ordering +#ifdef __NR_memory_ordering +#define SYS_memory_ordering __NR_memory_ordering #endif -#ifdef __NR_migrate_pages -# define SYS_migrate_pages __NR_migrate_pages +#ifdef __NR_migrate_pages +#define SYS_migrate_pages __NR_migrate_pages #endif -#ifdef __NR_mincore -# define SYS_mincore __NR_mincore +#ifdef __NR_mincore +#define SYS_mincore __NR_mincore #endif -#ifdef __NR_mkdir -# define SYS_mkdir __NR_mkdir +#ifdef __NR_mkdir +#define SYS_mkdir __NR_mkdir #endif -#ifdef __NR_mkdirat -# define SYS_mkdirat __NR_mkdirat +#ifdef __NR_mkdirat +#define SYS_mkdirat __NR_mkdirat #endif -#ifdef __NR_mknod -# define SYS_mknod __NR_mknod +#ifdef __NR_mknod +#define SYS_mknod __NR_mknod #endif -#ifdef __NR_mknodat -# define SYS_mknodat __NR_mknodat +#ifdef __NR_mknodat +#define SYS_mknodat __NR_mknodat #endif -#ifdef __NR_mlock -# define SYS_mlock __NR_mlock +#ifdef __NR_mlock +#define SYS_mlock __NR_mlock #endif -#ifdef __NR_mlock2 -# define SYS_mlock2 __NR_mlock2 +#ifdef __NR_mlock2 +#define SYS_mlock2 __NR_mlock2 #endif -#ifdef __NR_mlockall -# define SYS_mlockall __NR_mlockall +#ifdef __NR_mlockall +#define SYS_mlockall __NR_mlockall #endif -#ifdef __NR_mmap -# define SYS_mmap __NR_mmap +#ifdef __NR_mmap +#define SYS_mmap __NR_mmap #endif -#ifdef __NR_mmap2 -# define SYS_mmap2 __NR_mmap2 +#ifdef __NR_mmap2 +#define SYS_mmap2 __NR_mmap2 #endif -#ifdef __NR_modify_ldt -# define SYS_modify_ldt __NR_modify_ldt +#ifdef __NR_modify_ldt +#define SYS_modify_ldt __NR_modify_ldt #endif -#ifdef __NR_mount -# define SYS_mount __NR_mount +#ifdef __NR_mount +#define SYS_mount __NR_mount #endif -#ifdef __NR_mount_setattr -# define SYS_mount_setattr __NR_mount_setattr +#ifdef __NR_mount_setattr +#define SYS_mount_setattr __NR_mount_setattr #endif -#ifdef __NR_move_mount -# define SYS_move_mount __NR_move_mount +#ifdef __NR_move_mount +#define SYS_move_mount __NR_move_mount #endif -#ifdef __NR_move_pages -# define SYS_move_pages __NR_move_pages +#ifdef __NR_move_pages +#define SYS_move_pages __NR_move_pages #endif -#ifdef __NR_mprotect -# define SYS_mprotect __NR_mprotect +#ifdef __NR_mprotect +#define SYS_mprotect __NR_mprotect #endif -#ifdef __NR_mq_getsetattr -# define SYS_mq_getsetattr __NR_mq_getsetattr +#ifdef __NR_mq_getsetattr +#define SYS_mq_getsetattr __NR_mq_getsetattr #endif -#ifdef __NR_mq_notify -# define SYS_mq_notify __NR_mq_notify +#ifdef __NR_mq_notify +#define SYS_mq_notify __NR_mq_notify #endif -#ifdef __NR_mq_open -# define SYS_mq_open __NR_mq_open +#ifdef __NR_mq_open +#define SYS_mq_open __NR_mq_open #endif -#ifdef __NR_mq_timedreceive -# define SYS_mq_timedreceive __NR_mq_timedreceive +#ifdef __NR_mq_timedreceive +#define SYS_mq_timedreceive __NR_mq_timedreceive #endif -#ifdef __NR_mq_timedreceive_time64 -# define SYS_mq_timedreceive_time64 __NR_mq_timedreceive_time64 +#ifdef __NR_mq_timedreceive_time64 +#define SYS_mq_timedreceive_time64 __NR_mq_timedreceive_time64 #endif -#ifdef __NR_mq_timedsend -# define SYS_mq_timedsend __NR_mq_timedsend +#ifdef __NR_mq_timedsend +#define SYS_mq_timedsend __NR_mq_timedsend #endif -#ifdef __NR_mq_timedsend_time64 -# define SYS_mq_timedsend_time64 __NR_mq_timedsend_time64 +#ifdef __NR_mq_timedsend_time64 +#define SYS_mq_timedsend_time64 __NR_mq_timedsend_time64 #endif -#ifdef __NR_mq_unlink -# define SYS_mq_unlink __NR_mq_unlink +#ifdef __NR_mq_unlink +#define SYS_mq_unlink __NR_mq_unlink #endif -#ifdef __NR_mremap -# define SYS_mremap __NR_mremap +#ifdef __NR_mremap +#define SYS_mremap __NR_mremap #endif -#ifdef __NR_msgctl -# define SYS_msgctl __NR_msgctl +#ifdef __NR_msgctl +#define SYS_msgctl __NR_msgctl #endif -#ifdef __NR_msgget -# define SYS_msgget __NR_msgget +#ifdef __NR_msgget +#define SYS_msgget __NR_msgget #endif -#ifdef __NR_msgrcv -# define SYS_msgrcv __NR_msgrcv +#ifdef __NR_msgrcv +#define SYS_msgrcv __NR_msgrcv #endif -#ifdef __NR_msgsnd -# define SYS_msgsnd __NR_msgsnd +#ifdef __NR_msgsnd +#define SYS_msgsnd __NR_msgsnd #endif -#ifdef __NR_msync -# define SYS_msync __NR_msync +#ifdef __NR_msync +#define SYS_msync __NR_msync #endif -#ifdef __NR_multiplexer -# define SYS_multiplexer __NR_multiplexer +#ifdef __NR_multiplexer +#define SYS_multiplexer __NR_multiplexer #endif -#ifdef __NR_munlock -# define SYS_munlock __NR_munlock +#ifdef __NR_munlock +#define SYS_munlock __NR_munlock #endif -#ifdef __NR_munlockall -# define SYS_munlockall __NR_munlockall +#ifdef __NR_munlockall +#define SYS_munlockall __NR_munlockall #endif -#ifdef __NR_munmap -# define SYS_munmap __NR_munmap +#ifdef __NR_munmap +#define SYS_munmap __NR_munmap #endif -#ifdef __NR_name_to_handle_at -# define SYS_name_to_handle_at __NR_name_to_handle_at +#ifdef __NR_name_to_handle_at +#define SYS_name_to_handle_at __NR_name_to_handle_at #endif -#ifdef __NR_nanosleep -# define SYS_nanosleep __NR_nanosleep +#ifdef __NR_nanosleep +#define SYS_nanosleep __NR_nanosleep #endif -#ifdef __NR_newfstatat -# define SYS_newfstatat __NR_newfstatat +#ifdef __NR_newfstatat +#define SYS_newfstatat __NR_newfstatat #endif -#ifdef __NR_nfsservctl -# define SYS_nfsservctl __NR_nfsservctl +#ifdef __NR_nfsservctl +#define SYS_nfsservctl __NR_nfsservctl #endif -#ifdef __NR_nice -# define SYS_nice __NR_nice +#ifdef __NR_nice +#define SYS_nice __NR_nice #endif -#ifdef __NR_old_adjtimex -# define SYS_old_adjtimex __NR_old_adjtimex +#ifdef __NR_old_adjtimex +#define SYS_old_adjtimex __NR_old_adjtimex #endif -#ifdef __NR_old_getpagesize -# define SYS_old_getpagesize __NR_old_getpagesize +#ifdef __NR_old_getpagesize +#define SYS_old_getpagesize __NR_old_getpagesize #endif -#ifdef __NR_oldfstat -# define SYS_oldfstat __NR_oldfstat +#ifdef __NR_oldfstat +#define SYS_oldfstat __NR_oldfstat #endif -#ifdef __NR_oldlstat -# define SYS_oldlstat __NR_oldlstat +#ifdef __NR_oldlstat +#define SYS_oldlstat __NR_oldlstat #endif -#ifdef __NR_oldolduname -# define SYS_oldolduname __NR_oldolduname +#ifdef __NR_oldolduname +#define SYS_oldolduname __NR_oldolduname #endif -#ifdef __NR_oldstat -# define SYS_oldstat __NR_oldstat +#ifdef __NR_oldstat +#define SYS_oldstat __NR_oldstat #endif -#ifdef __NR_oldumount -# define SYS_oldumount __NR_oldumount +#ifdef __NR_oldumount +#define SYS_oldumount __NR_oldumount #endif -#ifdef __NR_olduname -# define SYS_olduname __NR_olduname +#ifdef __NR_olduname +#define SYS_olduname __NR_olduname #endif -#ifdef __NR_open -# define SYS_open __NR_open +#ifdef __NR_open +#define SYS_open __NR_open #endif -#ifdef __NR_open_by_handle_at -# define SYS_open_by_handle_at __NR_open_by_handle_at +#ifdef __NR_open_by_handle_at +#define SYS_open_by_handle_at __NR_open_by_handle_at #endif -#ifdef __NR_open_tree -# define SYS_open_tree __NR_open_tree +#ifdef __NR_open_tree +#define SYS_open_tree __NR_open_tree #endif -#ifdef __NR_openat -# define SYS_openat __NR_openat +#ifdef __NR_openat +#define SYS_openat __NR_openat #endif -#ifdef __NR_openat2 -# define SYS_openat2 __NR_openat2 +#ifdef __NR_openat2 +#define SYS_openat2 __NR_openat2 #endif -#ifdef __NR_or1k_atomic -# define SYS_or1k_atomic __NR_or1k_atomic +#ifdef __NR_or1k_atomic +#define SYS_or1k_atomic __NR_or1k_atomic #endif -#ifdef __NR_osf_adjtime -# define SYS_osf_adjtime __NR_osf_adjtime +#ifdef __NR_osf_adjtime +#define SYS_osf_adjtime __NR_osf_adjtime #endif -#ifdef __NR_osf_afs_syscall -# define SYS_osf_afs_syscall __NR_osf_afs_syscall +#ifdef __NR_osf_afs_syscall +#define SYS_osf_afs_syscall __NR_osf_afs_syscall #endif -#ifdef __NR_osf_alt_plock -# define SYS_osf_alt_plock __NR_osf_alt_plock +#ifdef __NR_osf_alt_plock +#define SYS_osf_alt_plock __NR_osf_alt_plock #endif -#ifdef __NR_osf_alt_setsid -# define SYS_osf_alt_setsid __NR_osf_alt_setsid +#ifdef __NR_osf_alt_setsid +#define SYS_osf_alt_setsid __NR_osf_alt_setsid #endif -#ifdef __NR_osf_alt_sigpending -# define SYS_osf_alt_sigpending __NR_osf_alt_sigpending +#ifdef __NR_osf_alt_sigpending +#define SYS_osf_alt_sigpending __NR_osf_alt_sigpending #endif -#ifdef __NR_osf_asynch_daemon -# define SYS_osf_asynch_daemon __NR_osf_asynch_daemon +#ifdef __NR_osf_asynch_daemon +#define SYS_osf_asynch_daemon __NR_osf_asynch_daemon #endif -#ifdef __NR_osf_audcntl -# define SYS_osf_audcntl __NR_osf_audcntl +#ifdef __NR_osf_audcntl +#define SYS_osf_audcntl __NR_osf_audcntl #endif -#ifdef __NR_osf_audgen -# define SYS_osf_audgen __NR_osf_audgen +#ifdef __NR_osf_audgen +#define SYS_osf_audgen __NR_osf_audgen #endif -#ifdef __NR_osf_chflags -# define SYS_osf_chflags __NR_osf_chflags +#ifdef __NR_osf_chflags +#define SYS_osf_chflags __NR_osf_chflags #endif -#ifdef __NR_osf_execve -# define SYS_osf_execve __NR_osf_execve +#ifdef __NR_osf_execve +#define SYS_osf_execve __NR_osf_execve #endif -#ifdef __NR_osf_exportfs -# define SYS_osf_exportfs __NR_osf_exportfs +#ifdef __NR_osf_exportfs +#define SYS_osf_exportfs __NR_osf_exportfs #endif -#ifdef __NR_osf_fchflags -# define SYS_osf_fchflags __NR_osf_fchflags +#ifdef __NR_osf_fchflags +#define SYS_osf_fchflags __NR_osf_fchflags #endif -#ifdef __NR_osf_fdatasync -# define SYS_osf_fdatasync __NR_osf_fdatasync +#ifdef __NR_osf_fdatasync +#define SYS_osf_fdatasync __NR_osf_fdatasync #endif -#ifdef __NR_osf_fpathconf -# define SYS_osf_fpathconf __NR_osf_fpathconf +#ifdef __NR_osf_fpathconf +#define SYS_osf_fpathconf __NR_osf_fpathconf #endif -#ifdef __NR_osf_fstat -# define SYS_osf_fstat __NR_osf_fstat +#ifdef __NR_osf_fstat +#define SYS_osf_fstat __NR_osf_fstat #endif -#ifdef __NR_osf_fstatfs -# define SYS_osf_fstatfs __NR_osf_fstatfs +#ifdef __NR_osf_fstatfs +#define SYS_osf_fstatfs __NR_osf_fstatfs #endif -#ifdef __NR_osf_fstatfs64 -# define SYS_osf_fstatfs64 __NR_osf_fstatfs64 +#ifdef __NR_osf_fstatfs64 +#define SYS_osf_fstatfs64 __NR_osf_fstatfs64 #endif -#ifdef __NR_osf_fuser -# define SYS_osf_fuser __NR_osf_fuser +#ifdef __NR_osf_fuser +#define SYS_osf_fuser __NR_osf_fuser #endif -#ifdef __NR_osf_getaddressconf -# define SYS_osf_getaddressconf __NR_osf_getaddressconf +#ifdef __NR_osf_getaddressconf +#define SYS_osf_getaddressconf __NR_osf_getaddressconf #endif -#ifdef __NR_osf_getdirentries -# define SYS_osf_getdirentries __NR_osf_getdirentries +#ifdef __NR_osf_getdirentries +#define SYS_osf_getdirentries __NR_osf_getdirentries #endif -#ifdef __NR_osf_getdomainname -# define SYS_osf_getdomainname __NR_osf_getdomainname +#ifdef __NR_osf_getdomainname +#define SYS_osf_getdomainname __NR_osf_getdomainname #endif -#ifdef __NR_osf_getfh -# define SYS_osf_getfh __NR_osf_getfh +#ifdef __NR_osf_getfh +#define SYS_osf_getfh __NR_osf_getfh #endif -#ifdef __NR_osf_getfsstat -# define SYS_osf_getfsstat __NR_osf_getfsstat +#ifdef __NR_osf_getfsstat +#define SYS_osf_getfsstat __NR_osf_getfsstat #endif -#ifdef __NR_osf_gethostid -# define SYS_osf_gethostid __NR_osf_gethostid +#ifdef __NR_osf_gethostid +#define SYS_osf_gethostid __NR_osf_gethostid #endif -#ifdef __NR_osf_getitimer -# define SYS_osf_getitimer __NR_osf_getitimer +#ifdef __NR_osf_getitimer +#define SYS_osf_getitimer __NR_osf_getitimer #endif -#ifdef __NR_osf_getlogin -# define SYS_osf_getlogin __NR_osf_getlogin +#ifdef __NR_osf_getlogin +#define SYS_osf_getlogin __NR_osf_getlogin #endif -#ifdef __NR_osf_getmnt -# define SYS_osf_getmnt __NR_osf_getmnt +#ifdef __NR_osf_getmnt +#define SYS_osf_getmnt __NR_osf_getmnt #endif -#ifdef __NR_osf_getrusage -# define SYS_osf_getrusage __NR_osf_getrusage +#ifdef __NR_osf_getrusage +#define SYS_osf_getrusage __NR_osf_getrusage #endif -#ifdef __NR_osf_getsysinfo -# define SYS_osf_getsysinfo __NR_osf_getsysinfo +#ifdef __NR_osf_getsysinfo +#define SYS_osf_getsysinfo __NR_osf_getsysinfo #endif -#ifdef __NR_osf_gettimeofday -# define SYS_osf_gettimeofday __NR_osf_gettimeofday +#ifdef __NR_osf_gettimeofday +#define SYS_osf_gettimeofday __NR_osf_gettimeofday #endif -#ifdef __NR_osf_kloadcall -# define SYS_osf_kloadcall __NR_osf_kloadcall +#ifdef __NR_osf_kloadcall +#define SYS_osf_kloadcall __NR_osf_kloadcall #endif -#ifdef __NR_osf_kmodcall -# define SYS_osf_kmodcall __NR_osf_kmodcall +#ifdef __NR_osf_kmodcall +#define SYS_osf_kmodcall __NR_osf_kmodcall #endif -#ifdef __NR_osf_lstat -# define SYS_osf_lstat __NR_osf_lstat +#ifdef __NR_osf_lstat +#define SYS_osf_lstat __NR_osf_lstat #endif -#ifdef __NR_osf_memcntl -# define SYS_osf_memcntl __NR_osf_memcntl +#ifdef __NR_osf_memcntl +#define SYS_osf_memcntl __NR_osf_memcntl #endif -#ifdef __NR_osf_mincore -# define SYS_osf_mincore __NR_osf_mincore +#ifdef __NR_osf_mincore +#define SYS_osf_mincore __NR_osf_mincore #endif -#ifdef __NR_osf_mount -# define SYS_osf_mount __NR_osf_mount +#ifdef __NR_osf_mount +#define SYS_osf_mount __NR_osf_mount #endif -#ifdef __NR_osf_mremap -# define SYS_osf_mremap __NR_osf_mremap +#ifdef __NR_osf_mremap +#define SYS_osf_mremap __NR_osf_mremap #endif -#ifdef __NR_osf_msfs_syscall -# define SYS_osf_msfs_syscall __NR_osf_msfs_syscall +#ifdef __NR_osf_msfs_syscall +#define SYS_osf_msfs_syscall __NR_osf_msfs_syscall #endif -#ifdef __NR_osf_msleep -# define SYS_osf_msleep __NR_osf_msleep +#ifdef __NR_osf_msleep +#define SYS_osf_msleep __NR_osf_msleep #endif -#ifdef __NR_osf_mvalid -# define SYS_osf_mvalid __NR_osf_mvalid +#ifdef __NR_osf_mvalid +#define SYS_osf_mvalid __NR_osf_mvalid #endif -#ifdef __NR_osf_mwakeup -# define SYS_osf_mwakeup __NR_osf_mwakeup +#ifdef __NR_osf_mwakeup +#define SYS_osf_mwakeup __NR_osf_mwakeup #endif -#ifdef __NR_osf_naccept -# define SYS_osf_naccept __NR_osf_naccept +#ifdef __NR_osf_naccept +#define SYS_osf_naccept __NR_osf_naccept #endif -#ifdef __NR_osf_nfssvc -# define SYS_osf_nfssvc __NR_osf_nfssvc +#ifdef __NR_osf_nfssvc +#define SYS_osf_nfssvc __NR_osf_nfssvc #endif -#ifdef __NR_osf_ngetpeername -# define SYS_osf_ngetpeername __NR_osf_ngetpeername +#ifdef __NR_osf_ngetpeername +#define SYS_osf_ngetpeername __NR_osf_ngetpeername #endif -#ifdef __NR_osf_ngetsockname -# define SYS_osf_ngetsockname __NR_osf_ngetsockname +#ifdef __NR_osf_ngetsockname +#define SYS_osf_ngetsockname __NR_osf_ngetsockname #endif -#ifdef __NR_osf_nrecvfrom -# define SYS_osf_nrecvfrom __NR_osf_nrecvfrom +#ifdef __NR_osf_nrecvfrom +#define SYS_osf_nrecvfrom __NR_osf_nrecvfrom #endif -#ifdef __NR_osf_nrecvmsg -# define SYS_osf_nrecvmsg __NR_osf_nrecvmsg +#ifdef __NR_osf_nrecvmsg +#define SYS_osf_nrecvmsg __NR_osf_nrecvmsg #endif -#ifdef __NR_osf_nsendmsg -# define SYS_osf_nsendmsg __NR_osf_nsendmsg +#ifdef __NR_osf_nsendmsg +#define SYS_osf_nsendmsg __NR_osf_nsendmsg #endif -#ifdef __NR_osf_ntp_adjtime -# define SYS_osf_ntp_adjtime __NR_osf_ntp_adjtime +#ifdef __NR_osf_ntp_adjtime +#define SYS_osf_ntp_adjtime __NR_osf_ntp_adjtime #endif -#ifdef __NR_osf_ntp_gettime -# define SYS_osf_ntp_gettime __NR_osf_ntp_gettime +#ifdef __NR_osf_ntp_gettime +#define SYS_osf_ntp_gettime __NR_osf_ntp_gettime #endif -#ifdef __NR_osf_old_creat -# define SYS_osf_old_creat __NR_osf_old_creat +#ifdef __NR_osf_old_creat +#define SYS_osf_old_creat __NR_osf_old_creat #endif -#ifdef __NR_osf_old_fstat -# define SYS_osf_old_fstat __NR_osf_old_fstat +#ifdef __NR_osf_old_fstat +#define SYS_osf_old_fstat __NR_osf_old_fstat #endif -#ifdef __NR_osf_old_getpgrp -# define SYS_osf_old_getpgrp __NR_osf_old_getpgrp +#ifdef __NR_osf_old_getpgrp +#define SYS_osf_old_getpgrp __NR_osf_old_getpgrp #endif -#ifdef __NR_osf_old_killpg -# define SYS_osf_old_killpg __NR_osf_old_killpg +#ifdef __NR_osf_old_killpg +#define SYS_osf_old_killpg __NR_osf_old_killpg #endif -#ifdef __NR_osf_old_lstat -# define SYS_osf_old_lstat __NR_osf_old_lstat +#ifdef __NR_osf_old_lstat +#define SYS_osf_old_lstat __NR_osf_old_lstat #endif -#ifdef __NR_osf_old_open -# define SYS_osf_old_open __NR_osf_old_open +#ifdef __NR_osf_old_open +#define SYS_osf_old_open __NR_osf_old_open #endif -#ifdef __NR_osf_old_sigaction -# define SYS_osf_old_sigaction __NR_osf_old_sigaction +#ifdef __NR_osf_old_sigaction +#define SYS_osf_old_sigaction __NR_osf_old_sigaction #endif -#ifdef __NR_osf_old_sigblock -# define SYS_osf_old_sigblock __NR_osf_old_sigblock +#ifdef __NR_osf_old_sigblock +#define SYS_osf_old_sigblock __NR_osf_old_sigblock #endif -#ifdef __NR_osf_old_sigreturn -# define SYS_osf_old_sigreturn __NR_osf_old_sigreturn +#ifdef __NR_osf_old_sigreturn +#define SYS_osf_old_sigreturn __NR_osf_old_sigreturn #endif -#ifdef __NR_osf_old_sigsetmask -# define SYS_osf_old_sigsetmask __NR_osf_old_sigsetmask +#ifdef __NR_osf_old_sigsetmask +#define SYS_osf_old_sigsetmask __NR_osf_old_sigsetmask #endif -#ifdef __NR_osf_old_sigvec -# define SYS_osf_old_sigvec __NR_osf_old_sigvec +#ifdef __NR_osf_old_sigvec +#define SYS_osf_old_sigvec __NR_osf_old_sigvec #endif -#ifdef __NR_osf_old_stat -# define SYS_osf_old_stat __NR_osf_old_stat +#ifdef __NR_osf_old_stat +#define SYS_osf_old_stat __NR_osf_old_stat #endif -#ifdef __NR_osf_old_vadvise -# define SYS_osf_old_vadvise __NR_osf_old_vadvise +#ifdef __NR_osf_old_vadvise +#define SYS_osf_old_vadvise __NR_osf_old_vadvise #endif -#ifdef __NR_osf_old_vtrace -# define SYS_osf_old_vtrace __NR_osf_old_vtrace +#ifdef __NR_osf_old_vtrace +#define SYS_osf_old_vtrace __NR_osf_old_vtrace #endif -#ifdef __NR_osf_old_wait -# define SYS_osf_old_wait __NR_osf_old_wait +#ifdef __NR_osf_old_wait +#define SYS_osf_old_wait __NR_osf_old_wait #endif -#ifdef __NR_osf_oldquota -# define SYS_osf_oldquota __NR_osf_oldquota +#ifdef __NR_osf_oldquota +#define SYS_osf_oldquota __NR_osf_oldquota #endif -#ifdef __NR_osf_pathconf -# define SYS_osf_pathconf __NR_osf_pathconf +#ifdef __NR_osf_pathconf +#define SYS_osf_pathconf __NR_osf_pathconf #endif -#ifdef __NR_osf_pid_block -# define SYS_osf_pid_block __NR_osf_pid_block +#ifdef __NR_osf_pid_block +#define SYS_osf_pid_block __NR_osf_pid_block #endif -#ifdef __NR_osf_pid_unblock -# define SYS_osf_pid_unblock __NR_osf_pid_unblock +#ifdef __NR_osf_pid_unblock +#define SYS_osf_pid_unblock __NR_osf_pid_unblock #endif -#ifdef __NR_osf_plock -# define SYS_osf_plock __NR_osf_plock +#ifdef __NR_osf_plock +#define SYS_osf_plock __NR_osf_plock #endif -#ifdef __NR_osf_priocntlset -# define SYS_osf_priocntlset __NR_osf_priocntlset +#ifdef __NR_osf_priocntlset +#define SYS_osf_priocntlset __NR_osf_priocntlset #endif -#ifdef __NR_osf_profil -# define SYS_osf_profil __NR_osf_profil +#ifdef __NR_osf_profil +#define SYS_osf_profil __NR_osf_profil #endif -#ifdef __NR_osf_proplist_syscall -# define SYS_osf_proplist_syscall __NR_osf_proplist_syscall +#ifdef __NR_osf_proplist_syscall +#define SYS_osf_proplist_syscall __NR_osf_proplist_syscall #endif -#ifdef __NR_osf_reboot -# define SYS_osf_reboot __NR_osf_reboot +#ifdef __NR_osf_reboot +#define SYS_osf_reboot __NR_osf_reboot #endif -#ifdef __NR_osf_revoke -# define SYS_osf_revoke __NR_osf_revoke +#ifdef __NR_osf_revoke +#define SYS_osf_revoke __NR_osf_revoke #endif -#ifdef __NR_osf_sbrk -# define SYS_osf_sbrk __NR_osf_sbrk +#ifdef __NR_osf_sbrk +#define SYS_osf_sbrk __NR_osf_sbrk #endif -#ifdef __NR_osf_security -# define SYS_osf_security __NR_osf_security +#ifdef __NR_osf_security +#define SYS_osf_security __NR_osf_security #endif -#ifdef __NR_osf_select -# define SYS_osf_select __NR_osf_select +#ifdef __NR_osf_select +#define SYS_osf_select __NR_osf_select #endif -#ifdef __NR_osf_set_program_attributes -# define SYS_osf_set_program_attributes __NR_osf_set_program_attributes +#ifdef __NR_osf_set_program_attributes +#define SYS_osf_set_program_attributes __NR_osf_set_program_attributes #endif -#ifdef __NR_osf_set_speculative -# define SYS_osf_set_speculative __NR_osf_set_speculative +#ifdef __NR_osf_set_speculative +#define SYS_osf_set_speculative __NR_osf_set_speculative #endif -#ifdef __NR_osf_sethostid -# define SYS_osf_sethostid __NR_osf_sethostid +#ifdef __NR_osf_sethostid +#define SYS_osf_sethostid __NR_osf_sethostid #endif -#ifdef __NR_osf_setitimer -# define SYS_osf_setitimer __NR_osf_setitimer +#ifdef __NR_osf_setitimer +#define SYS_osf_setitimer __NR_osf_setitimer #endif -#ifdef __NR_osf_setlogin -# define SYS_osf_setlogin __NR_osf_setlogin +#ifdef __NR_osf_setlogin +#define SYS_osf_setlogin __NR_osf_setlogin #endif -#ifdef __NR_osf_setsysinfo -# define SYS_osf_setsysinfo __NR_osf_setsysinfo +#ifdef __NR_osf_setsysinfo +#define SYS_osf_setsysinfo __NR_osf_setsysinfo #endif -#ifdef __NR_osf_settimeofday -# define SYS_osf_settimeofday __NR_osf_settimeofday +#ifdef __NR_osf_settimeofday +#define SYS_osf_settimeofday __NR_osf_settimeofday #endif -#ifdef __NR_osf_shmat -# define SYS_osf_shmat __NR_osf_shmat +#ifdef __NR_osf_shmat +#define SYS_osf_shmat __NR_osf_shmat #endif -#ifdef __NR_osf_signal -# define SYS_osf_signal __NR_osf_signal +#ifdef __NR_osf_signal +#define SYS_osf_signal __NR_osf_signal #endif -#ifdef __NR_osf_sigprocmask -# define SYS_osf_sigprocmask __NR_osf_sigprocmask +#ifdef __NR_osf_sigprocmask +#define SYS_osf_sigprocmask __NR_osf_sigprocmask #endif -#ifdef __NR_osf_sigsendset -# define SYS_osf_sigsendset __NR_osf_sigsendset +#ifdef __NR_osf_sigsendset +#define SYS_osf_sigsendset __NR_osf_sigsendset #endif -#ifdef __NR_osf_sigstack -# define SYS_osf_sigstack __NR_osf_sigstack +#ifdef __NR_osf_sigstack +#define SYS_osf_sigstack __NR_osf_sigstack #endif -#ifdef __NR_osf_sigwaitprim -# define SYS_osf_sigwaitprim __NR_osf_sigwaitprim +#ifdef __NR_osf_sigwaitprim +#define SYS_osf_sigwaitprim __NR_osf_sigwaitprim #endif -#ifdef __NR_osf_sstk -# define SYS_osf_sstk __NR_osf_sstk +#ifdef __NR_osf_sstk +#define SYS_osf_sstk __NR_osf_sstk #endif -#ifdef __NR_osf_stat -# define SYS_osf_stat __NR_osf_stat +#ifdef __NR_osf_stat +#define SYS_osf_stat __NR_osf_stat #endif -#ifdef __NR_osf_statfs -# define SYS_osf_statfs __NR_osf_statfs +#ifdef __NR_osf_statfs +#define SYS_osf_statfs __NR_osf_statfs #endif -#ifdef __NR_osf_statfs64 -# define SYS_osf_statfs64 __NR_osf_statfs64 +#ifdef __NR_osf_statfs64 +#define SYS_osf_statfs64 __NR_osf_statfs64 #endif -#ifdef __NR_osf_subsys_info -# define SYS_osf_subsys_info __NR_osf_subsys_info +#ifdef __NR_osf_subsys_info +#define SYS_osf_subsys_info __NR_osf_subsys_info #endif -#ifdef __NR_osf_swapctl -# define SYS_osf_swapctl __NR_osf_swapctl +#ifdef __NR_osf_swapctl +#define SYS_osf_swapctl __NR_osf_swapctl #endif -#ifdef __NR_osf_swapon -# define SYS_osf_swapon __NR_osf_swapon +#ifdef __NR_osf_swapon +#define SYS_osf_swapon __NR_osf_swapon #endif -#ifdef __NR_osf_syscall -# define SYS_osf_syscall __NR_osf_syscall +#ifdef __NR_osf_syscall +#define SYS_osf_syscall __NR_osf_syscall #endif -#ifdef __NR_osf_sysinfo -# define SYS_osf_sysinfo __NR_osf_sysinfo +#ifdef __NR_osf_sysinfo +#define SYS_osf_sysinfo __NR_osf_sysinfo #endif -#ifdef __NR_osf_table -# define SYS_osf_table __NR_osf_table +#ifdef __NR_osf_table +#define SYS_osf_table __NR_osf_table #endif -#ifdef __NR_osf_uadmin -# define SYS_osf_uadmin __NR_osf_uadmin +#ifdef __NR_osf_uadmin +#define SYS_osf_uadmin __NR_osf_uadmin #endif -#ifdef __NR_osf_usleep_thread -# define SYS_osf_usleep_thread __NR_osf_usleep_thread +#ifdef __NR_osf_usleep_thread +#define SYS_osf_usleep_thread __NR_osf_usleep_thread #endif -#ifdef __NR_osf_uswitch -# define SYS_osf_uswitch __NR_osf_uswitch +#ifdef __NR_osf_uswitch +#define SYS_osf_uswitch __NR_osf_uswitch #endif -#ifdef __NR_osf_utc_adjtime -# define SYS_osf_utc_adjtime __NR_osf_utc_adjtime +#ifdef __NR_osf_utc_adjtime +#define SYS_osf_utc_adjtime __NR_osf_utc_adjtime #endif -#ifdef __NR_osf_utc_gettime -# define SYS_osf_utc_gettime __NR_osf_utc_gettime +#ifdef __NR_osf_utc_gettime +#define SYS_osf_utc_gettime __NR_osf_utc_gettime #endif -#ifdef __NR_osf_utimes -# define SYS_osf_utimes __NR_osf_utimes +#ifdef __NR_osf_utimes +#define SYS_osf_utimes __NR_osf_utimes #endif -#ifdef __NR_osf_utsname -# define SYS_osf_utsname __NR_osf_utsname +#ifdef __NR_osf_utsname +#define SYS_osf_utsname __NR_osf_utsname #endif -#ifdef __NR_osf_wait4 -# define SYS_osf_wait4 __NR_osf_wait4 +#ifdef __NR_osf_wait4 +#define SYS_osf_wait4 __NR_osf_wait4 #endif -#ifdef __NR_osf_waitid -# define SYS_osf_waitid __NR_osf_waitid +#ifdef __NR_osf_waitid +#define SYS_osf_waitid __NR_osf_waitid #endif -#ifdef __NR_pause -# define SYS_pause __NR_pause +#ifdef __NR_pause +#define SYS_pause __NR_pause #endif -#ifdef __NR_pciconfig_iobase -# define SYS_pciconfig_iobase __NR_pciconfig_iobase +#ifdef __NR_pciconfig_iobase +#define SYS_pciconfig_iobase __NR_pciconfig_iobase #endif -#ifdef __NR_pciconfig_read -# define SYS_pciconfig_read __NR_pciconfig_read +#ifdef __NR_pciconfig_read +#define SYS_pciconfig_read __NR_pciconfig_read #endif -#ifdef __NR_pciconfig_write -# define SYS_pciconfig_write __NR_pciconfig_write +#ifdef __NR_pciconfig_write +#define SYS_pciconfig_write __NR_pciconfig_write #endif -#ifdef __NR_perf_event_open -# define SYS_perf_event_open __NR_perf_event_open +#ifdef __NR_perf_event_open +#define SYS_perf_event_open __NR_perf_event_open #endif -#ifdef __NR_perfctr -# define SYS_perfctr __NR_perfctr +#ifdef __NR_perfctr +#define SYS_perfctr __NR_perfctr #endif -#ifdef __NR_perfmonctl -# define SYS_perfmonctl __NR_perfmonctl +#ifdef __NR_perfmonctl +#define SYS_perfmonctl __NR_perfmonctl #endif -#ifdef __NR_personality -# define SYS_personality __NR_personality +#ifdef __NR_personality +#define SYS_personality __NR_personality #endif -#ifdef __NR_pidfd_getfd -# define SYS_pidfd_getfd __NR_pidfd_getfd +#ifdef __NR_pidfd_getfd +#define SYS_pidfd_getfd __NR_pidfd_getfd #endif -#ifdef __NR_pidfd_open -# define SYS_pidfd_open __NR_pidfd_open +#ifdef __NR_pidfd_open +#define SYS_pidfd_open __NR_pidfd_open #endif -#ifdef __NR_pidfd_send_signal -# define SYS_pidfd_send_signal __NR_pidfd_send_signal +#ifdef __NR_pidfd_send_signal +#define SYS_pidfd_send_signal __NR_pidfd_send_signal #endif -#ifdef __NR_pipe -# define SYS_pipe __NR_pipe +#ifdef __NR_pipe +#define SYS_pipe __NR_pipe #endif -#ifdef __NR_pipe2 -# define SYS_pipe2 __NR_pipe2 +#ifdef __NR_pipe2 +#define SYS_pipe2 __NR_pipe2 #endif -#ifdef __NR_pivot_root -# define SYS_pivot_root __NR_pivot_root +#ifdef __NR_pivot_root +#define SYS_pivot_root __NR_pivot_root #endif -#ifdef __NR_pkey_alloc -# define SYS_pkey_alloc __NR_pkey_alloc +#ifdef __NR_pkey_alloc +#define SYS_pkey_alloc __NR_pkey_alloc #endif -#ifdef __NR_pkey_free -# define SYS_pkey_free __NR_pkey_free +#ifdef __NR_pkey_free +#define SYS_pkey_free __NR_pkey_free #endif -#ifdef __NR_pkey_mprotect -# define SYS_pkey_mprotect __NR_pkey_mprotect +#ifdef __NR_pkey_mprotect +#define SYS_pkey_mprotect __NR_pkey_mprotect #endif -#ifdef __NR_poll -# define SYS_poll __NR_poll +#ifdef __NR_poll +#define SYS_poll __NR_poll #endif -#ifdef __NR_ppoll -# define SYS_ppoll __NR_ppoll +#ifdef __NR_ppoll +#define SYS_ppoll __NR_ppoll #endif -#ifdef __NR_ppoll_time64 -# define SYS_ppoll_time64 __NR_ppoll_time64 +#ifdef __NR_ppoll_time64 +#define SYS_ppoll_time64 __NR_ppoll_time64 #endif -#ifdef __NR_prctl -# define SYS_prctl __NR_prctl +#ifdef __NR_prctl +#define SYS_prctl __NR_prctl #endif -#ifdef __NR_pread64 -# define SYS_pread64 __NR_pread64 +#ifdef __NR_pread64 +#define SYS_pread64 __NR_pread64 #endif -#ifdef __NR_preadv -# define SYS_preadv __NR_preadv +#ifdef __NR_preadv +#define SYS_preadv __NR_preadv #endif -#ifdef __NR_preadv2 -# define SYS_preadv2 __NR_preadv2 +#ifdef __NR_preadv2 +#define SYS_preadv2 __NR_preadv2 #endif -#ifdef __NR_prlimit64 -# define SYS_prlimit64 __NR_prlimit64 +#ifdef __NR_prlimit64 +#define SYS_prlimit64 __NR_prlimit64 #endif -#ifdef __NR_process_madvise -# define SYS_process_madvise __NR_process_madvise +#ifdef __NR_process_madvise +#define SYS_process_madvise __NR_process_madvise #endif -#ifdef __NR_process_mrelease -# define SYS_process_mrelease __NR_process_mrelease +#ifdef __NR_process_mrelease +#define SYS_process_mrelease __NR_process_mrelease #endif -#ifdef __NR_process_vm_readv -# define SYS_process_vm_readv __NR_process_vm_readv +#ifdef __NR_process_vm_readv +#define SYS_process_vm_readv __NR_process_vm_readv #endif -#ifdef __NR_process_vm_writev -# define SYS_process_vm_writev __NR_process_vm_writev +#ifdef __NR_process_vm_writev +#define SYS_process_vm_writev __NR_process_vm_writev #endif -#ifdef __NR_pselect6 -# define SYS_pselect6 __NR_pselect6 +#ifdef __NR_pselect6 +#define SYS_pselect6 __NR_pselect6 #endif -#ifdef __NR_pselect6_time64 -# define SYS_pselect6_time64 __NR_pselect6_time64 +#ifdef __NR_pselect6_time64 +#define SYS_pselect6_time64 __NR_pselect6_time64 #endif -#ifdef __NR_ptrace -# define SYS_ptrace __NR_ptrace +#ifdef __NR_ptrace +#define SYS_ptrace __NR_ptrace #endif -#ifdef __NR_pwrite64 -# define SYS_pwrite64 __NR_pwrite64 +#ifdef __NR_pwrite64 +#define SYS_pwrite64 __NR_pwrite64 #endif -#ifdef __NR_pwritev -# define SYS_pwritev __NR_pwritev +#ifdef __NR_pwritev +#define SYS_pwritev __NR_pwritev #endif -#ifdef __NR_pwritev2 -# define SYS_pwritev2 __NR_pwritev2 +#ifdef __NR_pwritev2 +#define SYS_pwritev2 __NR_pwritev2 #endif -#ifdef __NR_query_module -# define SYS_query_module __NR_query_module +#ifdef __NR_query_module +#define SYS_query_module __NR_query_module #endif -#ifdef __NR_quotactl -# define SYS_quotactl __NR_quotactl +#ifdef __NR_quotactl +#define SYS_quotactl __NR_quotactl #endif -#ifdef __NR_quotactl_fd -# define SYS_quotactl_fd __NR_quotactl_fd +#ifdef __NR_quotactl_fd +#define SYS_quotactl_fd __NR_quotactl_fd #endif -#ifdef __NR_read -# define SYS_read __NR_read +#ifdef __NR_read +#define SYS_read __NR_read #endif -#ifdef __NR_readahead -# define SYS_readahead __NR_readahead +#ifdef __NR_readahead +#define SYS_readahead __NR_readahead #endif -#ifdef __NR_readdir -# define SYS_readdir __NR_readdir +#ifdef __NR_readdir +#define SYS_readdir __NR_readdir #endif -#ifdef __NR_readlink -# define SYS_readlink __NR_readlink +#ifdef __NR_readlink +#define SYS_readlink __NR_readlink #endif -#ifdef __NR_readlinkat -# define SYS_readlinkat __NR_readlinkat +#ifdef __NR_readlinkat +#define SYS_readlinkat __NR_readlinkat #endif -#ifdef __NR_readv -# define SYS_readv __NR_readv +#ifdef __NR_readv +#define SYS_readv __NR_readv #endif -#ifdef __NR_reboot -# define SYS_reboot __NR_reboot +#ifdef __NR_reboot +#define SYS_reboot __NR_reboot #endif -#ifdef __NR_recv -# define SYS_recv __NR_recv +#ifdef __NR_recv +#define SYS_recv __NR_recv #endif -#ifdef __NR_recvfrom -# define SYS_recvfrom __NR_recvfrom +#ifdef __NR_recvfrom +#define SYS_recvfrom __NR_recvfrom #endif -#ifdef __NR_recvmmsg -# define SYS_recvmmsg __NR_recvmmsg +#ifdef __NR_recvmmsg +#define SYS_recvmmsg __NR_recvmmsg #endif -#ifdef __NR_recvmmsg_time64 -# define SYS_recvmmsg_time64 __NR_recvmmsg_time64 +#ifdef __NR_recvmmsg_time64 +#define SYS_recvmmsg_time64 __NR_recvmmsg_time64 #endif -#ifdef __NR_recvmsg -# define SYS_recvmsg __NR_recvmsg +#ifdef __NR_recvmsg +#define SYS_recvmsg __NR_recvmsg #endif -#ifdef __NR_remap_file_pages -# define SYS_remap_file_pages __NR_remap_file_pages +#ifdef __NR_remap_file_pages +#define SYS_remap_file_pages __NR_remap_file_pages #endif -#ifdef __NR_removexattr -# define SYS_removexattr __NR_removexattr +#ifdef __NR_removexattr +#define SYS_removexattr __NR_removexattr #endif -#ifdef __NR_rename -# define SYS_rename __NR_rename +#ifdef __NR_rename +#define SYS_rename __NR_rename #endif -#ifdef __NR_renameat -# define SYS_renameat __NR_renameat +#ifdef __NR_renameat +#define SYS_renameat __NR_renameat #endif -#ifdef __NR_renameat2 -# define SYS_renameat2 __NR_renameat2 +#ifdef __NR_renameat2 +#define SYS_renameat2 __NR_renameat2 #endif -#ifdef __NR_request_key -# define SYS_request_key __NR_request_key +#ifdef __NR_request_key +#define SYS_request_key __NR_request_key #endif -#ifdef __NR_restart_syscall -# define SYS_restart_syscall __NR_restart_syscall +#ifdef __NR_restart_syscall +#define SYS_restart_syscall __NR_restart_syscall #endif -#ifdef __NR_riscv_flush_icache -# define SYS_riscv_flush_icache __NR_riscv_flush_icache +#ifdef __NR_riscv_flush_icache +#define SYS_riscv_flush_icache __NR_riscv_flush_icache #endif -#ifdef __NR_riscv_hwprobe -# define SYS_riscv_hwprobe __NR_riscv_hwprobe +#ifdef __NR_riscv_hwprobe +#define SYS_riscv_hwprobe __NR_riscv_hwprobe #endif -#ifdef __NR_rmdir -# define SYS_rmdir __NR_rmdir +#ifdef __NR_rmdir +#define SYS_rmdir __NR_rmdir #endif -#ifdef __NR_rseq -# define SYS_rseq __NR_rseq +#ifdef __NR_rseq +#define SYS_rseq __NR_rseq #endif -#ifdef __NR_rt_sigaction -# define SYS_rt_sigaction __NR_rt_sigaction +#ifdef __NR_rt_sigaction +#define SYS_rt_sigaction __NR_rt_sigaction #endif -#ifdef __NR_rt_sigpending -# define SYS_rt_sigpending __NR_rt_sigpending +#ifdef __NR_rt_sigpending +#define SYS_rt_sigpending __NR_rt_sigpending #endif -#ifdef __NR_rt_sigprocmask -# define SYS_rt_sigprocmask __NR_rt_sigprocmask +#ifdef __NR_rt_sigprocmask +#define SYS_rt_sigprocmask __NR_rt_sigprocmask #endif -#ifdef __NR_rt_sigqueueinfo -# define SYS_rt_sigqueueinfo __NR_rt_sigqueueinfo +#ifdef __NR_rt_sigqueueinfo +#define SYS_rt_sigqueueinfo __NR_rt_sigqueueinfo #endif -#ifdef __NR_rt_sigreturn -# define SYS_rt_sigreturn __NR_rt_sigreturn +#ifdef __NR_rt_sigreturn +#define SYS_rt_sigreturn __NR_rt_sigreturn #endif -#ifdef __NR_rt_sigsuspend -# define SYS_rt_sigsuspend __NR_rt_sigsuspend +#ifdef __NR_rt_sigsuspend +#define SYS_rt_sigsuspend __NR_rt_sigsuspend #endif -#ifdef __NR_rt_sigtimedwait -# define SYS_rt_sigtimedwait __NR_rt_sigtimedwait +#ifdef __NR_rt_sigtimedwait +#define SYS_rt_sigtimedwait __NR_rt_sigtimedwait #endif -#ifdef __NR_rt_sigtimedwait_time64 -# define SYS_rt_sigtimedwait_time64 __NR_rt_sigtimedwait_time64 +#ifdef __NR_rt_sigtimedwait_time64 +#define SYS_rt_sigtimedwait_time64 __NR_rt_sigtimedwait_time64 #endif -#ifdef __NR_rt_tgsigqueueinfo -# define SYS_rt_tgsigqueueinfo __NR_rt_tgsigqueueinfo +#ifdef __NR_rt_tgsigqueueinfo +#define SYS_rt_tgsigqueueinfo __NR_rt_tgsigqueueinfo #endif -#ifdef __NR_rtas -# define SYS_rtas __NR_rtas +#ifdef __NR_rtas +#define SYS_rtas __NR_rtas #endif -#ifdef __NR_s390_guarded_storage -# define SYS_s390_guarded_storage __NR_s390_guarded_storage +#ifdef __NR_s390_guarded_storage +#define SYS_s390_guarded_storage __NR_s390_guarded_storage #endif -#ifdef __NR_s390_pci_mmio_read -# define SYS_s390_pci_mmio_read __NR_s390_pci_mmio_read +#ifdef __NR_s390_pci_mmio_read +#define SYS_s390_pci_mmio_read __NR_s390_pci_mmio_read #endif -#ifdef __NR_s390_pci_mmio_write -# define SYS_s390_pci_mmio_write __NR_s390_pci_mmio_write +#ifdef __NR_s390_pci_mmio_write +#define SYS_s390_pci_mmio_write __NR_s390_pci_mmio_write #endif -#ifdef __NR_s390_runtime_instr -# define SYS_s390_runtime_instr __NR_s390_runtime_instr +#ifdef __NR_s390_runtime_instr +#define SYS_s390_runtime_instr __NR_s390_runtime_instr #endif -#ifdef __NR_s390_sthyi -# define SYS_s390_sthyi __NR_s390_sthyi +#ifdef __NR_s390_sthyi +#define SYS_s390_sthyi __NR_s390_sthyi #endif -#ifdef __NR_sched_get_affinity -# define SYS_sched_get_affinity __NR_sched_get_affinity +#ifdef __NR_sched_get_affinity +#define SYS_sched_get_affinity __NR_sched_get_affinity #endif -#ifdef __NR_sched_get_priority_max -# define SYS_sched_get_priority_max __NR_sched_get_priority_max +#ifdef __NR_sched_get_priority_max +#define SYS_sched_get_priority_max __NR_sched_get_priority_max #endif -#ifdef __NR_sched_get_priority_min -# define SYS_sched_get_priority_min __NR_sched_get_priority_min +#ifdef __NR_sched_get_priority_min +#define SYS_sched_get_priority_min __NR_sched_get_priority_min #endif -#ifdef __NR_sched_getaffinity -# define SYS_sched_getaffinity __NR_sched_getaffinity +#ifdef __NR_sched_getaffinity +#define SYS_sched_getaffinity __NR_sched_getaffinity #endif -#ifdef __NR_sched_getattr -# define SYS_sched_getattr __NR_sched_getattr +#ifdef __NR_sched_getattr +#define SYS_sched_getattr __NR_sched_getattr #endif -#ifdef __NR_sched_getparam -# define SYS_sched_getparam __NR_sched_getparam +#ifdef __NR_sched_getparam +#define SYS_sched_getparam __NR_sched_getparam #endif -#ifdef __NR_sched_getscheduler -# define SYS_sched_getscheduler __NR_sched_getscheduler +#ifdef __NR_sched_getscheduler +#define SYS_sched_getscheduler __NR_sched_getscheduler #endif -#ifdef __NR_sched_rr_get_interval -# define SYS_sched_rr_get_interval __NR_sched_rr_get_interval +#ifdef __NR_sched_rr_get_interval +#define SYS_sched_rr_get_interval __NR_sched_rr_get_interval #endif -#ifdef __NR_sched_rr_get_interval_time64 -# define SYS_sched_rr_get_interval_time64 __NR_sched_rr_get_interval_time64 +#ifdef __NR_sched_rr_get_interval_time64 +#define SYS_sched_rr_get_interval_time64 __NR_sched_rr_get_interval_time64 #endif -#ifdef __NR_sched_set_affinity -# define SYS_sched_set_affinity __NR_sched_set_affinity +#ifdef __NR_sched_set_affinity +#define SYS_sched_set_affinity __NR_sched_set_affinity #endif -#ifdef __NR_sched_setaffinity -# define SYS_sched_setaffinity __NR_sched_setaffinity +#ifdef __NR_sched_setaffinity +#define SYS_sched_setaffinity __NR_sched_setaffinity #endif -#ifdef __NR_sched_setattr -# define SYS_sched_setattr __NR_sched_setattr +#ifdef __NR_sched_setattr +#define SYS_sched_setattr __NR_sched_setattr #endif -#ifdef __NR_sched_setparam -# define SYS_sched_setparam __NR_sched_setparam +#ifdef __NR_sched_setparam +#define SYS_sched_setparam __NR_sched_setparam #endif -#ifdef __NR_sched_setscheduler -# define SYS_sched_setscheduler __NR_sched_setscheduler +#ifdef __NR_sched_setscheduler +#define SYS_sched_setscheduler __NR_sched_setscheduler #endif -#ifdef __NR_sched_yield -# define SYS_sched_yield __NR_sched_yield +#ifdef __NR_sched_yield +#define SYS_sched_yield __NR_sched_yield #endif -#ifdef __NR_seccomp -# define SYS_seccomp __NR_seccomp +#ifdef __NR_seccomp +#define SYS_seccomp __NR_seccomp #endif -#ifdef __NR_select -# define SYS_select __NR_select +#ifdef __NR_select +#define SYS_select __NR_select #endif -#ifdef __NR_semctl -# define SYS_semctl __NR_semctl +#ifdef __NR_semctl +#define SYS_semctl __NR_semctl #endif -#ifdef __NR_semget -# define SYS_semget __NR_semget +#ifdef __NR_semget +#define SYS_semget __NR_semget #endif -#ifdef __NR_semop -# define SYS_semop __NR_semop +#ifdef __NR_semop +#define SYS_semop __NR_semop #endif -#ifdef __NR_semtimedop -# define SYS_semtimedop __NR_semtimedop +#ifdef __NR_semtimedop +#define SYS_semtimedop __NR_semtimedop #endif -#ifdef __NR_semtimedop_time64 -# define SYS_semtimedop_time64 __NR_semtimedop_time64 +#ifdef __NR_semtimedop_time64 +#define SYS_semtimedop_time64 __NR_semtimedop_time64 #endif -#ifdef __NR_send -# define SYS_send __NR_send +#ifdef __NR_send +#define SYS_send __NR_send #endif -#ifdef __NR_sendfile -# define SYS_sendfile __NR_sendfile +#ifdef __NR_sendfile +#define SYS_sendfile __NR_sendfile #endif -#ifdef __NR_sendfile64 -# define SYS_sendfile64 __NR_sendfile64 +#ifdef __NR_sendfile64 +#define SYS_sendfile64 __NR_sendfile64 #endif -#ifdef __NR_sendmmsg -# define SYS_sendmmsg __NR_sendmmsg +#ifdef __NR_sendmmsg +#define SYS_sendmmsg __NR_sendmmsg #endif -#ifdef __NR_sendmsg -# define SYS_sendmsg __NR_sendmsg +#ifdef __NR_sendmsg +#define SYS_sendmsg __NR_sendmsg #endif -#ifdef __NR_sendto -# define SYS_sendto __NR_sendto +#ifdef __NR_sendto +#define SYS_sendto __NR_sendto #endif -#ifdef __NR_set_mempolicy -# define SYS_set_mempolicy __NR_set_mempolicy +#ifdef __NR_set_mempolicy +#define SYS_set_mempolicy __NR_set_mempolicy #endif -#ifdef __NR_set_mempolicy_home_node -# define SYS_set_mempolicy_home_node __NR_set_mempolicy_home_node +#ifdef __NR_set_mempolicy_home_node +#define SYS_set_mempolicy_home_node __NR_set_mempolicy_home_node #endif -#ifdef __NR_set_robust_list -# define SYS_set_robust_list __NR_set_robust_list +#ifdef __NR_set_robust_list +#define SYS_set_robust_list __NR_set_robust_list #endif -#ifdef __NR_set_thread_area -# define SYS_set_thread_area __NR_set_thread_area +#ifdef __NR_set_thread_area +#define SYS_set_thread_area __NR_set_thread_area #endif -#ifdef __NR_set_tid_address -# define SYS_set_tid_address __NR_set_tid_address +#ifdef __NR_set_tid_address +#define SYS_set_tid_address __NR_set_tid_address #endif -#ifdef __NR_setdomainname -# define SYS_setdomainname __NR_setdomainname +#ifdef __NR_setdomainname +#define SYS_setdomainname __NR_setdomainname #endif -#ifdef __NR_setfsgid -# define SYS_setfsgid __NR_setfsgid +#ifdef __NR_setfsgid +#define SYS_setfsgid __NR_setfsgid #endif -#ifdef __NR_setfsgid32 -# define SYS_setfsgid32 __NR_setfsgid32 +#ifdef __NR_setfsgid32 +#define SYS_setfsgid32 __NR_setfsgid32 #endif -#ifdef __NR_setfsuid -# define SYS_setfsuid __NR_setfsuid +#ifdef __NR_setfsuid +#define SYS_setfsuid __NR_setfsuid #endif -#ifdef __NR_setfsuid32 -# define SYS_setfsuid32 __NR_setfsuid32 +#ifdef __NR_setfsuid32 +#define SYS_setfsuid32 __NR_setfsuid32 #endif -#ifdef __NR_setgid -# define SYS_setgid __NR_setgid +#ifdef __NR_setgid +#define SYS_setgid __NR_setgid #endif -#ifdef __NR_setgid32 -# define SYS_setgid32 __NR_setgid32 +#ifdef __NR_setgid32 +#define SYS_setgid32 __NR_setgid32 #endif -#ifdef __NR_setgroups -# define SYS_setgroups __NR_setgroups +#ifdef __NR_setgroups +#define SYS_setgroups __NR_setgroups #endif -#ifdef __NR_setgroups32 -# define SYS_setgroups32 __NR_setgroups32 +#ifdef __NR_setgroups32 +#define SYS_setgroups32 __NR_setgroups32 #endif -#ifdef __NR_sethae -# define SYS_sethae __NR_sethae +#ifdef __NR_sethae +#define SYS_sethae __NR_sethae #endif -#ifdef __NR_sethostname -# define SYS_sethostname __NR_sethostname +#ifdef __NR_sethostname +#define SYS_sethostname __NR_sethostname #endif -#ifdef __NR_setitimer -# define SYS_setitimer __NR_setitimer +#ifdef __NR_setitimer +#define SYS_setitimer __NR_setitimer #endif -#ifdef __NR_setns -# define SYS_setns __NR_setns +#ifdef __NR_setns +#define SYS_setns __NR_setns #endif -#ifdef __NR_setpgid -# define SYS_setpgid __NR_setpgid +#ifdef __NR_setpgid +#define SYS_setpgid __NR_setpgid #endif -#ifdef __NR_setpgrp -# define SYS_setpgrp __NR_setpgrp +#ifdef __NR_setpgrp +#define SYS_setpgrp __NR_setpgrp #endif -#ifdef __NR_setpriority -# define SYS_setpriority __NR_setpriority +#ifdef __NR_setpriority +#define SYS_setpriority __NR_setpriority #endif -#ifdef __NR_setregid -# define SYS_setregid __NR_setregid +#ifdef __NR_setregid +#define SYS_setregid __NR_setregid #endif -#ifdef __NR_setregid32 -# define SYS_setregid32 __NR_setregid32 +#ifdef __NR_setregid32 +#define SYS_setregid32 __NR_setregid32 #endif -#ifdef __NR_setresgid -# define SYS_setresgid __NR_setresgid +#ifdef __NR_setresgid +#define SYS_setresgid __NR_setresgid #endif -#ifdef __NR_setresgid32 -# define SYS_setresgid32 __NR_setresgid32 +#ifdef __NR_setresgid32 +#define SYS_setresgid32 __NR_setresgid32 #endif -#ifdef __NR_setresuid -# define SYS_setresuid __NR_setresuid +#ifdef __NR_setresuid +#define SYS_setresuid __NR_setresuid #endif -#ifdef __NR_setresuid32 -# define SYS_setresuid32 __NR_setresuid32 +#ifdef __NR_setresuid32 +#define SYS_setresuid32 __NR_setresuid32 #endif -#ifdef __NR_setreuid -# define SYS_setreuid __NR_setreuid +#ifdef __NR_setreuid +#define SYS_setreuid __NR_setreuid #endif -#ifdef __NR_setreuid32 -# define SYS_setreuid32 __NR_setreuid32 +#ifdef __NR_setreuid32 +#define SYS_setreuid32 __NR_setreuid32 #endif -#ifdef __NR_setrlimit -# define SYS_setrlimit __NR_setrlimit +#ifdef __NR_setrlimit +#define SYS_setrlimit __NR_setrlimit #endif -#ifdef __NR_setsid -# define SYS_setsid __NR_setsid +#ifdef __NR_setsid +#define SYS_setsid __NR_setsid #endif -#ifdef __NR_setsockopt -# define SYS_setsockopt __NR_setsockopt +#ifdef __NR_setsockopt +#define SYS_setsockopt __NR_setsockopt #endif -#ifdef __NR_settimeofday -# define SYS_settimeofday __NR_settimeofday +#ifdef __NR_settimeofday +#define SYS_settimeofday __NR_settimeofday #endif -#ifdef __NR_setuid -# define SYS_setuid __NR_setuid +#ifdef __NR_setuid +#define SYS_setuid __NR_setuid #endif -#ifdef __NR_setuid32 -# define SYS_setuid32 __NR_setuid32 +#ifdef __NR_setuid32 +#define SYS_setuid32 __NR_setuid32 #endif -#ifdef __NR_setxattr -# define SYS_setxattr __NR_setxattr +#ifdef __NR_setxattr +#define SYS_setxattr __NR_setxattr #endif -#ifdef __NR_sgetmask -# define SYS_sgetmask __NR_sgetmask +#ifdef __NR_sgetmask +#define SYS_sgetmask __NR_sgetmask #endif -#ifdef __NR_shmat -# define SYS_shmat __NR_shmat +#ifdef __NR_shmat +#define SYS_shmat __NR_shmat #endif -#ifdef __NR_shmctl -# define SYS_shmctl __NR_shmctl +#ifdef __NR_shmctl +#define SYS_shmctl __NR_shmctl #endif -#ifdef __NR_shmdt -# define SYS_shmdt __NR_shmdt +#ifdef __NR_shmdt +#define SYS_shmdt __NR_shmdt #endif -#ifdef __NR_shmget -# define SYS_shmget __NR_shmget +#ifdef __NR_shmget +#define SYS_shmget __NR_shmget #endif -#ifdef __NR_shutdown -# define SYS_shutdown __NR_shutdown +#ifdef __NR_shutdown +#define SYS_shutdown __NR_shutdown #endif -#ifdef __NR_sigaction -# define SYS_sigaction __NR_sigaction +#ifdef __NR_sigaction +#define SYS_sigaction __NR_sigaction #endif -#ifdef __NR_sigaltstack -# define SYS_sigaltstack __NR_sigaltstack +#ifdef __NR_sigaltstack +#define SYS_sigaltstack __NR_sigaltstack #endif -#ifdef __NR_signal -# define SYS_signal __NR_signal +#ifdef __NR_signal +#define SYS_signal __NR_signal #endif -#ifdef __NR_signalfd -# define SYS_signalfd __NR_signalfd +#ifdef __NR_signalfd +#define SYS_signalfd __NR_signalfd #endif -#ifdef __NR_signalfd4 -# define SYS_signalfd4 __NR_signalfd4 +#ifdef __NR_signalfd4 +#define SYS_signalfd4 __NR_signalfd4 #endif -#ifdef __NR_sigpending -# define SYS_sigpending __NR_sigpending +#ifdef __NR_sigpending +#define SYS_sigpending __NR_sigpending #endif -#ifdef __NR_sigprocmask -# define SYS_sigprocmask __NR_sigprocmask +#ifdef __NR_sigprocmask +#define SYS_sigprocmask __NR_sigprocmask #endif -#ifdef __NR_sigreturn -# define SYS_sigreturn __NR_sigreturn +#ifdef __NR_sigreturn +#define SYS_sigreturn __NR_sigreturn #endif -#ifdef __NR_sigsuspend -# define SYS_sigsuspend __NR_sigsuspend +#ifdef __NR_sigsuspend +#define SYS_sigsuspend __NR_sigsuspend #endif -#ifdef __NR_socket -# define SYS_socket __NR_socket +#ifdef __NR_socket +#define SYS_socket __NR_socket #endif -#ifdef __NR_socketcall -# define SYS_socketcall __NR_socketcall +#ifdef __NR_socketcall +#define SYS_socketcall __NR_socketcall #endif -#ifdef __NR_socketpair -# define SYS_socketpair __NR_socketpair +#ifdef __NR_socketpair +#define SYS_socketpair __NR_socketpair #endif -#ifdef __NR_spill -# define SYS_spill __NR_spill +#ifdef __NR_spill +#define SYS_spill __NR_spill #endif -#ifdef __NR_splice -# define SYS_splice __NR_splice +#ifdef __NR_splice +#define SYS_splice __NR_splice #endif -#ifdef __NR_spu_create -# define SYS_spu_create __NR_spu_create +#ifdef __NR_spu_create +#define SYS_spu_create __NR_spu_create #endif -#ifdef __NR_spu_run -# define SYS_spu_run __NR_spu_run +#ifdef __NR_spu_run +#define SYS_spu_run __NR_spu_run #endif -#ifdef __NR_ssetmask -# define SYS_ssetmask __NR_ssetmask +#ifdef __NR_ssetmask +#define SYS_ssetmask __NR_ssetmask #endif -#ifdef __NR_stat -# define SYS_stat __NR_stat +#ifdef __NR_stat +#define SYS_stat __NR_stat #endif -#ifdef __NR_stat64 -# define SYS_stat64 __NR_stat64 +#ifdef __NR_stat64 +#define SYS_stat64 __NR_stat64 #endif -#ifdef __NR_statfs -# define SYS_statfs __NR_statfs +#ifdef __NR_statfs +#define SYS_statfs __NR_statfs #endif -#ifdef __NR_statfs64 -# define SYS_statfs64 __NR_statfs64 +#ifdef __NR_statfs64 +#define SYS_statfs64 __NR_statfs64 #endif -#ifdef __NR_statx -# define SYS_statx __NR_statx +#ifdef __NR_statx +#define SYS_statx __NR_statx #endif -#ifdef __NR_stime -# define SYS_stime __NR_stime +#ifdef __NR_stime +#define SYS_stime __NR_stime #endif -#ifdef __NR_subpage_prot -# define SYS_subpage_prot __NR_subpage_prot +#ifdef __NR_subpage_prot +#define SYS_subpage_prot __NR_subpage_prot #endif -#ifdef __NR_swapcontext -# define SYS_swapcontext __NR_swapcontext +#ifdef __NR_swapcontext +#define SYS_swapcontext __NR_swapcontext #endif -#ifdef __NR_swapoff -# define SYS_swapoff __NR_swapoff +#ifdef __NR_swapoff +#define SYS_swapoff __NR_swapoff #endif -#ifdef __NR_swapon -# define SYS_swapon __NR_swapon +#ifdef __NR_swapon +#define SYS_swapon __NR_swapon #endif -#ifdef __NR_switch_endian -# define SYS_switch_endian __NR_switch_endian +#ifdef __NR_switch_endian +#define SYS_switch_endian __NR_switch_endian #endif -#ifdef __NR_symlink -# define SYS_symlink __NR_symlink +#ifdef __NR_symlink +#define SYS_symlink __NR_symlink #endif -#ifdef __NR_symlinkat -# define SYS_symlinkat __NR_symlinkat +#ifdef __NR_symlinkat +#define SYS_symlinkat __NR_symlinkat #endif -#ifdef __NR_sync -# define SYS_sync __NR_sync +#ifdef __NR_sync +#define SYS_sync __NR_sync #endif -#ifdef __NR_sync_file_range -# define SYS_sync_file_range __NR_sync_file_range +#ifdef __NR_sync_file_range +#define SYS_sync_file_range __NR_sync_file_range #endif -#ifdef __NR_sync_file_range2 -# define SYS_sync_file_range2 __NR_sync_file_range2 +#ifdef __NR_sync_file_range2 +#define SYS_sync_file_range2 __NR_sync_file_range2 #endif -#ifdef __NR_syncfs -# define SYS_syncfs __NR_syncfs +#ifdef __NR_syncfs +#define SYS_syncfs __NR_syncfs #endif -#ifdef __NR_sys_debug_setcontext -# define SYS_sys_debug_setcontext __NR_sys_debug_setcontext +#ifdef __NR_sys_debug_setcontext +#define SYS_sys_debug_setcontext __NR_sys_debug_setcontext #endif -#ifdef __NR_syscall -# define SYS_syscall __NR_syscall +#ifdef __NR_syscall +#define SYS_syscall __NR_syscall #endif -#ifdef __NR_syscalls -# define SYS_syscalls __NR_syscalls +#ifdef __NR_syscalls +#define SYS_syscalls __NR_syscalls #endif -#ifdef __NR_sysfs -# define SYS_sysfs __NR_sysfs +#ifdef __NR_sysfs +#define SYS_sysfs __NR_sysfs #endif -#ifdef __NR_sysinfo -# define SYS_sysinfo __NR_sysinfo +#ifdef __NR_sysinfo +#define SYS_sysinfo __NR_sysinfo #endif -#ifdef __NR_syslog -# define SYS_syslog __NR_syslog +#ifdef __NR_syslog +#define SYS_syslog __NR_syslog #endif -#ifdef __NR_sysmips -# define SYS_sysmips __NR_sysmips +#ifdef __NR_sysmips +#define SYS_sysmips __NR_sysmips #endif -#ifdef __NR_tee -# define SYS_tee __NR_tee +#ifdef __NR_tee +#define SYS_tee __NR_tee #endif -#ifdef __NR_tgkill -# define SYS_tgkill __NR_tgkill +#ifdef __NR_tgkill +#define SYS_tgkill __NR_tgkill #endif -#ifdef __NR_time -# define SYS_time __NR_time +#ifdef __NR_time +#define SYS_time __NR_time #endif -#ifdef __NR_timer_create -# define SYS_timer_create __NR_timer_create +#ifdef __NR_timer_create +#define SYS_timer_create __NR_timer_create #endif -#ifdef __NR_timer_delete -# define SYS_timer_delete __NR_timer_delete +#ifdef __NR_timer_delete +#define SYS_timer_delete __NR_timer_delete #endif -#ifdef __NR_timer_getoverrun -# define SYS_timer_getoverrun __NR_timer_getoverrun +#ifdef __NR_timer_getoverrun +#define SYS_timer_getoverrun __NR_timer_getoverrun #endif -#ifdef __NR_timer_gettime -# define SYS_timer_gettime __NR_timer_gettime +#ifdef __NR_timer_gettime +#define SYS_timer_gettime __NR_timer_gettime #endif -#ifdef __NR_timer_gettime64 -# define SYS_timer_gettime64 __NR_timer_gettime64 +#ifdef __NR_timer_gettime64 +#define SYS_timer_gettime64 __NR_timer_gettime64 #endif -#ifdef __NR_timer_settime -# define SYS_timer_settime __NR_timer_settime +#ifdef __NR_timer_settime +#define SYS_timer_settime __NR_timer_settime #endif -#ifdef __NR_timer_settime64 -# define SYS_timer_settime64 __NR_timer_settime64 +#ifdef __NR_timer_settime64 +#define SYS_timer_settime64 __NR_timer_settime64 #endif -#ifdef __NR_timerfd -# define SYS_timerfd __NR_timerfd +#ifdef __NR_timerfd +#define SYS_timerfd __NR_timerfd #endif -#ifdef __NR_timerfd_create -# define SYS_timerfd_create __NR_timerfd_create +#ifdef __NR_timerfd_create +#define SYS_timerfd_create __NR_timerfd_create #endif -#ifdef __NR_timerfd_gettime -# define SYS_timerfd_gettime __NR_timerfd_gettime +#ifdef __NR_timerfd_gettime +#define SYS_timerfd_gettime __NR_timerfd_gettime #endif -#ifdef __NR_timerfd_gettime64 -# define SYS_timerfd_gettime64 __NR_timerfd_gettime64 +#ifdef __NR_timerfd_gettime64 +#define SYS_timerfd_gettime64 __NR_timerfd_gettime64 #endif -#ifdef __NR_timerfd_settime -# define SYS_timerfd_settime __NR_timerfd_settime +#ifdef __NR_timerfd_settime +#define SYS_timerfd_settime __NR_timerfd_settime #endif -#ifdef __NR_timerfd_settime64 -# define SYS_timerfd_settime64 __NR_timerfd_settime64 +#ifdef __NR_timerfd_settime64 +#define SYS_timerfd_settime64 __NR_timerfd_settime64 #endif -#ifdef __NR_times -# define SYS_times __NR_times +#ifdef __NR_times +#define SYS_times __NR_times #endif -#ifdef __NR_tkill -# define SYS_tkill __NR_tkill +#ifdef __NR_tkill +#define SYS_tkill __NR_tkill #endif -#ifdef __NR_truncate -# define SYS_truncate __NR_truncate +#ifdef __NR_truncate +#define SYS_truncate __NR_truncate #endif -#ifdef __NR_truncate64 -# define SYS_truncate64 __NR_truncate64 +#ifdef __NR_truncate64 +#define SYS_truncate64 __NR_truncate64 #endif -#ifdef __NR_ugetrlimit -# define SYS_ugetrlimit __NR_ugetrlimit +#ifdef __NR_ugetrlimit +#define SYS_ugetrlimit __NR_ugetrlimit #endif -#ifdef __NR_umask -# define SYS_umask __NR_umask +#ifdef __NR_umask +#define SYS_umask __NR_umask #endif -#ifdef __NR_umount -# define SYS_umount __NR_umount +#ifdef __NR_umount +#define SYS_umount __NR_umount #endif -#ifdef __NR_umount2 -# define SYS_umount2 __NR_umount2 +#ifdef __NR_umount2 +#define SYS_umount2 __NR_umount2 #endif -#ifdef __NR_uname -# define SYS_uname __NR_uname +#ifdef __NR_uname +#define SYS_uname __NR_uname #endif -#ifdef __NR_unlink -# define SYS_unlink __NR_unlink +#ifdef __NR_unlink +#define SYS_unlink __NR_unlink #endif -#ifdef __NR_unlinkat -# define SYS_unlinkat __NR_unlinkat +#ifdef __NR_unlinkat +#define SYS_unlinkat __NR_unlinkat #endif -#ifdef __NR_unshare -# define SYS_unshare __NR_unshare +#ifdef __NR_unshare +#define SYS_unshare __NR_unshare #endif -#ifdef __NR_uselib -# define SYS_uselib __NR_uselib +#ifdef __NR_uselib +#define SYS_uselib __NR_uselib #endif -#ifdef __NR_userfaultfd -# define SYS_userfaultfd __NR_userfaultfd +#ifdef __NR_userfaultfd +#define SYS_userfaultfd __NR_userfaultfd #endif -#ifdef __NR_ustat -# define SYS_ustat __NR_ustat +#ifdef __NR_ustat +#define SYS_ustat __NR_ustat #endif -#ifdef __NR_utime -# define SYS_utime __NR_utime +#ifdef __NR_utime +#define SYS_utime __NR_utime #endif -#ifdef __NR_utimensat -# define SYS_utimensat __NR_utimensat +#ifdef __NR_utimensat +#define SYS_utimensat __NR_utimensat #endif -#ifdef __NR_utimensat_time64 -# define SYS_utimensat_time64 __NR_utimensat_time64 +#ifdef __NR_utimensat_time64 +#define SYS_utimensat_time64 __NR_utimensat_time64 #endif -#ifdef __NR_utimes -# define SYS_utimes __NR_utimes +#ifdef __NR_utimes +#define SYS_utimes __NR_utimes #endif -#ifdef __NR_utrap_install -# define SYS_utrap_install __NR_utrap_install +#ifdef __NR_utrap_install +#define SYS_utrap_install __NR_utrap_install #endif -#ifdef __NR_vfork -# define SYS_vfork __NR_vfork +#ifdef __NR_vfork +#define SYS_vfork __NR_vfork #endif -#ifdef __NR_vhangup -# define SYS_vhangup __NR_vhangup +#ifdef __NR_vhangup +#define SYS_vhangup __NR_vhangup #endif -#ifdef __NR_vm86 -# define SYS_vm86 __NR_vm86 +#ifdef __NR_vm86 +#define SYS_vm86 __NR_vm86 #endif -#ifdef __NR_vm86old -# define SYS_vm86old __NR_vm86old +#ifdef __NR_vm86old +#define SYS_vm86old __NR_vm86old #endif -#ifdef __NR_vmsplice -# define SYS_vmsplice __NR_vmsplice +#ifdef __NR_vmsplice +#define SYS_vmsplice __NR_vmsplice #endif -#ifdef __NR_wait4 -# define SYS_wait4 __NR_wait4 +#ifdef __NR_wait4 +#define SYS_wait4 __NR_wait4 #endif -#ifdef __NR_waitid -# define SYS_waitid __NR_waitid +#ifdef __NR_waitid +#define SYS_waitid __NR_waitid #endif -#ifdef __NR_waitpid -# define SYS_waitpid __NR_waitpid +#ifdef __NR_waitpid +#define SYS_waitpid __NR_waitpid #endif -#ifdef __NR_write -# define SYS_write __NR_write +#ifdef __NR_write +#define SYS_write __NR_write #endif -#ifdef __NR_writev -# define SYS_writev __NR_writev +#ifdef __NR_writev +#define SYS_writev __NR_writev #endif #endif /* __MLIBC_SYSCALL_ALIAS_BIT */ diff --git a/sysdeps/linux/include/mlibc/thread-entry.hpp b/sysdeps/linux/include/mlibc/thread-entry.hpp index a20cab5842..d832105f50 100644 --- a/sysdeps/linux/include/mlibc/thread-entry.hpp +++ b/sysdeps/linux/include/mlibc/thread-entry.hpp @@ -2,11 +2,12 @@ #include -extern "C" int __mlibc_spawn_thread(int flags, void *stack, void *pid_out, void *child_tid, void *tcb); +extern "C" int +__mlibc_spawn_thread(int flags, void *stack, void *pid_out, void *child_tid, void *tcb); extern "C" void __mlibc_enter_thread(void *entry, void *user_arg); namespace mlibc { - void *prepare_stack(void *entry, void *user_arg); +void *prepare_stack(void *entry, void *user_arg); } #endif // MLIBC_THREAD_ENTRY diff --git a/sysdeps/linux/m68k/arch-syscall.cpp b/sysdeps/linux/m68k/arch-syscall.cpp index 57b944e015..62b6fc4fe4 100644 --- a/sysdeps/linux/m68k/arch-syscall.cpp +++ b/sysdeps/linux/m68k/arch-syscall.cpp @@ -1,79 +1,62 @@ -#include #include +#include using sc_word_t = __sc_word_t; sc_word_t __do_syscall0(long sc) { register int sc_reg asm("d0") = sc; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : "r"(sc_reg) : "memory"); + asm volatile("trap #0" : "=r"(ret) : "r"(sc_reg) : "memory"); return ret; } -sc_word_t __do_syscall1(long sc, - sc_word_t arg1) { +sc_word_t __do_syscall1(long sc, sc_word_t arg1) { register int sc_reg asm("d0") = sc; register sc_word_t arg1_reg asm("d1") = arg1; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg) - : "memory"); + asm volatile("trap #0" : "=r"(ret) : "r"(sc_reg), "r"(arg1_reg) : "memory"); return ret; } -sc_word_t __do_syscall2(long sc, - sc_word_t arg1, sc_word_t arg2) { +sc_word_t __do_syscall2(long sc, sc_word_t arg1, sc_word_t arg2) { register int sc_reg asm("d0") = sc; register sc_word_t arg1_reg asm("d1") = arg1; register sc_word_t arg2_reg asm("d2") = arg2; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg) - : "memory"); + asm volatile("trap #0" : "=r"(ret) : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg) : "memory"); return ret; } -sc_word_t __do_syscall3(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { +sc_word_t __do_syscall3(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { register int sc_reg asm("d0") = sc; register sc_word_t arg1_reg asm("d1") = arg1; register sc_word_t arg2_reg asm("d2") = arg2; register sc_word_t arg3_reg asm("d3") = arg3; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg) - : "memory"); + asm volatile("trap #0" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg) + : "memory"); return ret; } -sc_word_t __do_syscall4(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4) { +sc_word_t __do_syscall4(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { register int sc_reg asm("d0") = sc; register sc_word_t arg1_reg asm("d1") = arg1; register sc_word_t arg2_reg asm("d2") = arg2; register sc_word_t arg3_reg asm("d3") = arg3; register sc_word_t arg4_reg asm("d4") = arg4; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg) - : "memory"); + asm volatile("trap #0" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg), "r"(arg4_reg) + : "memory"); return ret; } -sc_word_t __do_syscall5(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5) { +sc_word_t __do_syscall5( + long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { register int sc_reg asm("d0") = sc; register sc_word_t arg1_reg asm("d1") = arg1; register sc_word_t arg2_reg asm("d2") = arg2; @@ -81,20 +64,24 @@ sc_word_t __do_syscall5(long sc, register sc_word_t arg4_reg asm("d4") = arg4; register sc_word_t arg5_reg asm("d5") = arg5; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg), - "r"(arg5_reg) - : "memory"); + asm volatile( + "trap #0" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg), "r"(arg4_reg), "r"(arg5_reg) + : "memory" + ); return ret; } -sc_word_t __do_syscall6(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5, sc_word_t arg6) { +sc_word_t __do_syscall6( + long sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { register int sc_reg asm("d0") = sc; register sc_word_t arg1_reg asm("d1") = arg1; register sc_word_t arg2_reg asm("d2") = arg2; @@ -103,15 +90,15 @@ sc_word_t __do_syscall6(long sc, register sc_word_t arg5_reg asm("d5") = arg5; register sc_word_t arg6_reg asm("a0") = arg6; register sc_word_t ret asm("d0"); - asm volatile ("trap #0" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg), - "r"(arg5_reg), - "r"(arg6_reg) - : "memory" - ); + asm volatile("trap #0" + : "=r"(ret) + : "r"(sc_reg), + "r"(arg1_reg), + "r"(arg2_reg), + "r"(arg3_reg), + "r"(arg4_reg), + "r"(arg5_reg), + "r"(arg6_reg) + : "memory"); return ret; } diff --git a/sysdeps/linux/m68k/syscallnos.h b/sysdeps/linux/m68k/syscallnos.h index 7b51cebce2..7ec96e77a0 100644 --- a/sysdeps/linux/m68k/syscallnos.h +++ b/sysdeps/linux/m68k/syscallnos.h @@ -2,427 +2,427 @@ #define __MLIBC_SYSCALLNOS_h /* This file is autogenerated. Don't bother. */ /* Generator script: sysdeps/linux/update-syscall-list.py. */ -#define __NR_restart_syscall 0 -#define __NR_exit 1 -#define __NR_fork 2 -#define __NR_read 3 -#define __NR_write 4 -#define __NR_open 5 -#define __NR_close 6 -#define __NR_waitpid 7 -#define __NR_creat 8 -#define __NR_link 9 -#define __NR_unlink 10 -#define __NR_execve 11 -#define __NR_chdir 12 -#define __NR_time 13 -#define __NR_mknod 14 -#define __NR_chmod 15 -#define __NR_chown 16 -#define __NR_oldstat 18 -#define __NR_lseek 19 -#define __NR_getpid 20 -#define __NR_mount 21 -#define __NR_umount 22 -#define __NR_setuid 23 -#define __NR_getuid 24 -#define __NR_stime 25 -#define __NR_ptrace 26 -#define __NR_alarm 27 -#define __NR_oldfstat 28 -#define __NR_pause 29 -#define __NR_utime 30 -#define __NR_access 33 -#define __NR_nice 34 -#define __NR_sync 36 -#define __NR_kill 37 -#define __NR_rename 38 -#define __NR_mkdir 39 -#define __NR_rmdir 40 -#define __NR_dup 41 -#define __NR_pipe 42 -#define __NR_times 43 -#define __NR_brk 45 -#define __NR_setgid 46 -#define __NR_getgid 47 -#define __NR_signal 48 -#define __NR_geteuid 49 -#define __NR_getegid 50 -#define __NR_acct 51 -#define __NR_umount2 52 -#define __NR_ioctl 54 -#define __NR_fcntl 55 -#define __NR_setpgid 57 -#define __NR_umask 60 -#define __NR_chroot 61 -#define __NR_ustat 62 -#define __NR_dup2 63 -#define __NR_getppid 64 -#define __NR_getpgrp 65 -#define __NR_setsid 66 -#define __NR_sigaction 67 -#define __NR_sgetmask 68 -#define __NR_ssetmask 69 -#define __NR_setreuid 70 -#define __NR_setregid 71 -#define __NR_sigsuspend 72 -#define __NR_sigpending 73 -#define __NR_sethostname 74 -#define __NR_setrlimit 75 -#define __NR_getrlimit 76 -#define __NR_getrusage 77 -#define __NR_gettimeofday_time32 78 -#define __NR_settimeofday_time32 79 -#define __NR_getgroups 80 -#define __NR_setgroups 81 -#define __NR_select 82 -#define __NR_symlink 83 -#define __NR_oldlstat 84 -#define __NR_readlink 85 -#define __NR_uselib 86 -#define __NR_swapon 87 -#define __NR_reboot 88 -#define __NR_readdir 89 -#define __NR_mmap 90 -#define __NR_munmap 91 -#define __NR_truncate 92 -#define __NR_ftruncate 93 -#define __NR_fchmod 94 -#define __NR_fchown 95 -#define __NR_getpriority 96 -#define __NR_setpriority 97 -#define __NR_statfs 99 -#define __NR_fstatfs 100 -#define __NR_socketcall 102 -#define __NR_syslog 103 -#define __NR_setitimer 104 -#define __NR_getitimer 105 -#define __NR_stat 106 -#define __NR_lstat 107 -#define __NR_fstat 108 -#define __NR_vhangup 111 -#define __NR_wait4 114 -#define __NR_swapoff 115 -#define __NR_sysinfo 116 -#define __NR_ipc 117 -#define __NR_fsync 118 -#define __NR_sigreturn 119 -#define __NR_clone 120 -#define __NR_setdomainname 121 -#define __NR_uname 122 -#define __NR_cacheflush 123 -#define __NR_adjtimex 124 -#define __NR_mprotect 125 -#define __NR_sigprocmask 126 -#define __NR_create_module 127 -#define __NR_init_module 128 -#define __NR_delete_module 129 -#define __NR_get_kernel_syms 130 -#define __NR_quotactl 131 -#define __NR_getpgid 132 -#define __NR_fchdir 133 -#define __NR_bdflush 134 -#define __NR_sysfs 135 -#define __NR_personality 136 -#define __NR_setfsuid 138 -#define __NR_setfsgid 139 -#define __NR__llseek 140 -#define __NR_getdents 141 -#define __NR__newselect 142 -#define __NR_flock 143 -#define __NR_msync 144 -#define __NR_readv 145 -#define __NR_writev 146 -#define __NR_getsid 147 -#define __NR_fdatasync 148 -#define __NR__sysctl 149 -#define __NR_mlock 150 -#define __NR_munlock 151 -#define __NR_mlockall 152 -#define __NR_munlockall 153 -#define __NR_sched_setparam 154 -#define __NR_sched_getparam 155 -#define __NR_sched_setscheduler 156 -#define __NR_sched_getscheduler 157 -#define __NR_sched_yield 158 -#define __NR_sched_get_priority_max 159 -#define __NR_sched_get_priority_min 160 -#define __NR_sched_rr_get_interval 161 -#define __NR_nanosleep 162 -#define __NR_mremap 163 -#define __NR_setresuid 164 -#define __NR_getresuid 165 -#define __NR_getpagesize 166 -#define __NR_query_module 167 -#define __NR_poll 168 -#define __NR_nfsservctl 169 -#define __NR_setresgid 170 -#define __NR_getresgid 171 -#define __NR_prctl 172 -#define __NR_rt_sigreturn 173 -#define __NR_rt_sigaction 174 -#define __NR_rt_sigprocmask 175 -#define __NR_rt_sigpending 176 -#define __NR_rt_sigtimedwait 177 -#define __NR_rt_sigqueueinfo 178 -#define __NR_rt_sigsuspend 179 -#define __NR_pread64 180 -#define __NR_pwrite64 181 -#define __NR_lchown 182 -#define __NR_getcwd 183 -#define __NR_capget 184 -#define __NR_capset 185 -#define __NR_sigaltstack 186 -#define __NR_sendfile 187 -#define __NR_getpmsg 188 -#define __NR_putpmsg 189 -#define __NR_vfork 190 -#define __NR_ugetrlimit 191 -#define __NR_mmap2 192 -#define __NR_truncate64 193 -#define __NR_ftruncate64 194 -#define __NR_stat64 195 -#define __NR_lstat64 196 -#define __NR_fstat64 197 -#define __NR_chown32 198 -#define __NR_getuid32 199 -#define __NR_getgid32 200 -#define __NR_geteuid32 201 -#define __NR_getegid32 202 -#define __NR_setreuid32 203 -#define __NR_setregid32 204 -#define __NR_getgroups32 205 -#define __NR_setgroups32 206 -#define __NR_fchown32 207 -#define __NR_setresuid32 208 -#define __NR_getresuid32 209 -#define __NR_setresgid32 210 -#define __NR_getresgid32 211 -#define __NR_lchown32 212 -#define __NR_setuid32 213 -#define __NR_setgid32 214 -#define __NR_setfsuid32 215 -#define __NR_setfsgid32 216 -#define __NR_pivot_root 217 -#define __NR_getdents64 220 -#define __NR_gettid 221 -#define __NR_tkill 222 -#define __NR_setxattr 223 -#define __NR_lsetxattr 224 -#define __NR_fsetxattr 225 -#define __NR_getxattr 226 -#define __NR_lgetxattr 227 -#define __NR_fgetxattr 228 -#define __NR_listxattr 229 -#define __NR_llistxattr 230 -#define __NR_flistxattr 231 -#define __NR_removexattr 232 -#define __NR_lremovexattr 233 -#define __NR_fremovexattr 234 -#define __NR_futex 235 -#define __NR_sendfile64 236 -#define __NR_mincore 237 -#define __NR_madvise 238 -#define __NR_fcntl64 239 -#define __NR_readahead 240 -#define __NR_io_setup 241 -#define __NR_io_destroy 242 -#define __NR_io_getevents 243 -#define __NR_io_submit 244 -#define __NR_io_cancel 245 -#define __NR_fadvise64 246 -#define __NR_exit_group 247 -#define __NR_lookup_dcookie 248 -#define __NR_epoll_create 249 -#define __NR_epoll_ctl 250 -#define __NR_epoll_wait 251 -#define __NR_remap_file_pages 252 -#define __NR_set_tid_address 253 -#define __NR_timer_create 254 -#define __NR_timer_settime32 255 -#define __NR_timer_gettime32 256 -#define __NR_timer_getoverrun 257 -#define __NR_timer_delete 258 -#define __NR_clock_settime32 259 -#define __NR_clock_gettime32 260 -#define __NR_clock_getres_time32 261 -#define __NR_clock_nanosleep_time32 262 -#define __NR_statfs64 263 -#define __NR_fstatfs64 264 -#define __NR_tgkill 265 -#define __NR_utimes 266 -#define __NR_fadvise64_64 267 -#define __NR_mbind 268 -#define __NR_get_mempolicy 269 -#define __NR_set_mempolicy 270 -#define __NR_mq_open 271 -#define __NR_mq_unlink 272 -#define __NR_mq_timedsend 273 -#define __NR_mq_timedreceive 274 -#define __NR_mq_notify 275 -#define __NR_mq_getsetattr 276 -#define __NR_waitid 277 -#define __NR_add_key 279 -#define __NR_request_key 280 -#define __NR_keyctl 281 -#define __NR_ioprio_set 282 -#define __NR_ioprio_get 283 -#define __NR_inotify_init 284 -#define __NR_inotify_add_watch 285 -#define __NR_inotify_rm_watch 286 -#define __NR_migrate_pages 287 -#define __NR_openat 288 -#define __NR_mkdirat 289 -#define __NR_mknodat 290 -#define __NR_fchownat 291 -#define __NR_futimesat 292 -#define __NR_fstatat64 293 -#define __NR_unlinkat 294 -#define __NR_renameat 295 -#define __NR_linkat 296 -#define __NR_symlinkat 297 -#define __NR_readlinkat 298 -#define __NR_fchmodat 299 -#define __NR_faccessat 300 -#define __NR_pselect6 301 -#define __NR_ppoll 302 -#define __NR_unshare 303 -#define __NR_set_robust_list 304 -#define __NR_get_robust_list 305 -#define __NR_splice 306 -#define __NR_sync_file_range 307 -#define __NR_tee 308 -#define __NR_vmsplice 309 -#define __NR_move_pages 310 -#define __NR_sched_setaffinity 311 -#define __NR_sched_getaffinity 312 -#define __NR_kexec_load 313 -#define __NR_getcpu 314 -#define __NR_epoll_pwait 315 -#define __NR_utimensat 316 -#define __NR_signalfd 317 -#define __NR_timerfd_create 318 -#define __NR_eventfd 319 -#define __NR_fallocate 320 -#define __NR_timerfd_settime32 321 -#define __NR_timerfd_gettime32 322 -#define __NR_signalfd4 323 -#define __NR_eventfd2 324 -#define __NR_epoll_create1 325 -#define __NR_dup3 326 -#define __NR_pipe2 327 -#define __NR_inotify_init1 328 -#define __NR_preadv 329 -#define __NR_pwritev 330 -#define __NR_rt_tgsigqueueinfo 331 -#define __NR_perf_event_open 332 -#define __NR_get_thread_area 333 -#define __NR_set_thread_area 334 -#define __NR_atomic_cmpxchg_32 335 -#define __NR_atomic_barrier 336 -#define __NR_fanotify_init 337 -#define __NR_fanotify_mark 338 -#define __NR_prlimit64 339 -#define __NR_name_to_handle_at 340 -#define __NR_open_by_handle_at 341 -#define __NR_clock_adjtime 342 -#define __NR_syncfs 343 -#define __NR_setns 344 -#define __NR_process_vm_readv 345 -#define __NR_process_vm_writev 346 -#define __NR_kcmp 347 -#define __NR_finit_module 348 -#define __NR_sched_setattr 349 -#define __NR_sched_getattr 350 -#define __NR_renameat2 351 -#define __NR_getrandom 352 -#define __NR_memfd_create 353 -#define __NR_bpf 354 -#define __NR_execveat 355 -#define __NR_socket 356 -#define __NR_socketpair 357 -#define __NR_bind 358 -#define __NR_connect 359 -#define __NR_listen 360 -#define __NR_accept4 361 -#define __NR_getsockopt 362 -#define __NR_setsockopt 363 -#define __NR_getsockname 364 -#define __NR_getpeername 365 -#define __NR_sendto 366 -#define __NR_sendmsg 367 -#define __NR_recvfrom 368 -#define __NR_recvmsg 369 -#define __NR_shutdown 370 -#define __NR_recvmmsg 371 -#define __NR_sendmmsg 372 -#define __NR_userfaultfd 373 -#define __NR_membarrier 374 -#define __NR_mlock2 375 -#define __NR_copy_file_range 376 -#define __NR_preadv2 377 -#define __NR_pwritev2 378 -#define __NR_statx 379 -#define __NR_seccomp 380 -#define __NR_pkey_mprotect 381 -#define __NR_pkey_alloc 382 -#define __NR_pkey_free 383 -#define __NR_rseq 384 -#define __NR_semget 393 -#define __NR_semctl 394 -#define __NR_shmget 395 -#define __NR_shmctl 396 -#define __NR_shmat 397 -#define __NR_shmdt 398 -#define __NR_msgget 399 -#define __NR_msgsnd 400 -#define __NR_msgrcv 401 -#define __NR_msgctl 402 -#define __NR_clock_gettime64 403 -#define __NR_clock_settime64 404 -#define __NR_clock_adjtime64 405 +#define __NR_restart_syscall 0 +#define __NR_exit 1 +#define __NR_fork 2 +#define __NR_read 3 +#define __NR_write 4 +#define __NR_open 5 +#define __NR_close 6 +#define __NR_waitpid 7 +#define __NR_creat 8 +#define __NR_link 9 +#define __NR_unlink 10 +#define __NR_execve 11 +#define __NR_chdir 12 +#define __NR_time 13 +#define __NR_mknod 14 +#define __NR_chmod 15 +#define __NR_chown 16 +#define __NR_oldstat 18 +#define __NR_lseek 19 +#define __NR_getpid 20 +#define __NR_mount 21 +#define __NR_umount 22 +#define __NR_setuid 23 +#define __NR_getuid 24 +#define __NR_stime 25 +#define __NR_ptrace 26 +#define __NR_alarm 27 +#define __NR_oldfstat 28 +#define __NR_pause 29 +#define __NR_utime 30 +#define __NR_access 33 +#define __NR_nice 34 +#define __NR_sync 36 +#define __NR_kill 37 +#define __NR_rename 38 +#define __NR_mkdir 39 +#define __NR_rmdir 40 +#define __NR_dup 41 +#define __NR_pipe 42 +#define __NR_times 43 +#define __NR_brk 45 +#define __NR_setgid 46 +#define __NR_getgid 47 +#define __NR_signal 48 +#define __NR_geteuid 49 +#define __NR_getegid 50 +#define __NR_acct 51 +#define __NR_umount2 52 +#define __NR_ioctl 54 +#define __NR_fcntl 55 +#define __NR_setpgid 57 +#define __NR_umask 60 +#define __NR_chroot 61 +#define __NR_ustat 62 +#define __NR_dup2 63 +#define __NR_getppid 64 +#define __NR_getpgrp 65 +#define __NR_setsid 66 +#define __NR_sigaction 67 +#define __NR_sgetmask 68 +#define __NR_ssetmask 69 +#define __NR_setreuid 70 +#define __NR_setregid 71 +#define __NR_sigsuspend 72 +#define __NR_sigpending 73 +#define __NR_sethostname 74 +#define __NR_setrlimit 75 +#define __NR_getrlimit 76 +#define __NR_getrusage 77 +#define __NR_gettimeofday_time32 78 +#define __NR_settimeofday_time32 79 +#define __NR_getgroups 80 +#define __NR_setgroups 81 +#define __NR_select 82 +#define __NR_symlink 83 +#define __NR_oldlstat 84 +#define __NR_readlink 85 +#define __NR_uselib 86 +#define __NR_swapon 87 +#define __NR_reboot 88 +#define __NR_readdir 89 +#define __NR_mmap 90 +#define __NR_munmap 91 +#define __NR_truncate 92 +#define __NR_ftruncate 93 +#define __NR_fchmod 94 +#define __NR_fchown 95 +#define __NR_getpriority 96 +#define __NR_setpriority 97 +#define __NR_statfs 99 +#define __NR_fstatfs 100 +#define __NR_socketcall 102 +#define __NR_syslog 103 +#define __NR_setitimer 104 +#define __NR_getitimer 105 +#define __NR_stat 106 +#define __NR_lstat 107 +#define __NR_fstat 108 +#define __NR_vhangup 111 +#define __NR_wait4 114 +#define __NR_swapoff 115 +#define __NR_sysinfo 116 +#define __NR_ipc 117 +#define __NR_fsync 118 +#define __NR_sigreturn 119 +#define __NR_clone 120 +#define __NR_setdomainname 121 +#define __NR_uname 122 +#define __NR_cacheflush 123 +#define __NR_adjtimex 124 +#define __NR_mprotect 125 +#define __NR_sigprocmask 126 +#define __NR_create_module 127 +#define __NR_init_module 128 +#define __NR_delete_module 129 +#define __NR_get_kernel_syms 130 +#define __NR_quotactl 131 +#define __NR_getpgid 132 +#define __NR_fchdir 133 +#define __NR_bdflush 134 +#define __NR_sysfs 135 +#define __NR_personality 136 +#define __NR_setfsuid 138 +#define __NR_setfsgid 139 +#define __NR__llseek 140 +#define __NR_getdents 141 +#define __NR__newselect 142 +#define __NR_flock 143 +#define __NR_msync 144 +#define __NR_readv 145 +#define __NR_writev 146 +#define __NR_getsid 147 +#define __NR_fdatasync 148 +#define __NR__sysctl 149 +#define __NR_mlock 150 +#define __NR_munlock 151 +#define __NR_mlockall 152 +#define __NR_munlockall 153 +#define __NR_sched_setparam 154 +#define __NR_sched_getparam 155 +#define __NR_sched_setscheduler 156 +#define __NR_sched_getscheduler 157 +#define __NR_sched_yield 158 +#define __NR_sched_get_priority_max 159 +#define __NR_sched_get_priority_min 160 +#define __NR_sched_rr_get_interval 161 +#define __NR_nanosleep 162 +#define __NR_mremap 163 +#define __NR_setresuid 164 +#define __NR_getresuid 165 +#define __NR_getpagesize 166 +#define __NR_query_module 167 +#define __NR_poll 168 +#define __NR_nfsservctl 169 +#define __NR_setresgid 170 +#define __NR_getresgid 171 +#define __NR_prctl 172 +#define __NR_rt_sigreturn 173 +#define __NR_rt_sigaction 174 +#define __NR_rt_sigprocmask 175 +#define __NR_rt_sigpending 176 +#define __NR_rt_sigtimedwait 177 +#define __NR_rt_sigqueueinfo 178 +#define __NR_rt_sigsuspend 179 +#define __NR_pread64 180 +#define __NR_pwrite64 181 +#define __NR_lchown 182 +#define __NR_getcwd 183 +#define __NR_capget 184 +#define __NR_capset 185 +#define __NR_sigaltstack 186 +#define __NR_sendfile 187 +#define __NR_getpmsg 188 +#define __NR_putpmsg 189 +#define __NR_vfork 190 +#define __NR_ugetrlimit 191 +#define __NR_mmap2 192 +#define __NR_truncate64 193 +#define __NR_ftruncate64 194 +#define __NR_stat64 195 +#define __NR_lstat64 196 +#define __NR_fstat64 197 +#define __NR_chown32 198 +#define __NR_getuid32 199 +#define __NR_getgid32 200 +#define __NR_geteuid32 201 +#define __NR_getegid32 202 +#define __NR_setreuid32 203 +#define __NR_setregid32 204 +#define __NR_getgroups32 205 +#define __NR_setgroups32 206 +#define __NR_fchown32 207 +#define __NR_setresuid32 208 +#define __NR_getresuid32 209 +#define __NR_setresgid32 210 +#define __NR_getresgid32 211 +#define __NR_lchown32 212 +#define __NR_setuid32 213 +#define __NR_setgid32 214 +#define __NR_setfsuid32 215 +#define __NR_setfsgid32 216 +#define __NR_pivot_root 217 +#define __NR_getdents64 220 +#define __NR_gettid 221 +#define __NR_tkill 222 +#define __NR_setxattr 223 +#define __NR_lsetxattr 224 +#define __NR_fsetxattr 225 +#define __NR_getxattr 226 +#define __NR_lgetxattr 227 +#define __NR_fgetxattr 228 +#define __NR_listxattr 229 +#define __NR_llistxattr 230 +#define __NR_flistxattr 231 +#define __NR_removexattr 232 +#define __NR_lremovexattr 233 +#define __NR_fremovexattr 234 +#define __NR_futex 235 +#define __NR_sendfile64 236 +#define __NR_mincore 237 +#define __NR_madvise 238 +#define __NR_fcntl64 239 +#define __NR_readahead 240 +#define __NR_io_setup 241 +#define __NR_io_destroy 242 +#define __NR_io_getevents 243 +#define __NR_io_submit 244 +#define __NR_io_cancel 245 +#define __NR_fadvise64 246 +#define __NR_exit_group 247 +#define __NR_lookup_dcookie 248 +#define __NR_epoll_create 249 +#define __NR_epoll_ctl 250 +#define __NR_epoll_wait 251 +#define __NR_remap_file_pages 252 +#define __NR_set_tid_address 253 +#define __NR_timer_create 254 +#define __NR_timer_settime32 255 +#define __NR_timer_gettime32 256 +#define __NR_timer_getoverrun 257 +#define __NR_timer_delete 258 +#define __NR_clock_settime32 259 +#define __NR_clock_gettime32 260 +#define __NR_clock_getres_time32 261 +#define __NR_clock_nanosleep_time32 262 +#define __NR_statfs64 263 +#define __NR_fstatfs64 264 +#define __NR_tgkill 265 +#define __NR_utimes 266 +#define __NR_fadvise64_64 267 +#define __NR_mbind 268 +#define __NR_get_mempolicy 269 +#define __NR_set_mempolicy 270 +#define __NR_mq_open 271 +#define __NR_mq_unlink 272 +#define __NR_mq_timedsend 273 +#define __NR_mq_timedreceive 274 +#define __NR_mq_notify 275 +#define __NR_mq_getsetattr 276 +#define __NR_waitid 277 +#define __NR_add_key 279 +#define __NR_request_key 280 +#define __NR_keyctl 281 +#define __NR_ioprio_set 282 +#define __NR_ioprio_get 283 +#define __NR_inotify_init 284 +#define __NR_inotify_add_watch 285 +#define __NR_inotify_rm_watch 286 +#define __NR_migrate_pages 287 +#define __NR_openat 288 +#define __NR_mkdirat 289 +#define __NR_mknodat 290 +#define __NR_fchownat 291 +#define __NR_futimesat 292 +#define __NR_fstatat64 293 +#define __NR_unlinkat 294 +#define __NR_renameat 295 +#define __NR_linkat 296 +#define __NR_symlinkat 297 +#define __NR_readlinkat 298 +#define __NR_fchmodat 299 +#define __NR_faccessat 300 +#define __NR_pselect6 301 +#define __NR_ppoll 302 +#define __NR_unshare 303 +#define __NR_set_robust_list 304 +#define __NR_get_robust_list 305 +#define __NR_splice 306 +#define __NR_sync_file_range 307 +#define __NR_tee 308 +#define __NR_vmsplice 309 +#define __NR_move_pages 310 +#define __NR_sched_setaffinity 311 +#define __NR_sched_getaffinity 312 +#define __NR_kexec_load 313 +#define __NR_getcpu 314 +#define __NR_epoll_pwait 315 +#define __NR_utimensat 316 +#define __NR_signalfd 317 +#define __NR_timerfd_create 318 +#define __NR_eventfd 319 +#define __NR_fallocate 320 +#define __NR_timerfd_settime32 321 +#define __NR_timerfd_gettime32 322 +#define __NR_signalfd4 323 +#define __NR_eventfd2 324 +#define __NR_epoll_create1 325 +#define __NR_dup3 326 +#define __NR_pipe2 327 +#define __NR_inotify_init1 328 +#define __NR_preadv 329 +#define __NR_pwritev 330 +#define __NR_rt_tgsigqueueinfo 331 +#define __NR_perf_event_open 332 +#define __NR_get_thread_area 333 +#define __NR_set_thread_area 334 +#define __NR_atomic_cmpxchg_32 335 +#define __NR_atomic_barrier 336 +#define __NR_fanotify_init 337 +#define __NR_fanotify_mark 338 +#define __NR_prlimit64 339 +#define __NR_name_to_handle_at 340 +#define __NR_open_by_handle_at 341 +#define __NR_clock_adjtime 342 +#define __NR_syncfs 343 +#define __NR_setns 344 +#define __NR_process_vm_readv 345 +#define __NR_process_vm_writev 346 +#define __NR_kcmp 347 +#define __NR_finit_module 348 +#define __NR_sched_setattr 349 +#define __NR_sched_getattr 350 +#define __NR_renameat2 351 +#define __NR_getrandom 352 +#define __NR_memfd_create 353 +#define __NR_bpf 354 +#define __NR_execveat 355 +#define __NR_socket 356 +#define __NR_socketpair 357 +#define __NR_bind 358 +#define __NR_connect 359 +#define __NR_listen 360 +#define __NR_accept4 361 +#define __NR_getsockopt 362 +#define __NR_setsockopt 363 +#define __NR_getsockname 364 +#define __NR_getpeername 365 +#define __NR_sendto 366 +#define __NR_sendmsg 367 +#define __NR_recvfrom 368 +#define __NR_recvmsg 369 +#define __NR_shutdown 370 +#define __NR_recvmmsg 371 +#define __NR_sendmmsg 372 +#define __NR_userfaultfd 373 +#define __NR_membarrier 374 +#define __NR_mlock2 375 +#define __NR_copy_file_range 376 +#define __NR_preadv2 377 +#define __NR_pwritev2 378 +#define __NR_statx 379 +#define __NR_seccomp 380 +#define __NR_pkey_mprotect 381 +#define __NR_pkey_alloc 382 +#define __NR_pkey_free 383 +#define __NR_rseq 384 +#define __NR_semget 393 +#define __NR_semctl 394 +#define __NR_shmget 395 +#define __NR_shmctl 396 +#define __NR_shmat 397 +#define __NR_shmdt 398 +#define __NR_msgget 399 +#define __NR_msgsnd 400 +#define __NR_msgrcv 401 +#define __NR_msgctl 402 +#define __NR_clock_gettime64 403 +#define __NR_clock_settime64 404 +#define __NR_clock_adjtime64 405 #define __NR_clock_getres_time64 406 #define __NR_clock_nanosleep_time64 407 -#define __NR_timer_gettime64 408 -#define __NR_timer_settime64 409 -#define __NR_timerfd_gettime64 410 -#define __NR_timerfd_settime64 411 -#define __NR_utimensat_time64 412 -#define __NR_pselect6_time64 413 -#define __NR_ppoll_time64 414 +#define __NR_timer_gettime64 408 +#define __NR_timer_settime64 409 +#define __NR_timerfd_gettime64 410 +#define __NR_timerfd_settime64 411 +#define __NR_utimensat_time64 412 +#define __NR_pselect6_time64 413 +#define __NR_ppoll_time64 414 #define __NR_io_pgetevents_time64 416 -#define __NR_recvmmsg_time64 417 +#define __NR_recvmmsg_time64 417 #define __NR_mq_timedsend_time64 418 #define __NR_mq_timedreceive_time64 419 -#define __NR_semtimedop_time64 420 +#define __NR_semtimedop_time64 420 #define __NR_rt_sigtimedwait_time64 421 -#define __NR_futex_time64 422 +#define __NR_futex_time64 422 #define __NR_sched_rr_get_interval_time64 423 -#define __NR_pidfd_send_signal 424 -#define __NR_io_uring_setup 425 -#define __NR_io_uring_enter 426 -#define __NR_io_uring_register 427 -#define __NR_open_tree 428 -#define __NR_move_mount 429 -#define __NR_fsopen 430 -#define __NR_fsconfig 431 -#define __NR_fsmount 432 -#define __NR_fspick 433 -#define __NR_pidfd_open 434 -#define __NR_clone3 435 -#define __NR_close_range 436 -#define __NR_openat2 437 -#define __NR_pidfd_getfd 438 -#define __NR_faccessat2 439 -#define __NR_process_madvise 440 -#define __NR_epoll_pwait2 441 -#define __NR_mount_setattr 442 -#define __NR_landlock_create_ruleset 444 -#define __NR_landlock_add_rule 445 -#define __NR_landlock_restrict_self 446 -#define __NR_process_mrelease 448 -#define __NR_futex_waitv 449 -#define __NR_set_mempolicy_home_node 450 -#define __NR_cachestat 451 -#define __NR_fchmodat2 452 +#define __NR_pidfd_send_signal 424 +#define __NR_io_uring_setup 425 +#define __NR_io_uring_enter 426 +#define __NR_io_uring_register 427 +#define __NR_open_tree 428 +#define __NR_move_mount 429 +#define __NR_fsopen 430 +#define __NR_fsconfig 431 +#define __NR_fsmount 432 +#define __NR_fspick 433 +#define __NR_pidfd_open 434 +#define __NR_clone3 435 +#define __NR_close_range 436 +#define __NR_openat2 437 +#define __NR_pidfd_getfd 438 +#define __NR_faccessat2 439 +#define __NR_process_madvise 440 +#define __NR_epoll_pwait2 441 +#define __NR_mount_setattr 442 +#define __NR_landlock_create_ruleset 444 +#define __NR_landlock_add_rule 445 +#define __NR_landlock_restrict_self 446 +#define __NR_process_mrelease 448 +#define __NR_futex_waitv 449 +#define __NR_set_mempolicy_home_node 450 +#define __NR_cachestat 451 +#define __NR_fchmodat2 452 #endif /* __MLIBC_SYSCALLNOS_h */ diff --git a/sysdeps/linux/riscv64/arch-syscall.cpp b/sysdeps/linux/riscv64/arch-syscall.cpp index 18ac6b09b2..304f389932 100644 --- a/sysdeps/linux/riscv64/arch-syscall.cpp +++ b/sysdeps/linux/riscv64/arch-syscall.cpp @@ -1,79 +1,62 @@ -#include #include +#include using sc_word_t = __sc_word_t; sc_word_t __do_syscall0(long sc) { register int sc_reg asm("a7") = sc; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : "r"(sc_reg) : "memory", "a1"); + asm volatile("ecall" : "=r"(ret) : "r"(sc_reg) : "memory", "a1"); return ret; } -sc_word_t __do_syscall1(long sc, - sc_word_t arg1) { +sc_word_t __do_syscall1(long sc, sc_word_t arg1) { register int sc_reg asm("a7") = sc; register sc_word_t arg1_reg asm("a0") = arg1; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg) - : "memory", "a1"); + asm volatile("ecall" : "=r"(ret) : "r"(sc_reg), "r"(arg1_reg) : "memory", "a1"); return ret; } -sc_word_t __do_syscall2(long sc, - sc_word_t arg1, sc_word_t arg2) { +sc_word_t __do_syscall2(long sc, sc_word_t arg1, sc_word_t arg2) { register int sc_reg asm("a7") = sc; register sc_word_t arg1_reg asm("a0") = arg1; register sc_word_t arg2_reg asm("a1") = arg2; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg) - : "memory"); + asm volatile("ecall" : "=r"(ret) : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg) : "memory"); return ret; } -sc_word_t __do_syscall3(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { +sc_word_t __do_syscall3(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { register int sc_reg asm("a7") = sc; register sc_word_t arg1_reg asm("a0") = arg1; register sc_word_t arg2_reg asm("a1") = arg2; register sc_word_t arg3_reg asm("a2") = arg3; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg) - : "memory"); + asm volatile("ecall" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg) + : "memory"); return ret; } -sc_word_t __do_syscall4(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4) { +sc_word_t __do_syscall4(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { register int sc_reg asm("a7") = sc; register sc_word_t arg1_reg asm("a0") = arg1; register sc_word_t arg2_reg asm("a1") = arg2; register sc_word_t arg3_reg asm("a2") = arg3; register sc_word_t arg4_reg asm("a3") = arg4; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg) - : "memory"); + asm volatile("ecall" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg), "r"(arg4_reg) + : "memory"); return ret; } -sc_word_t __do_syscall5(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5) { +sc_word_t __do_syscall5( + long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { register int sc_reg asm("a7") = sc; register sc_word_t arg1_reg asm("a0") = arg1; register sc_word_t arg2_reg asm("a1") = arg2; @@ -81,20 +64,24 @@ sc_word_t __do_syscall5(long sc, register sc_word_t arg4_reg asm("a3") = arg4; register sc_word_t arg5_reg asm("a4") = arg5; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg), - "r"(arg5_reg) - : "memory"); + asm volatile( + "ecall" + : "=r"(ret) + : "r"(sc_reg), "r"(arg1_reg), "r"(arg2_reg), "r"(arg3_reg), "r"(arg4_reg), "r"(arg5_reg) + : "memory" + ); return ret; } -sc_word_t __do_syscall6(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5, sc_word_t arg6) { +sc_word_t __do_syscall6( + long sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { register int sc_reg asm("a7") = sc; register sc_word_t arg1_reg asm("a0") = arg1; register sc_word_t arg2_reg asm("a1") = arg2; @@ -103,15 +90,15 @@ sc_word_t __do_syscall6(long sc, register sc_word_t arg5_reg asm("a4") = arg5; register sc_word_t arg6_reg asm("a5") = arg6; register sc_word_t ret asm("a0"); - asm volatile ("ecall" : "=r"(ret) : - "r"(sc_reg), - "r"(arg1_reg), - "r"(arg2_reg), - "r"(arg3_reg), - "r"(arg4_reg), - "r"(arg5_reg), - "r"(arg6_reg) - : "memory" - ); + asm volatile("ecall" + : "=r"(ret) + : "r"(sc_reg), + "r"(arg1_reg), + "r"(arg2_reg), + "r"(arg3_reg), + "r"(arg4_reg), + "r"(arg5_reg), + "r"(arg6_reg) + : "memory"); return ret; } diff --git a/sysdeps/linux/x86/arch-syscall.cpp b/sysdeps/linux/x86/arch-syscall.cpp index 35fc8aacaa..1e3017b06b 100644 --- a/sysdeps/linux/x86/arch-syscall.cpp +++ b/sysdeps/linux/x86/arch-syscall.cpp @@ -3,8 +3,8 @@ using sc_word_t = __sc_word_t; -// Note: ebx is used for PIC (it holds a reference to the GOT), so we can't clobber it with gcc apparently, -// and also need to make sure to restore it after a syscall +// Note: ebx is used for PIC (it holds a reference to the GOT), so we can't clobber it with gcc +// apparently, and also need to make sure to restore it after a syscall sc_word_t __do_syscall0(long sc) { sc_word_t ret; @@ -15,76 +15,86 @@ sc_word_t __do_syscall0(long sc) { sc_word_t __do_syscall1(long sc, sc_word_t arg1) { sc_word_t ret; asm volatile("xchg %%ebx, %%edi;" - "int $0x80;" - "xchg %%edi, %%ebx;" - : "=a"(ret) - : "a"(sc), "D"(arg1) - : "memory"); + "int $0x80;" + "xchg %%edi, %%ebx;" + : "=a"(ret) + : "a"(sc), "D"(arg1) + : "memory"); return ret; } sc_word_t __do_syscall2(long sc, sc_word_t arg1, sc_word_t arg2) { sc_word_t ret; asm volatile("xchg %%ebx, %%edi;" - "int $0x80;" - "xchg %%edi, %%ebx;" - : "=a"(ret) - : "a"(sc), "D"(arg1), "c"(arg2) - : "memory"); + "int $0x80;" + "xchg %%edi, %%ebx;" + : "=a"(ret) + : "a"(sc), "D"(arg1), "c"(arg2) + : "memory"); return ret; } sc_word_t __do_syscall3(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { sc_word_t ret; asm volatile("xchg %%ebx, %%edi;" - "int $0x80;" - "xchg %%edi, %%ebx;" - : "=a"(ret) - : "a"(sc), "D"(arg1), "c"(arg2), "d"(arg3) - : "memory"); + "int $0x80;" + "xchg %%edi, %%ebx;" + : "=a"(ret) + : "a"(sc), "D"(arg1), "c"(arg2), "d"(arg3) + : "memory"); return ret; } sc_word_t __do_syscall4(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { sc_word_t ret; asm volatile("xchg %%ebx, %%edi;" - "int $0x80;" - "xchg %%edi, %%ebx;" - : "=a"(ret) - : "a"(sc), "D"(arg1), "c"(arg2), "d"(arg3), "S"(arg4) - : "memory"); + "int $0x80;" + "xchg %%edi, %%ebx;" + : "=a"(ret) + : "a"(sc), "D"(arg1), "c"(arg2), "d"(arg3), "S"(arg4) + : "memory"); return ret; } -sc_word_t __do_syscall5(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, - sc_word_t arg5) { +sc_word_t __do_syscall5( + long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { sc_word_t ret; asm volatile("pushl %2;" - "push %%ebx;" - "mov 4(%%esp), %%ebx;" - "int $0x80;" - "pop %%ebx;" - "add $4, %%esp;" - : "=a"(ret) - : "a"(sc), "g"(arg1), "c"(arg2), "d"(arg3), "S"(arg4), "D"(arg5) - : "memory"); + "push %%ebx;" + "mov 4(%%esp), %%ebx;" + "int $0x80;" + "pop %%ebx;" + "add $4, %%esp;" + : "=a"(ret) + : "a"(sc), "g"(arg1), "c"(arg2), "d"(arg3), "S"(arg4), "D"(arg5) + : "memory"); return ret; } -sc_word_t __do_syscall6(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, - sc_word_t arg5, sc_word_t arg6) { +sc_word_t __do_syscall6( + long sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { sc_word_t ret; - sc_word_t a1a6[2] = { arg1, arg6 }; - asm volatile ("pushl %1;" - "push %%ebx;" - "push %%ebp;" - "mov 8(%%esp),%%ebx;" - "mov 4(%%ebx),%%ebp;" - "mov (%%ebx),%%ebx;" - "int $0x80;" - "pop %%ebp;" - "pop %%ebx;" - "add $4,%%esp;" - : "=a"(ret) : "g"(&a1a6), "a"(sc), "c"(arg2), "d"(arg3), "S"(arg4), "D"(arg5) : "memory"); + sc_word_t a1a6[2] = {arg1, arg6}; + asm volatile("pushl %1;" + "push %%ebx;" + "push %%ebp;" + "mov 8(%%esp),%%ebx;" + "mov 4(%%ebx),%%ebp;" + "mov (%%ebx),%%ebx;" + "int $0x80;" + "pop %%ebp;" + "pop %%ebx;" + "add $4,%%esp;" + : "=a"(ret) + : "g"(&a1a6), "a"(sc), "c"(arg2), "d"(arg3), "S"(arg4), "D"(arg5) + : "memory"); return ret; } diff --git a/sysdeps/linux/x86_64/arch-syscall.cpp b/sysdeps/linux/x86_64/arch-syscall.cpp index d2ebbe7b47..6b7b5884e7 100644 --- a/sysdeps/linux/x86_64/arch-syscall.cpp +++ b/sysdeps/linux/x86_64/arch-syscall.cpp @@ -1,78 +1,76 @@ -#include #include +#include using sc_word_t = __sc_word_t; sc_word_t __do_syscall0(long sc) { sc_word_t ret; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc) - : "rcx", "r11", "memory"); + asm volatile("syscall" : "=a"(ret) : "a"(sc) : "rcx", "r11", "memory"); return ret; } -sc_word_t __do_syscall1(long sc, - sc_word_t arg1) { +sc_word_t __do_syscall1(long sc, sc_word_t arg1) { sc_word_t ret; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc), "D"(arg1) - : "rcx", "r11", "memory"); + asm volatile("syscall" : "=a"(ret) : "a"(sc), "D"(arg1) : "rcx", "r11", "memory"); return ret; } -sc_word_t __do_syscall2(long sc, - sc_word_t arg1, sc_word_t arg2) { +sc_word_t __do_syscall2(long sc, sc_word_t arg1, sc_word_t arg2) { sc_word_t ret; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc), "D"(arg1), "S"(arg2) - : "rcx", "r11", "memory"); + asm volatile("syscall" : "=a"(ret) : "a"(sc), "D"(arg1), "S"(arg2) : "rcx", "r11", "memory"); return ret; } -sc_word_t __do_syscall3(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { +sc_word_t __do_syscall3(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3) { sc_word_t ret; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3) - : "rcx", "r11", "memory"); + asm volatile("syscall" + : "=a"(ret) + : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3) + : "rcx", "r11", "memory"); return ret; } -sc_word_t __do_syscall4(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4) { +sc_word_t __do_syscall4(long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4) { sc_word_t ret; register sc_word_t arg4_reg asm("r10") = arg4; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3), - "r"(arg4_reg) - : "rcx", "r11", "memory"); + asm volatile("syscall" + : "=a"(ret) + : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3), "r"(arg4_reg) + : "rcx", "r11", "memory"); return ret; } -sc_word_t __do_syscall5(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5) { +sc_word_t __do_syscall5( + long sc, sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, sc_word_t arg4, sc_word_t arg5 +) { sc_word_t ret; register sc_word_t arg4_reg asm("r10") = arg4; register sc_word_t arg5_reg asm("r8") = arg5; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3), - "r"(arg4_reg), "r"(arg5_reg) - : "rcx", "r11", "memory"); + asm volatile("syscall" + : "=a"(ret) + : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3), "r"(arg4_reg), "r"(arg5_reg) + : "rcx", "r11", "memory"); return ret; } -sc_word_t __do_syscall6(long sc, - sc_word_t arg1, sc_word_t arg2, sc_word_t arg3, - sc_word_t arg4, sc_word_t arg5, sc_word_t arg6) { +sc_word_t __do_syscall6( + long sc, + sc_word_t arg1, + sc_word_t arg2, + sc_word_t arg3, + sc_word_t arg4, + sc_word_t arg5, + sc_word_t arg6 +) { sc_word_t ret; register sc_word_t arg4_reg asm("r10") = arg4; register sc_word_t arg5_reg asm("r8") = arg5; register sc_word_t arg6_reg asm("r9") = arg6; - asm volatile ("syscall" : "=a"(ret) - : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3), - "r"(arg4_reg), "r"(arg5_reg), "r"(arg6_reg) - : "rcx", "r11", "memory"); + asm volatile( + "syscall" + : "=a"(ret) + : "a"(sc), "D"(arg1), "S"(arg2), "d"(arg3), "r"(arg4_reg), "r"(arg5_reg), "r"(arg6_reg) + : "rcx", "r11", "memory" + ); return ret; } diff --git a/sysdeps/lyre/.clang-format b/sysdeps/lyre/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/lyre/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/sysdeps/managarm/aarch64/thread.cpp b/sysdeps/managarm/aarch64/thread.cpp index 88f1bf3588..129267d3e7 100644 --- a/sysdeps/managarm/aarch64/thread.cpp +++ b/sysdeps/managarm/aarch64/thread.cpp @@ -1,18 +1,18 @@ -#include -#include -#include #include -#include #include -#include +#include +#include +#include #include +#include +#include extern "C" void __mlibc_enter_thread(void *entry, void *user_arg, Tcb *tcb) { // Wait until our parent sets up the TID. - while(!__atomic_load_n(&tcb->tid, __ATOMIC_RELAXED)) + while (!__atomic_load_n(&tcb->tid, __ATOMIC_RELAXED)) mlibc::sys_futex_wait(&tcb->tid, 0, nullptr); - if(mlibc::sys_tcb_set(tcb)) + if (mlibc::sys_tcb_set(tcb)) __ensure(!"sys_tcb_set() failed"); tcb->invokeThreadFunc(entry, user_arg); @@ -29,7 +29,15 @@ namespace mlibc { static constexpr size_t default_stacksize = 0x200000; -int sys_prepare_stack(void **stack, void *entry, void *user_arg, void *tcb, size_t *stack_size, size_t *guard_size, void **stack_base) { +int sys_prepare_stack( + void **stack, + void *entry, + void *user_arg, + void *tcb, + size_t *stack_size, + size_t *guard_size, + void **stack_base +) { if (!*stack_size) *stack_size = default_stacksize; *guard_size = 0; @@ -37,20 +45,21 @@ int sys_prepare_stack(void **stack, void *entry, void *user_arg, void *tcb, size if (*stack) { *stack_base = *stack; } else { - *stack_base = mmap(nullptr, *stack_size, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if(*stack_base == MAP_FAILED) { + *stack_base = + mmap(nullptr, *stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (*stack_base == MAP_FAILED) { return errno; } } - - uintptr_t *sp = reinterpret_cast(reinterpret_cast(*stack_base) + *stack_size); + + uintptr_t *sp = + reinterpret_cast(reinterpret_cast(*stack_base) + *stack_size); *--sp = reinterpret_cast(tcb); *--sp = reinterpret_cast(user_arg); *--sp = reinterpret_cast(entry); - *stack = reinterpret_cast(sp); + *stack = reinterpret_cast(sp); return 0; } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/drm.cpp b/sysdeps/managarm/generic/drm.cpp index 805c366b7b..f4025597a5 100644 --- a/sysdeps/managarm/generic/drm.cpp +++ b/sysdeps/managarm/generic/drm.cpp @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -14,19 +14,20 @@ namespace mlibc { int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle handle) { managarm::fs::IoctlRequest ioctl_req(getSysdepsAllocator()); - switch(request) { + switch (request) { case DRM_IOCTL_VERSION: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -41,15 +42,24 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h param->version_minor = resp.drm_version_minor(); param->version_patchlevel = resp.drm_version_patchlevel(); - if(param->name) - memcpy(param->name, resp.drm_driver_name().data(), frg::min(param->name_len, - resp.drm_driver_name().size())); - if(param->date) - memcpy(param->date, resp.drm_driver_date().data(), frg::min(param->date_len, - resp.drm_driver_date().size())); - if(param->desc) - memcpy(param->desc, resp.drm_driver_desc().data(), frg::min(param->desc_len, - resp.drm_driver_desc().size())); + if (param->name) + memcpy( + param->name, + resp.drm_driver_name().data(), + frg::min(param->name_len, resp.drm_driver_name().size()) + ); + if (param->date) + memcpy( + param->date, + resp.drm_driver_date().data(), + frg::min(param->date_len, resp.drm_driver_date().size()) + ); + if (param->desc) + memcpy( + param->desc, + resp.drm_driver_desc().data(), + frg::min(param->desc_len, resp.drm_driver_desc().size()) + ); param->name_len = resp.drm_driver_name().size(); param->date_len = resp.drm_driver_date().size(); @@ -59,18 +69,19 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_GET_CAP: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_drm_capability(param->capability); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -80,9 +91,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); param->value = resp.drm_value(); @@ -92,18 +103,20 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h } case DRM_IOCTL_SET_CLIENT_CAP: { auto param = reinterpret_cast(arg); - mlibc::infoLogger() << "\e[35mmlibc: DRM_IOCTL_SET_CLIENT_CAP(" << param->capability << ") ignores its value\e[39m" << frg::endlog; + mlibc::infoLogger() << "\e[35mmlibc: DRM_IOCTL_SET_CLIENT_CAP(" << param->capability + << ") ignores its value\e[39m" << frg::endlog; managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_drm_capability(param->capability); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -113,9 +126,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); param->value = resp.drm_value(); @@ -126,26 +139,29 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h case DRM_IOCTL_GET_MAGIC: { auto param = reinterpret_cast(arg); mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_GET_MAGIC is not implemented correctly\e[39m" - << frg::endlog; + << frg::endlog; param->magic = 1; *result = 0; return 0; } case DRM_IOCTL_AUTH_MAGIC: { - mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_AUTH_MAGIC is not implemented correctly\e[39m" - << frg::endlog; + mlibc::infoLogger( + ) << "\e[31mmlibc: DRM_IOCTL_AUTH_MAGIC is not implemented correctly\e[39m" + << frg::endlog; *result = 0; return 0; } case DRM_IOCTL_SET_MASTER: { - mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_SET_MASTER is not implemented correctly\e[39m" - << frg::endlog; + mlibc::infoLogger( + ) << "\e[31mmlibc: DRM_IOCTL_SET_MASTER is not implemented correctly\e[39m" + << frg::endlog; *result = 0; return 0; } case DRM_IOCTL_DROP_MASTER: { - mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_DROP_MASTER is not implemented correctly\e[39m" - << frg::endlog; + mlibc::infoLogger( + ) << "\e[31mmlibc: DRM_IOCTL_DROP_MASTER is not implemented correctly\e[39m" + << frg::endlog; *result = 0; return 0; } @@ -156,18 +172,19 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_command(request); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); - if(recv_resp.error() == kHelErrDismissed) { + if (recv_resp.error() == kHelErrDismissed) { return EINVAL; } @@ -176,33 +193,33 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - for(size_t i = 0; i < resp.drm_fb_ids_size(); i++) { - if(i >= param->count_fbs) - break; + for (size_t i = 0; i < resp.drm_fb_ids_size(); i++) { + if (i >= param->count_fbs) + break; auto dest = reinterpret_cast(param->fb_id_ptr); dest[i] = resp.drm_fb_ids(i); } param->count_fbs = resp.drm_fb_ids_size(); - for(size_t i = 0; i < resp.drm_crtc_ids_size(); i++) { - if(i >= param->count_crtcs) - break; + for (size_t i = 0; i < resp.drm_crtc_ids_size(); i++) { + if (i >= param->count_crtcs) + break; auto dest = reinterpret_cast(param->crtc_id_ptr); dest[i] = resp.drm_crtc_ids(i); } param->count_crtcs = resp.drm_crtc_ids_size(); - for(size_t i = 0; i < resp.drm_connector_ids_size(); i++) { - if(i >= param->count_connectors) - break; + for (size_t i = 0; i < resp.drm_connector_ids_size(); i++) { + if (i >= param->count_connectors) + break; auto dest = reinterpret_cast(param->connector_id_ptr); dest[i] = resp.drm_connector_ids(i); } param->count_connectors = resp.drm_connector_ids_size(); - for(size_t i = 0; i < resp.drm_encoder_ids_size(); i++) { - if(i >= param->count_encoders) - continue; + for (size_t i = 0; i < resp.drm_encoder_ids_size(); i++) { + if (i >= param->count_encoders) + continue; auto dest = reinterpret_cast(param->encoder_id_ptr); dest[i] = resp.drm_encoder_ids(i); } @@ -217,7 +234,7 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_GETCONNECTOR: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); @@ -225,19 +242,22 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_max_modes(param->count_modes); auto [offer, send_ioctl_req, send_req, recv_resp, recv_list] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(reinterpret_cast(param->modes_ptr), param->count_modes * sizeof(drm_mode_modeinfo)) - ) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer( + reinterpret_cast(param->modes_ptr), + param->count_modes * sizeof(drm_mode_modeinfo) + ) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); HEL_CHECK(send_req.error()); - if(recv_resp.error() == kHelErrDismissed) + if (recv_resp.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(recv_resp.error()); @@ -247,9 +267,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h resp.ParseFromArray(recv_resp.data(), recv_resp.length()); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - for(size_t i = 0; i < resp.drm_encoders_size(); i++) { - if(i >= param->count_encoders) - continue; + for (size_t i = 0; i < resp.drm_encoders_size(); i++) { + if (i >= param->count_encoders) + continue; auto dest = reinterpret_cast(param->encoders_ptr); dest[i] = resp.drm_encoders(i); } @@ -265,11 +285,15 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h param->count_encoders = resp.drm_encoders_size(); param->count_modes = resp.drm_num_modes(); - if(param->props_ptr) { + if (param->props_ptr) { auto id_ptr = reinterpret_cast(param->props_ptr); auto val_ptr = reinterpret_cast(param->prop_values_ptr); - for(size_t i = 0; i < frg::min(static_cast(param->count_props), resp.drm_obj_property_ids_size()); i++) { + for (size_t i = 0; + i < frg::min( + static_cast(param->count_props), resp.drm_obj_property_ids_size() + ); + i++) { id_ptr[i] = resp.drm_obj_property_ids(i); val_ptr[i] = resp.drm_obj_property_values(i); } @@ -281,18 +305,19 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_GETPROPERTY: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_drm_property_id(param->prop_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -302,9 +327,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() != managarm::fs::Errors::SUCCESS) { - mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_MODE_GETPROPERTY(" << param->prop_id << ") error " << (int) resp.error() << "\e[39m" - << frg::endlog; + if (resp.error() != managarm::fs::Errors::SUCCESS) { + mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_MODE_GETPROPERTY(" << param->prop_id + << ") error " << (int)resp.error() << "\e[39m" << frg::endlog; *result = 0; return EINVAL; } @@ -313,14 +338,18 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h param->count_values = resp.drm_property_vals_size(); param->flags = resp.drm_property_flags(); - for(size_t i = 0; i < param->count_values && i < resp.drm_property_vals_size() && param->values_ptr; i++) { + for (size_t i = 0; + i < param->count_values && i < resp.drm_property_vals_size() && param->values_ptr; + i++) { auto dest = reinterpret_cast(param->values_ptr); dest[i] = resp.drm_property_vals(i); } __ensure(resp.drm_enum_name_size() == resp.drm_enum_value_size()); - for(size_t i = 0; i < param->count_enum_blobs && i < resp.drm_enum_name_size() && i < resp.drm_enum_value_size(); i++) { + for (size_t i = 0; i < param->count_enum_blobs && i < resp.drm_enum_name_size() && + i < resp.drm_enum_value_size(); + i++) { auto dest = reinterpret_cast(param->enum_blob_ptr); dest[i].value = resp.drm_enum_value(i); strncpy(dest[i].name, resp.drm_enum_name(i).data(), DRM_PROP_NAME_LEN); @@ -341,11 +370,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_obj_id(param->connector_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -355,9 +385,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() != managarm::fs::Errors::SUCCESS) { - mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_MODE_SETPROPERTY(" << param->prop_id << ") error " << (int) resp.error() << "\e[39m" - << frg::endlog; + if (resp.error() != managarm::fs::Errors::SUCCESS) { + mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_MODE_SETPROPERTY(" << param->prop_id + << ") error " << (int)resp.error() << "\e[39m" << frg::endlog; *result = 0; return EINVAL; } @@ -373,11 +403,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_blob_id(param->blob_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -387,16 +418,16 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() != managarm::fs::Errors::SUCCESS) { - mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_MODE_GETPROPBLOB(" << param->blob_id << ") error " << (int) resp.error() << "\e[39m" - << frg::endlog; + if (resp.error() != managarm::fs::Errors::SUCCESS) { + mlibc::infoLogger() << "\e[31mmlibc: DRM_IOCTL_MODE_GETPROPBLOB(" << param->blob_id + << ") error " << (int)resp.error() << "\e[39m" << frg::endlog; *result = 0; return EINVAL; } uint8_t *dest = reinterpret_cast(param->data); - for(size_t i = 0; i < resp.drm_property_blob_size(); i++) { - if(i >= param->length) { + for (size_t i = 0; i < resp.drm_property_blob_size(); i++) { + if (i >= param->length) { continue; } @@ -409,18 +440,19 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_GETPLANE: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_drm_plane_id(param->plane_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -437,8 +469,8 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h param->gamma_size = resp.drm_gamma_size(); // FIXME: this should be passed as a buffer with helix, but this has no bounded max size? - for(size_t i = 0; i < resp.drm_format_type_size(); i++) { - if(i >= param->count_format_types) { + for (size_t i = 0; i < resp.drm_format_type_size(); i++) { + if (i >= param->count_format_types) { break; } auto dest = reinterpret_cast(param->format_type_ptr); @@ -460,11 +492,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.SerializeToString(&ser); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -476,8 +509,8 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h __ensure(resp.error() == managarm::fs::Errors::SUCCESS); // FIXME: send this via a helix_ng buffer - for(size_t i = 0; i < resp.drm_plane_res_size(); i++) { - if(i >= param->count_planes) { + for (size_t i = 0; i < resp.drm_plane_res_size(); i++) { + if (i >= param->count_planes) { continue; } auto dest = reinterpret_cast(param->plane_id_ptr); @@ -491,18 +524,19 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_GETENCODER: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_drm_encoder_id(param->encoder_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -522,7 +556,7 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_CREATE_DUMB: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); @@ -533,11 +567,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_flags(param->flags); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -569,11 +604,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_handle(param->handle); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -597,11 +633,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_fb_id(param->fb_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -616,9 +653,15 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h param->height = resp.drm_height(); param->pixel_format = resp.pixel_format(); param->modifier[0] = resp.modifier(); - memcpy(param->handles, resp.drm_handles().data(), sizeof(uint32_t) * resp.drm_handles_size()); - memcpy(param->pitches, resp.drm_pitches().data(), sizeof(uint32_t) * resp.drm_pitches_size()); - memcpy(param->offsets, resp.drm_offsets().data(), sizeof(uint32_t) * resp.drm_offsets_size()); + memcpy( + param->handles, resp.drm_handles().data(), sizeof(uint32_t) * resp.drm_handles_size() + ); + memcpy( + param->pitches, resp.drm_pitches().data(), sizeof(uint32_t) * resp.drm_pitches_size() + ); + memcpy( + param->offsets, resp.drm_offsets().data(), sizeof(uint32_t) * resp.drm_offsets_size() + ); *result = resp.result(); return 0; @@ -640,11 +683,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_handle(param->handles[0]); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -669,11 +713,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_fb_id(*param); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -688,7 +733,7 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_MAP_DUMB: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); @@ -696,11 +741,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_handle(param->handle); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -717,19 +763,20 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_GETCRTC: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_drm_crtc_id(param->crtc_id); auto [offer, send_ioctl_req, send_req, recv_resp, recv_data] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(¶m->mode, sizeof(drm_mode_modeinfo))) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(¶m->mode, sizeof(drm_mode_modeinfo)) + ) ); HEL_CHECK(offer.error()); @@ -752,12 +799,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_SETCRTC: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); - for(size_t i = 0; i < param->count_connectors; i++) { + for (size_t i = 0; i < param->count_connectors; i++) { auto dest = reinterpret_cast(param->set_connectors_ptr); req.add_drm_connector_ids(dest[i]); } @@ -768,12 +815,13 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_mode_valid(param->mode_valid); auto [offer, send_ioctl_req, send_req, send_mode, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::sendBuffer(¶m->mode, sizeof(drm_mode_modeinfo)), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::sendBuffer(¶m->mode, sizeof(drm_mode_modeinfo)), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -800,11 +848,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_obj_type(param->obj_type); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -818,8 +867,8 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h auto props = reinterpret_cast(param->props_ptr); auto prop_vals = reinterpret_cast(param->prop_values_ptr); - for(size_t i = 0; i < resp.drm_obj_property_ids_size(); i++) { - if(i >= param->count_props) { + for (size_t i = 0; i < resp.drm_obj_property_ids_size(); i++) { + if (i >= param->count_props) { break; } props[i] = resp.drm_obj_property_ids(i); @@ -843,11 +892,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_cookie(param->user_data); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -862,7 +912,7 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h return 0; } case DRM_IOCTL_MODE_DIRTYFB: { - auto param = reinterpret_cast(arg); + auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); @@ -870,7 +920,7 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_fb_id(param->fb_id); req.set_drm_flags(param->flags); req.set_drm_color(param->color); - for(size_t i = 0; i < param->num_clips; i++) { + for (size_t i = 0; i < param->num_clips; i++) { auto dest = reinterpret_cast(param->clips_ptr); managarm::fs::Rect clip(getSysdepsAllocator()); clip.set_x1(dest->x1); @@ -881,11 +931,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h } auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -895,9 +946,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = resp.result(); return 0; @@ -920,16 +971,18 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_height(param->height); req.set_drm_handle(param->handle); } else { - mlibc::infoLogger() << "\e[35mmlibc: invalid flags in DRM_IOCTL_MODE_CURSOR\e[39m" << frg::endlog; + mlibc::infoLogger() << "\e[35mmlibc: invalid flags in DRM_IOCTL_MODE_CURSOR\e[39m" + << frg::endlog; return EINVAL; } auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -941,9 +994,9 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h if (resp.error() == managarm::fs::Errors::NO_BACKING_DEVICE) { return ENXIO; - }else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else{ + } else { *result = resp.result(); return 0; } @@ -957,11 +1010,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_handle(param->handle); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -982,12 +1036,13 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_blob_size(param->length); auto [offer, send_ioctl_req, send_req, blob_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::sendBuffer(reinterpret_cast(param->data), param->length), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::sendBuffer(reinterpret_cast(param->data), param->length), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -1012,11 +1067,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_blob_id(param->blob_id); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -1044,14 +1100,14 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h auto props_ptr = reinterpret_cast(param->props_ptr); auto prop_values_ptr = reinterpret_cast(param->prop_values_ptr); - for(size_t i = 0; i < param->count_objs; i++) { + for (size_t i = 0; i < param->count_objs; i++) { /* list of modeobjs and their property count */ req.add_drm_obj_ids(objs_ptr[i]); req.add_drm_prop_counts(count_props_ptr[i]); prop_count += count_props_ptr[i]; } - for(size_t i = 0; i < prop_count; i++) { + for (size_t i = 0; i < prop_count; i++) { /* array of property IDs */ req.add_drm_props(props_ptr[i]); /* array of property values */ @@ -1059,11 +1115,12 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h } auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -1078,19 +1135,22 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h } case DRM_IOCTL_MODE_LIST_LESSEES: { mlibc::infoLogger() << "\e[35mmlibc: DRM_IOCTL_MODE_LIST_LESSEES" - " is not implemented correctly\e[39m" << frg::endlog; + " is not implemented correctly\e[39m" + << frg::endlog; return EINVAL; } case DRM_IOCTL_MODE_SETGAMMA: { mlibc::infoLogger() << "\e[35mmlibc: DRM_IOCTL_MODE_SETGAMMA" - " is not implemented correctly\e[39m" << frg::endlog; + " is not implemented correctly\e[39m" + << frg::endlog; return 0; } case DRM_IOCTL_MODE_CREATE_LEASE: { auto param = reinterpret_cast(arg); mlibc::infoLogger() << "\e[35mmlibc: DRM_IOCTL_MODE_CREATE_LEASE" - " is a noop\e[39m" << frg::endlog; + " is a noop\e[39m" + << frg::endlog; param->lessee_id = 1; param->fd = fd; *result = 0; @@ -1098,7 +1158,8 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h } case DRM_IOCTL_GEM_CLOSE: { mlibc::infoLogger() << "\e[35mmlibc: DRM_IOCTL_GEM_CLOSE" - " is a noop\e[39m" << frg::endlog; + " is a noop\e[39m" + << frg::endlog; return 0; } case DRM_IOCTL_PRIME_HANDLE_TO_FD: { @@ -1110,12 +1171,13 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_flags(param->flags); auto [offer, send_ioctl_req, send_req, send_creds, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -1139,12 +1201,13 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h req.set_drm_flags(param->flags); auto [offer, send_ioctl_req, send_req, send_creds, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(getHandleForFd(param->fd)), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(getHandleForFd(param->fd)), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); @@ -1154,7 +1217,7 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::fs::Errors::FILE_NOT_FOUND) { return EBADF; } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -1167,10 +1230,10 @@ int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle h } mlibc::infoLogger() << "mlibc: Unexpected DRM ioctl with" - << ", number: 0x" << frg::hex_fmt(_IOC_NR(request)) - << " (raw request: " << frg::hex_fmt(request) << ")" << frg::endlog; + << ", number: 0x" << frg::hex_fmt(_IOC_NR(request)) + << " (raw request: " << frg::hex_fmt(request) << ")" << frg::endlog; __ensure(!"Illegal ioctl request"); __builtin_unreachable(); } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/ensure.cpp b/sysdeps/managarm/generic/ensure.cpp index c9ba35d411..79316e0290 100644 --- a/sysdeps/managarm/generic/ensure.cpp +++ b/sysdeps/managarm/generic/ensure.cpp @@ -1,38 +1,37 @@ +#include #include #include -#include #include -#include #include +#include -#include #include +#include -void __frigg_assert_fail(const char *assertion, const char *file, unsigned int line, - const char *function) { - mlibc::panicLogger() << "In function " << function - << ", file " << file << ":" << line << "\n" - << "__ensure(" << assertion << ") failed" << frg::endlog; +void __frigg_assert_fail( + const char *assertion, const char *file, unsigned int line, const char *function +) { + mlibc::panicLogger() << "In function " << function << ", file " << file << ":" << line << "\n" + << "__ensure(" << assertion << ") failed" << frg::endlog; } namespace mlibc { - void sys_libc_log(const char *message) { - // This implementation is inherently signal-safe. - size_t n = 0; - while(message[n]) - n++; - HEL_CHECK(helLog(kHelLogSeverityInfo, message, n)); - } - - void sys_libc_panic() { - // This implementation is inherently signal-safe. - const char *message = "mlibc: Panic!"; - size_t n = 0; - while(message[n]) - n++; - helPanic(message, n); - } +void sys_libc_log(const char *message) { + // This implementation is inherently signal-safe. + size_t n = 0; + while (message[n]) + n++; + HEL_CHECK(helLog(kHelLogSeverityInfo, message, n)); } +void sys_libc_panic() { + // This implementation is inherently signal-safe. + const char *message = "mlibc: Panic!"; + size_t n = 0; + while (message[n]) + n++; + helPanic(message, n); +} +} // namespace mlibc diff --git a/sysdeps/managarm/generic/entry.cpp b/sysdeps/managarm/generic/entry.cpp index 3ff28d2cb3..6fdda27fa1 100644 --- a/sysdeps/managarm/generic/entry.cpp +++ b/sysdeps/managarm/generic/entry.cpp @@ -5,11 +5,11 @@ #include #include +#include #include #include -#include -#include #include +#include #include #include @@ -28,49 +28,51 @@ thread_local HelHandle __mlibc_posix_lane; thread_local void *__mlibc_clk_tracker_page; namespace { - thread_local unsigned __mlibc_gsf_nesting; - thread_local void *__mlibc_cached_thread_page; - thread_local HelHandle *cachedFileTable; - - // This construction is a bit weird: Even though the variables above - // are thread_local we still protect their initialization with a pthread_once_t - // (instead of using a C++ constructor). - // We do this in order to able to clear the pthread_once_t after a fork. - thread_local pthread_once_t has_cached_infos = PTHREAD_ONCE_INIT; - - void actuallyCacheInfos() { - posix::ManagarmProcessData data; - HEL_CHECK(helSyscall1(kHelCallSuper + posix::superGetProcessData, reinterpret_cast(&data))); - - __mlibc_posix_lane = data.posixLane; - __mlibc_cached_thread_page = data.threadPage; - cachedFileTable = data.fileTable; - __mlibc_clk_tracker_page = data.clockTrackerPage; - } +thread_local unsigned __mlibc_gsf_nesting; +thread_local void *__mlibc_cached_thread_page; +thread_local HelHandle *cachedFileTable; + +// This construction is a bit weird: Even though the variables above +// are thread_local we still protect their initialization with a pthread_once_t +// (instead of using a C++ constructor). +// We do this in order to able to clear the pthread_once_t after a fork. +thread_local pthread_once_t has_cached_infos = PTHREAD_ONCE_INIT; + +void actuallyCacheInfos() { + posix::ManagarmProcessData data; + HEL_CHECK( + helSyscall1(kHelCallSuper + posix::superGetProcessData, reinterpret_cast(&data)) + ); + + __mlibc_posix_lane = data.posixLane; + __mlibc_cached_thread_page = data.threadPage; + cachedFileTable = data.fileTable; + __mlibc_clk_tracker_page = data.clockTrackerPage; } +} // namespace SignalGuard::SignalGuard() { pthread_once(&has_cached_infos, &actuallyCacheInfos); - if(!__mlibc_cached_thread_page) + if (!__mlibc_cached_thread_page) return; auto p = reinterpret_cast(__mlibc_cached_thread_page); - if(!__mlibc_gsf_nesting) + if (!__mlibc_gsf_nesting) __atomic_store_n(p, 1, __ATOMIC_RELAXED); __mlibc_gsf_nesting++; } SignalGuard::~SignalGuard() { pthread_once(&has_cached_infos, &actuallyCacheInfos); - if(!__mlibc_cached_thread_page) + if (!__mlibc_cached_thread_page) return; auto p = reinterpret_cast(__mlibc_cached_thread_page); __ensure(__mlibc_gsf_nesting > 0); __mlibc_gsf_nesting--; - if(!__mlibc_gsf_nesting) { + if (!__mlibc_gsf_nesting) { unsigned int result = __atomic_exchange_n(p, 0, __ATOMIC_RELAXED); - if(result == 2) { + if (result == 2) { HEL_CHECK(helSyscall0(kHelCallSuper + posix::superSigRaise)); - }else{ + } else { __ensure(result == 1); } } @@ -103,9 +105,7 @@ HelHandle getHandleForFd(int fd) { return cacheFileTable()[fd]; } -void clearCachedInfos() { - has_cached_infos = PTHREAD_ONCE_INIT; -} +void clearCachedInfos() { has_cached_infos = PTHREAD_ONCE_INIT; } struct LibraryGuard { LibraryGuard(); @@ -121,11 +121,13 @@ LibraryGuard::LibraryGuard() { // Parse the exec() stack. mlibc::parse_exec_stack(__dlapi_entrystack(), &__mlibc_stack_data); - mlibc::set_startup_data(__mlibc_stack_data.argc, __mlibc_stack_data.argv, - __mlibc_stack_data.envp); + mlibc::set_startup_data( + __mlibc_stack_data.argc, __mlibc_stack_data.argv, __mlibc_stack_data.envp + ); } -extern "C" void __mlibc_entry(uintptr_t *entry_stack, int (*main_fn)(int argc, char *argv[], char *env[])) { +extern "C" void +__mlibc_entry(uintptr_t *entry_stack, int (*main_fn)(int argc, char *argv[], char *env[])) { __dlapi_enter(entry_stack); auto result = main_fn(__mlibc_stack_data.argc, __mlibc_stack_data.argv, environ); exit(result); diff --git a/sysdeps/managarm/generic/file.cpp b/sysdeps/managarm/generic/file.cpp index e920f9c99a..16949206a3 100644 --- a/sysdeps/managarm/generic/file.cpp +++ b/sysdeps/managarm/generic/file.cpp @@ -31,11 +31,11 @@ int sys_chdir(const char *path) { req.set_request_type(managarm::posix::CntReqType::CHDIR); req.set_path(frg::string(getSysdepsAllocator(), path)); - auto [offer, send_req, recv_resp] = exchangeMsgsSync(getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_req, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -44,9 +44,9 @@ int sys_chdir(const char *path) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -60,10 +60,10 @@ int sys_fchdir(int fd) { req.set_fd(fd); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -84,10 +84,10 @@ int sys_chroot(const char *path) { req.set_path(frg::string(getSysdepsAllocator(), path)); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -100,9 +100,7 @@ int sys_chroot(const char *path) { return 0; } -int sys_mkdir(const char *path, mode_t mode) { - return sys_mkdirat(AT_FDCWD, path, mode); -} +int sys_mkdir(const char *path, mode_t mode) { return sys_mkdirat(AT_FDCWD, path, mode); } int sys_mkdirat(int dirfd, const char *path, mode_t mode) { (void)mode; @@ -112,14 +110,12 @@ int sys_mkdirat(int dirfd, const char *path, mode_t mode) { req.set_fd(dirfd); req.set_path(frg::string(getSysdepsAllocator(), path)); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -128,17 +124,17 @@ int sys_mkdirat(int dirfd, const char *path, mode_t mode) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - } else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + } else if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { return ENOTDIR; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -156,14 +152,12 @@ int sys_symlinkat(const char *target_path, int dirfd, const char *link_path) { req.set_path(frg::string(getSysdepsAllocator(), link_path)); req.set_target_path(frg::string(getSysdepsAllocator(), target_path)); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -172,17 +166,17 @@ int sys_symlinkat(const char *target_path, int dirfd, const char *link_path) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { return ENOTDIR; - }else if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + } else if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -202,14 +196,12 @@ int sys_linkat(int olddirfd, const char *old_path, int newdirfd, const char *new req.set_newfd(newdirfd); req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -218,13 +210,13 @@ int sys_linkat(int olddirfd, const char *old_path, int newdirfd, const char *new managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -243,14 +235,12 @@ int sys_renameat(int olddirfd, const char *old_path, int newdirfd, const char *n req.set_fd(olddirfd); req.set_newfd(newdirfd); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -259,42 +249,42 @@ int sys_renameat(int olddirfd, const char *old_path, int newdirfd, const char *n managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } } -} //namespace mlibc +} // namespace mlibc namespace mlibc { int sys_fcntl(int fd, int request, va_list args, int *result) { SignalGuard sguard; - if(request == F_DUPFD) { + if (request == F_DUPFD) { int newfd; - if(int e = sys_dup(fd, 0, &newfd); e) + if (int e = sys_dup(fd, 0, &newfd); e) return e; *result = newfd; return 0; - }else if(request == F_DUPFD_CLOEXEC) { + } else if (request == F_DUPFD_CLOEXEC) { int newfd; - if(int e = sys_dup(fd, O_CLOEXEC, &newfd); e) + if (int e = sys_dup(fd, O_CLOEXEC, &newfd); e) return e; *result = newfd; return 0; - }else if(request == F_GETFD) { + } else if (request == F_GETFD) { managarm::posix::CntRequest req(getSysdepsAllocator()); req.set_request_type(managarm::posix::CntReqType::FD_GET_FLAGS); req.set_fd(fd); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -302,22 +292,22 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) + if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) return EBADF; __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *result = resp.flags(); return 0; - }else if(request == F_SETFD) { + } else if (request == F_SETFD) { managarm::posix::CntRequest req(getSysdepsAllocator()); req.set_request_type(managarm::posix::CntReqType::FD_SET_FLAGS); req.set_fd(fd); req.set_flags(va_arg(args, int)); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -325,14 +315,14 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) + if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) return EBADF; - else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) + else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) return EINVAL; __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *result = static_cast(resp.error()); return 0; - }else if(request == F_GETFL) { + } else if (request == F_GETFL) { SignalGuard sguard; auto handle = getHandleForFd(fd); @@ -344,10 +334,10 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { req.set_fd(fd); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -355,14 +345,15 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { - mlibc::infoLogger() << "\e[31mmlibc: fcntl(F_GETFL) unimplemented for this file\e[39m" << frg::endlog; + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + mlibc::infoLogger() << "\e[31mmlibc: fcntl(F_GETFL) unimplemented for this file\e[39m" + << frg::endlog; return EINVAL; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = resp.flags(); return 0; - }else if(request == F_SETFL) { + } else if (request == F_SETFL) { SignalGuard sguard; auto handle = getHandleForFd(fd); @@ -375,10 +366,10 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { req.set_flags(va_arg(args, int)); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -386,25 +377,26 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { - mlibc::infoLogger() << "\e[31mmlibc: fcntl(F_SETFL) unimplemented for this file\e[39m" << frg::endlog; + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + mlibc::infoLogger() << "\e[31mmlibc: fcntl(F_SETFL) unimplemented for this file\e[39m" + << frg::endlog; return EINVAL; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = 0; return 0; - }else if(request == F_SETLK) { + } else if (request == F_SETLK) { mlibc::infoLogger() << "\e[31mmlibc: F_SETLK\e[39m" << frg::endlog; return 0; - }else if(request == F_SETLKW) { + } else if (request == F_SETLKW) { mlibc::infoLogger() << "\e[31mmlibc: F_SETLKW\e[39m" << frg::endlog; return 0; - }else if(request == F_GETLK) { + } else if (request == F_GETLK) { struct flock *lock = va_arg(args, struct flock *); lock->l_type = F_UNLCK; mlibc::infoLogger() << "\e[31mmlibc: F_GETLK is stubbed!\e[39m" << frg::endlog; return 0; - }else if(request == F_ADD_SEALS) { + } else if (request == F_ADD_SEALS) { auto seals = va_arg(args, int); auto handle = getHandleForFd(fd); if (!handle) @@ -415,11 +407,12 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { req.set_fd(fd); req.set_seals(seals); - auto [offer, send_req, recv_resp] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::RecvInline() - )); + auto [offer, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::RecvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -427,17 +420,19 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { - mlibc::infoLogger() << "\e[31mmlibc: fcntl(F_ADD_SEALS) unimplemented for this file\e[39m" << frg::endlog; + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + mlibc::infoLogger( + ) << "\e[31mmlibc: fcntl(F_ADD_SEALS) unimplemented for this file\e[39m" + << frg::endlog; return EINVAL; - } else if(resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { + } else if (resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { return EPERM; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = resp.seals(); return 0; - }else if(request == F_GET_SEALS) { + } else if (request == F_GET_SEALS) { auto handle = getHandleForFd(fd); if (!handle) return EBADF; @@ -446,11 +441,12 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { req.set_req_type(managarm::fs::CntReqType::PT_GET_SEALS); req.set_fd(fd); - auto [offer, send_req, recv_resp] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::RecvInline() - )); + auto [offer, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::RecvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -458,23 +454,23 @@ int sys_fcntl(int fd, int request, va_list args, int *result) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { - mlibc::infoLogger() << "\e[31mmlibc: fcntl(F_GET_SEALS) unimplemented for this file\e[39m" << frg::endlog; + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + mlibc::infoLogger( + ) << "\e[31mmlibc: fcntl(F_GET_SEALS) unimplemented for this file\e[39m" + << frg::endlog; return EINVAL; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = resp.seals(); return 0; - }else{ - mlibc::infoLogger() << "\e[31mmlibc: Unexpected fcntl() request: " - << request << "\e[39m" << frg::endlog; + } else { + mlibc::infoLogger() << "\e[31mmlibc: Unexpected fcntl() request: " << request << "\e[39m" + << frg::endlog; return EINVAL; } } -int sys_open_dir(const char *path, int *handle) { - return sys_open(path, 0, 0, handle); -} +int sys_open_dir(const char *path, int *handle) { return sys_open(path, 0, 0, handle); } int sys_read_entries(int fd, void *buffer, size_t max_size, size_t *bytes_read) { SignalGuard sguard; @@ -486,10 +482,10 @@ int sys_read_entries(int fd, void *buffer, size_t max_size, size_t *bytes_read) req.set_req_type(managarm::fs::CntReqType::PT_READ_ENTRIES); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -497,10 +493,10 @@ int sys_read_entries(int fd, void *buffer, size_t max_size, size_t *bytes_read) managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::END_OF_FILE) { + if (resp.error() == managarm::fs::Errors::END_OF_FILE) { *bytes_read = 0; return 0; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); __ensure(max_size > sizeof(struct dirent)); auto ent = new (buffer) struct dirent; @@ -520,10 +516,10 @@ int sys_ttyname(int fd, char *buf, size_t size) { req.set_fd(fd); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -532,11 +528,11 @@ int sys_ttyname(int fd, char *buf, size_t size) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) { + if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::NOT_A_TTY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_TTY) { return ENOTTY; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); __ensure(size >= resp.path().size() + 1); memcpy(buf, resp.path().data(), size); @@ -546,8 +542,7 @@ int sys_ttyname(int fd, char *buf, size_t size) { } int sys_fdatasync(int) { - mlibc::infoLogger() << "\e[35mmlibc: fdatasync() is a no-op\e[39m" - << frg::endlog; + mlibc::infoLogger() << "\e[35mmlibc: fdatasync() is a no-op\e[39m" << frg::endlog; return 0; } @@ -559,11 +554,12 @@ int sys_getcwd(char *buffer, size_t size) { req.set_size(size); auto [offer, send_req, recv_resp, recv_path] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(buffer, size)) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(buffer, size) + ) ); HEL_CHECK(offer.error()); @@ -574,7 +570,7 @@ int sys_getcwd(char *buffer, size_t size) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); __ensure(resp.error() == managarm::posix::Errors::SUCCESS); - if(static_cast(resp.size()) >= size) + if (static_cast(resp.size()) >= size) return ERANGE; return 0; } @@ -591,11 +587,10 @@ int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offse req.set_rel_offset(offset); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -604,13 +599,13 @@ int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offse managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - }else if(resp.error() == managarm::posix::Errors::NO_MEMORY) { + } else if (resp.error() == managarm::posix::Errors::NO_MEMORY) { return EFAULT; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else { + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *window = reinterpret_cast(resp.offset()); } @@ -628,10 +623,10 @@ int sys_vm_remap(void *pointer, size_t size, size_t new_size, void **window) { req.set_new_size(new_size); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -655,10 +650,10 @@ int sys_vm_protect(void *pointer, size_t size, int prot) { req.set_mode(prot); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -680,10 +675,10 @@ int sys_vm_unmap(void *pointer, size_t size) { req.set_size(size); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -703,10 +698,10 @@ int sys_setsid(pid_t *sid) { req.set_request_type(managarm::posix::CntReqType::SETSID); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -715,7 +710,7 @@ int sys_setsid(pid_t *sid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ACCESS_DENIED) { + if (resp.error() == managarm::posix::Errors::ACCESS_DENIED) { *sid = -1; return EPERM; } @@ -726,16 +721,16 @@ int sys_setsid(pid_t *sid) { int sys_tcgetattr(int fd, struct termios *attr) { int result; - if(int e = sys_ioctl(fd, TCGETS, attr, &result); e) + if (int e = sys_ioctl(fd, TCGETS, attr, &result); e) return e; return 0; } int sys_tcsetattr(int fd, int when, const struct termios *attr) { - if(when < TCSANOW || when > TCSAFLUSH) + if (when < TCSANOW || when > TCSAFLUSH) return EINVAL; - if(int e = sys_ioctl(fd, TCSETS, const_cast(attr), nullptr); e) + if (int e = sys_ioctl(fd, TCSETS, const_cast(attr), nullptr); e) return e; return 0; } @@ -759,11 +754,10 @@ int sys_socket(int domain, int type_and_flags, int proto, int *fd) { req.set_flags(type_and_flags & flags_mask); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -772,7 +766,7 @@ int sys_socket(int domain, int type_and_flags, int proto, int *fd) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EAFNOSUPPORT; } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); @@ -789,10 +783,10 @@ int sys_pipe(int *fds, int flags) { req.set_flags(flags); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -822,11 +816,10 @@ int sys_socketpair(int domain, int type_and_flags, int proto, int *fds) { req.set_flags(type_and_flags & flags_mask); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -835,7 +828,7 @@ int sys_socketpair(int domain, int type_and_flags, int proto, int *fds) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::PROTOCOL_NOT_SUPPORTED) { + if (resp.error() == managarm::posix::Errors::PROTOCOL_NOT_SUPPORTED) { return EPROTONOSUPPORT; } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); @@ -853,10 +846,10 @@ int sys_msg_send(int sockfd, const struct msghdr *hdr, int flags, ssize_t *lengt return EBADF; size_t overall_size = 0; - for(size_t i = 0; i < hdr->msg_iovlen; i++) { + for (size_t i = 0; i < hdr->msg_iovlen; i++) { HelSgItem item{ - .buffer = hdr->msg_iov[i].iov_base, - .length = hdr->msg_iov[i].iov_len, + .buffer = hdr->msg_iov[i].iov_base, + .length = hdr->msg_iov[i].iov_len, }; sglist.push_back(item); overall_size += hdr->msg_iov[i].iov_len; @@ -870,10 +863,10 @@ int sys_msg_send(int sockfd, const struct msghdr *hdr, int flags, ssize_t *lengt req.set_has_cmsg_creds(false); req.set_has_cmsg_rights(false); - for(auto cmsg = CMSG_FIRSTHDR(hdr); cmsg; cmsg = CMSG_NXTHDR(hdr, cmsg)) { + for (auto cmsg = CMSG_FIRSTHDR(hdr); cmsg; cmsg = CMSG_NXTHDR(hdr, cmsg)) { __ensure(cmsg->cmsg_level == SOL_SOCKET); __ensure(cmsg->cmsg_len >= sizeof(struct cmsghdr)); - if(cmsg->cmsg_type == SCM_CREDENTIALS) { + if (cmsg->cmsg_type == SCM_CREDENTIALS) { req.set_has_cmsg_creds(true); size_t size = cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)); __ensure(size == sizeof(struct ucred)); @@ -882,30 +875,34 @@ int sys_msg_send(int sockfd, const struct msghdr *hdr, int flags, ssize_t *lengt req.set_creds_pid(creds.pid); req.set_creds_uid(creds.uid); req.set_creds_gid(creds.gid); - } else if(cmsg->cmsg_type == SCM_RIGHTS) { + } else if (cmsg->cmsg_type == SCM_RIGHTS) { req.set_has_cmsg_rights(true); size_t size = cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)); __ensure(!(size % sizeof(int))); - for(size_t off = 0; off < size; off += sizeof(int)) { + for (size_t off = 0; off < size; off += sizeof(int)) { int fd; memcpy(&fd, CMSG_DATA(cmsg) + off, sizeof(int)); req.add_fds(fd); } } else { - mlibc::infoLogger() << "mlibc: sys_msg_send only supports SCM_RIGHTS or SCM_CREDENTIALS, got: " << cmsg->cmsg_type << "!" << frg::endlog; + mlibc::infoLogger( + ) << "mlibc: sys_msg_send only supports SCM_RIGHTS or SCM_CREDENTIALS, got: " + << cmsg->cmsg_type << "!" << frg::endlog; return EINVAL; } } - auto [offer, send_head, send_tail, send_data, imbue_creds, send_addr, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::sendBufferSg(sglist.data(), hdr->msg_iovlen), - helix_ng::imbueCredentials(), - helix_ng::sendBuffer(hdr->msg_name, hdr->msg_namelen), - helix_ng::recvInline()) - ); + auto [offer, send_head, send_tail, send_data, imbue_creds, send_addr, recv_resp] = + exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), + helix_ng::sendBufferSg(sglist.data(), hdr->msg_iovlen), + helix_ng::imbueCredentials(), + helix_ng::sendBuffer(hdr->msg_name, hdr->msg_namelen), + helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -918,31 +915,31 @@ int sys_msg_send(int sockfd, const struct msghdr *hdr, int flags, ssize_t *lengt managarm::fs::SendMsgReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::BROKEN_PIPE) { + if (resp.error() == managarm::fs::Errors::BROKEN_PIPE) { return EPIPE; - }else if(resp.error() == managarm::fs::Errors::NOT_CONNECTED) { + } else if (resp.error() == managarm::fs::Errors::NOT_CONNECTED) { return ENOTCONN; - }else if(resp.error() == managarm::fs::Errors::WOULD_BLOCK) { + } else if (resp.error() == managarm::fs::Errors::WOULD_BLOCK) { return EAGAIN; - }else if(resp.error() == managarm::fs::Errors::HOST_UNREACHABLE) { + } else if (resp.error() == managarm::fs::Errors::HOST_UNREACHABLE) { return EHOSTUNREACH; - }else if(resp.error() == managarm::fs::Errors::ACCESS_DENIED) { + } else if (resp.error() == managarm::fs::Errors::ACCESS_DENIED) { return EACCES; - }else if(resp.error() == managarm::fs::Errors::NETWORK_UNREACHABLE) { + } else if (resp.error() == managarm::fs::Errors::NETWORK_UNREACHABLE) { return ENETUNREACH; - }else if(resp.error() == managarm::fs::Errors::DESTINATION_ADDRESS_REQUIRED) { + } else if (resp.error() == managarm::fs::Errors::DESTINATION_ADDRESS_REQUIRED) { return EDESTADDRREQ; - }else if(resp.error() == managarm::fs::Errors::ADDRESS_NOT_AVAILABLE) { + } else if (resp.error() == managarm::fs::Errors::ADDRESS_NOT_AVAILABLE) { return EADDRNOTAVAIL; - }else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else if(resp.error() == managarm::fs::Errors::AF_NOT_SUPPORTED) { + } else if (resp.error() == managarm::fs::Errors::AF_NOT_SUPPORTED) { return EAFNOSUPPORT; - }else if(resp.error() == managarm::fs::Errors::MESSAGE_TOO_LARGE) { + } else if (resp.error() == managarm::fs::Errors::MESSAGE_TOO_LARGE) { return EMSGSIZE; - }else if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return EOPNOTSUPP; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *length = resp.size(); return 0; @@ -950,7 +947,7 @@ int sys_msg_send(int sockfd, const struct msghdr *hdr, int flags, ssize_t *lengt } int sys_msg_recv(int sockfd, struct msghdr *hdr, int flags, ssize_t *length) { - if(!hdr->msg_iovlen) { + if (!hdr->msg_iovlen) { return EMSGSIZE; } @@ -966,16 +963,18 @@ int sys_msg_recv(int sockfd, struct msghdr *hdr, int flags, ssize_t *length) { req.set_addr_size(hdr->msg_namelen); req.set_ctrl_size(hdr->msg_controllen); - auto [offer, send_req, imbue_creds, recv_resp, recv_addr, recv_data, recv_ctrl] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::recvInline(), - helix_ng::recvBuffer(hdr->msg_name, hdr->msg_namelen), - helix_ng::recvBuffer(hdr->msg_iov[0].iov_base, hdr->msg_iov[0].iov_len), - helix_ng::recvBuffer(hdr->msg_control, hdr->msg_controllen)) - ); + auto [offer, send_req, imbue_creds, recv_resp, recv_addr, recv_data, recv_ctrl] = + exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::recvInline(), + helix_ng::recvBuffer(hdr->msg_name, hdr->msg_namelen), + helix_ng::recvBuffer(hdr->msg_iov[0].iov_base, hdr->msg_iov[0].iov_len), + helix_ng::recvBuffer(hdr->msg_control, hdr->msg_controllen) + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -985,9 +984,9 @@ int sys_msg_recv(int sockfd, struct msghdr *hdr, int flags, ssize_t *length) { managarm::fs::RecvMsgReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::WOULD_BLOCK) { + if (resp.error() == managarm::fs::Errors::WOULD_BLOCK) { return EAGAIN; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); HEL_CHECK(recv_addr.error()); HEL_CHECK(recv_data.error()); @@ -1001,37 +1000,44 @@ int sys_msg_recv(int sockfd, struct msghdr *hdr, int flags, ssize_t *length) { } } -int sys_pselect(int, fd_set *read_set, fd_set *write_set, - fd_set *except_set, const struct timespec *timeout, - const sigset_t *sigmask, int *num_events) { +int sys_pselect( + int, + fd_set *read_set, + fd_set *write_set, + fd_set *except_set, + const struct timespec *timeout, + const sigset_t *sigmask, + int *num_events +) { // TODO: Do not keep errors from epoll (?). int fd = epoll_create1(0); - if(fd == -1) + if (fd == -1) return -1; - for(int k = 0; k < FD_SETSIZE; k++) { + for (int k = 0; k < FD_SETSIZE; k++) { struct epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); - if(read_set && FD_ISSET(k, read_set)) + if (read_set && FD_ISSET(k, read_set)) ev.events |= EPOLLIN; // TODO: Additional events. - if(write_set && FD_ISSET(k, write_set)) + if (write_set && FD_ISSET(k, write_set)) ev.events |= EPOLLOUT; // TODO: Additional events. - if(except_set && FD_ISSET(k, except_set)) + if (except_set && FD_ISSET(k, except_set)) ev.events |= EPOLLPRI; - if(!ev.events) + if (!ev.events) continue; ev.data.u32 = k; - if(epoll_ctl(fd, EPOLL_CTL_ADD, k, &ev)) + if (epoll_ctl(fd, EPOLL_CTL_ADD, k, &ev)) return -1; } struct epoll_event evnts[16]; - int n = epoll_pwait(fd, evnts, 16, - timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 100) : -1, sigmask); - if(n == -1) + int n = epoll_pwait( + fd, evnts, 16, timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 100) : -1, sigmask + ); + if (n == -1) return -1; fd_set res_read_set; @@ -1042,36 +1048,35 @@ int sys_pselect(int, fd_set *read_set, fd_set *write_set, FD_ZERO(&res_except_set); int m = 0; - for(int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) { int k = evnts[i].data.u32; - if(read_set && FD_ISSET(k, read_set) - && evnts[i].events & (EPOLLIN | EPOLLERR | EPOLLHUP)) { + if (read_set && FD_ISSET(k, read_set) && + evnts[i].events & (EPOLLIN | EPOLLERR | EPOLLHUP)) { FD_SET(k, &res_read_set); m++; } - if(write_set && FD_ISSET(k, write_set) - && evnts[i].events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) { + if (write_set && FD_ISSET(k, write_set) && + evnts[i].events & (EPOLLOUT | EPOLLERR | EPOLLHUP)) { FD_SET(k, &res_write_set); m++; } - if(except_set && FD_ISSET(k, except_set) - && evnts[i].events & EPOLLPRI) { + if (except_set && FD_ISSET(k, except_set) && evnts[i].events & EPOLLPRI) { FD_SET(k, &res_except_set); m++; } } - if(close(fd)) + if (close(fd)) __ensure("close() failed on epoll file"); - if(read_set) + if (read_set) memcpy(read_set, &res_read_set, sizeof(fd_set)); - if(write_set) + if (write_set) memcpy(write_set, &res_write_set, sizeof(fd_set)); - if(except_set) + if (except_set) memcpy(except_set, &res_except_set, sizeof(fd_set)); *num_events = m; @@ -1087,16 +1092,16 @@ int sys_poll(struct pollfd *fds, nfds_t count, int timeout, int *num_events) { req.set_request_type(managarm::posix::CntReqType::EPOLL_CALL); req.set_timeout(timeout > 0 ? int64_t{timeout} * 1000000 : timeout); - for(nfds_t i = 0; i < count; i++) { + for (nfds_t i = 0; i < count; i++) { req.add_fds(fds[i].fd); req.add_events(fds[i].events); } auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1105,15 +1110,15 @@ int sys_poll(struct pollfd *fds, nfds_t count, int timeout, int *num_events) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); __ensure(resp.events_size() == count); int m = 0; - for(nfds_t i = 0; i < count; i++) { - if(resp.events(i)) + for (nfds_t i = 0; i < count; i++) { + if (resp.events(i)) m++; fds[i].revents = resp.events(i); } @@ -1131,7 +1136,7 @@ int sys_epoll_create(int flags, int *fd) { SignalGuard sguard; uint32_t proto_flags = 0; - if(flags & EPOLL_CLOEXEC || flags & O_CLOEXEC) + if (flags & EPOLL_CLOEXEC || flags & O_CLOEXEC) proto_flags |= managarm::posix::OpenFlags::OF_CLOEXEC; managarm::posix::CntRequest req(getSysdepsAllocator()); @@ -1139,10 +1144,10 @@ int sys_epoll_create(int flags, int *fd) { req.set_flags(proto_flags); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1160,29 +1165,29 @@ int sys_epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) { SignalGuard sguard; managarm::posix::CntRequest req(getSysdepsAllocator()); - if(mode == EPOLL_CTL_ADD) { + if (mode == EPOLL_CTL_ADD) { __ensure(ev); req.set_request_type(managarm::posix::CntReqType::EPOLL_ADD); req.set_flags(ev->events); req.set_cookie(ev->data.u64); - }else if(mode == EPOLL_CTL_MOD) { + } else if (mode == EPOLL_CTL_MOD) { __ensure(ev); req.set_request_type(managarm::posix::CntReqType::EPOLL_MODIFY); req.set_flags(ev->events); req.set_cookie(ev->data.u64); - }else if(mode == EPOLL_CTL_DEL) { + } else if (mode == EPOLL_CTL_DEL) { req.set_request_type(managarm::posix::CntReqType::EPOLL_DELETE); - }else{ + } else { mlibc::panicLogger() << "\e[31mmlibc: Illegal epoll_ctl() mode\e[39m" << frg::endlog; } req.set_fd(epfd); req.set_newfd(fd); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1191,11 +1196,11 @@ int sys_epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::BAD_FD) { + if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - } else if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + } else if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - } else if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + } else if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); @@ -1204,8 +1209,9 @@ int sys_epoll_ctl(int epfd, int mode, int fd, struct epoll_event *ev) { return 0; } -int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, - int timeout, const sigset_t *sigmask, int *raised) { +int sys_epoll_pwait( + int epfd, struct epoll_event *ev, int n, int timeout, const sigset_t *sigmask, int *raised +) { __ensure(timeout >= 0 || timeout == -1); // TODO: Report errors correctly. SignalGuard sguard; @@ -1215,7 +1221,7 @@ int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, req.set_fd(epfd); req.set_size(n); req.set_timeout(timeout > 0 ? int64_t{timeout} * 1000000 : timeout); - if(sigmask != NULL) { + if (sigmask != NULL) { req.set_sigmask(*reinterpret_cast(sigmask)); req.set_sigmask_needed(true); } else { @@ -1223,11 +1229,12 @@ int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, } auto [offer, send_req, recv_resp, recv_data] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(ev, n * sizeof(struct epoll_event))) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(ev, n * sizeof(struct epoll_event)) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -1236,7 +1243,7 @@ int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::BAD_FD) { + if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; } __ensure(resp.error() == managarm::posix::Errors::SUCCESS); @@ -1246,7 +1253,7 @@ int sys_epoll_pwait(int epfd, struct epoll_event *ev, int n, } int sys_timerfd_create(int clockid, int flags, int *fd) { - (void) clockid; + (void)clockid; SignalGuard sguard; managarm::posix::CntRequest req(getSysdepsAllocator()); @@ -1254,10 +1261,10 @@ int sys_timerfd_create(int clockid, int flags, int *fd) { req.set_flags(flags); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1271,8 +1278,7 @@ int sys_timerfd_create(int clockid, int flags, int *fd) { return 0; } -int sys_timerfd_settime(int fd, int, - const struct itimerspec *value, struct itimerspec *oldvalue) { +int sys_timerfd_settime(int fd, int, const struct itimerspec *value, struct itimerspec *oldvalue) { __ensure(!oldvalue); SignalGuard sguard; @@ -1285,10 +1291,10 @@ int sys_timerfd_settime(int fd, int, req.set_interval_nanos(value->it_interval.tv_nsec); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1301,13 +1307,13 @@ int sys_timerfd_settime(int fd, int, return 0; } -int sys_signalfd_create(const sigset_t *masks, int flags, int *fd) { +int sys_signalfd_create(const sigset_t *masks, int flags, int *fd) { __ensure(!(flags & ~(SFD_CLOEXEC | SFD_NONBLOCK))); uint32_t proto_flags = 0; - if(flags & SFD_CLOEXEC) + if (flags & SFD_CLOEXEC) proto_flags |= managarm::posix::OpenFlags::OF_CLOEXEC; - if(flags & SFD_NONBLOCK) + if (flags & SFD_NONBLOCK) proto_flags |= managarm::posix::OpenFlags::OF_NONBLOCK; SignalGuard sguard; @@ -1318,10 +1324,10 @@ int sys_signalfd_create(const sigset_t *masks, int flags, int *fd) { req.set_sigset(*reinterpret_cast(masks)); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1336,8 +1342,10 @@ int sys_signalfd_create(const sigset_t *masks, int flags, int *fd) { } int sys_reboot(int command) { - if(command != RB_POWER_OFF && command != RB_AUTOBOOT) { - mlibc::infoLogger() << "mlibc: Anything other than power off or reboot is not supported yet!" << frg::endlog; + if (command != RB_POWER_OFF && command != RB_AUTOBOOT) { + mlibc::infoLogger( + ) << "mlibc: Anything other than power off or reboot is not supported yet!" + << frg::endlog; return EINVAL; } @@ -1347,11 +1355,10 @@ int sys_reboot(int command) { req.set_cmd(command); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1360,7 +1367,7 @@ int sys_reboot(int command) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::INSUFFICIENT_PERMISSION) + if (resp.error() == managarm::posix::Errors::INSUFFICIENT_PERMISSION) return EPERM; __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; @@ -1372,20 +1379,19 @@ int sys_inotify_create(int flags, int *fd) { SignalGuard sguard; uint32_t proto_flags = 0; - if(flags & IN_CLOEXEC) + if (flags & IN_CLOEXEC) proto_flags |= managarm::posix::OpenFlags::OF_CLOEXEC; - if(flags & IN_NONBLOCK) + if (flags & IN_NONBLOCK) proto_flags |= managarm::posix::OpenFlags::OF_NONBLOCK; managarm::posix::InotifyCreateRequest req(getSysdepsAllocator()); req.set_flags(proto_flags); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1407,14 +1413,12 @@ int sys_inotify_add_watch(int ifd, const char *path, uint32_t mask, int *wd) { req.set_path(frg::string(getSysdepsAllocator(), path)); req.set_flags(mask); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -1423,11 +1427,11 @@ int sys_inotify_add_watch(int ifd, const char *path, uint32_t mask, int *wd) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *wd = resp.wd(); return 0; @@ -1438,20 +1442,22 @@ int sys_eventfd_create(unsigned int initval, int flags, int *fd) { SignalGuard sguard; uint32_t proto_flags = 0; - if (flags & EFD_NONBLOCK) proto_flags |= managarm::posix::EventFdFlags::NONBLOCK; - if (flags & EFD_CLOEXEC) proto_flags |= managarm::posix::EventFdFlags::CLOEXEC; - if (flags & EFD_SEMAPHORE) proto_flags |= managarm::posix::EventFdFlags::SEMAPHORE; + if (flags & EFD_NONBLOCK) + proto_flags |= managarm::posix::EventFdFlags::NONBLOCK; + if (flags & EFD_CLOEXEC) + proto_flags |= managarm::posix::EventFdFlags::CLOEXEC; + if (flags & EFD_SEMAPHORE) + proto_flags |= managarm::posix::EventFdFlags::SEMAPHORE; managarm::posix::EventfdCreateRequest req(getSysdepsAllocator()); req.set_flags(proto_flags); req.set_initval(initval); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1473,33 +1479,33 @@ int sys_openat(int dirfd, const char *path, int flags, mode_t mode, int *fd) { SignalGuard sguard; // We do not support O_TMPFILE. - if(flags & O_TMPFILE) + if (flags & O_TMPFILE) return EOPNOTSUPP; uint32_t proto_flags = 0; - if(flags & O_APPEND) + if (flags & O_APPEND) proto_flags |= managarm::posix::OpenFlags::OF_APPEND; - if(flags & O_CREAT) + if (flags & O_CREAT) proto_flags |= managarm::posix::OpenFlags::OF_CREATE; - if(flags & O_EXCL) + if (flags & O_EXCL) proto_flags |= managarm::posix::OpenFlags::OF_EXCLUSIVE; - if(flags & O_NONBLOCK) + if (flags & O_NONBLOCK) proto_flags |= managarm::posix::OpenFlags::OF_NONBLOCK; - if(flags & O_TRUNC) + if (flags & O_TRUNC) proto_flags |= managarm::posix::OpenFlags::OF_TRUNC; - if(flags & O_CLOEXEC) + if (flags & O_CLOEXEC) proto_flags |= managarm::posix::OpenFlags::OF_CLOEXEC; - if(flags & O_NOCTTY) + if (flags & O_NOCTTY) proto_flags |= managarm::posix::OpenFlags::OF_NOCTTY; - if(flags & O_PATH) + if (flags & O_PATH) proto_flags |= managarm::posix::OpenFlags::OF_PATH; - else if((flags & O_ACCMODE) == O_RDONLY) + else if ((flags & O_ACCMODE) == O_RDONLY) proto_flags |= managarm::posix::OpenFlags::OF_RDONLY; - else if((flags & O_ACCMODE) == O_WRONLY) + else if ((flags & O_ACCMODE) == O_WRONLY) proto_flags |= managarm::posix::OpenFlags::OF_WRONLY; - else if((flags & O_ACCMODE) == O_RDWR) + else if ((flags & O_ACCMODE) == O_RDWR) proto_flags |= managarm::posix::OpenFlags::OF_RDWR; managarm::posix::OpenAtRequest req(getSysdepsAllocator()); @@ -1509,11 +1515,10 @@ int sys_openat(int dirfd, const char *path, int flags, mode_t mode, int *fd) { req.set_mode(mode); auto [offer, sendHead, sendTail, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1523,22 +1528,23 @@ int sys_openat(int dirfd, const char *path, int flags, mode_t mode, int *fd) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + } else if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - }else if(resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { return ENOTDIR; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_OPERATION_TARGET) { - mlibc::infoLogger() << "\e[31mmlibc: openat unimplemented for this file " << path << "\e[39m" << frg::endlog; + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_OPERATION_TARGET) { + mlibc::infoLogger() << "\e[31mmlibc: openat unimplemented for this file " << path + << "\e[39m" << frg::endlog; return EINVAL; - }else if(resp.error() == managarm::posix::Errors::NO_BACKING_DEVICE) { + } else if (resp.error() == managarm::posix::Errors::NO_BACKING_DEVICE) { return ENXIO; - }else if(resp.error() == managarm::posix::Errors::IS_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::IS_DIRECTORY) { return EISDIR; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *fd = resp.fd(); return 0; @@ -1553,14 +1559,12 @@ int sys_mkfifoat(int dirfd, const char *path, mode_t mode) { req.set_path(frg::string(getSysdepsAllocator(), path)); req.set_mode(mode); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -1569,17 +1573,17 @@ int sys_mkfifoat(int dirfd, const char *path, mode_t mode) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + } else if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::INTERNAL_ERROR) { + } else if (resp.error() == managarm::posix::Errors::INTERNAL_ERROR) { return EIEIO; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -1594,14 +1598,12 @@ int sys_mknodat(int dirfd, const char *path, int mode, int dev) { req.set_mode(mode); req.set_device(dev); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -1610,15 +1612,15 @@ int sys_mknodat(int dirfd, const char *path, int mode, int dev) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { + } else if (resp.error() == managarm::posix::Errors::ALREADY_EXISTS) { return EEXIST; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -1639,16 +1641,15 @@ int sys_read(int fd, void *data, size_t max_size, ssize_t *bytes_read) { frg::string ser(getSysdepsAllocator()); req.SerializeToString(&ser); - auto [offer, send_req, imbue_creds, recv_resp, recv_data] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::imbueCredentials(), - helix_ng::recvInline(), - helix_ng::recvBuffer(data, max_size) - ) - ); + auto [offer, send_req, imbue_creds, recv_resp, recv_data] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::imbueCredentials(), + helix_ng::recvInline(), + helix_ng::recvBuffer(data, max_size) + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -1657,21 +1658,21 @@ int sys_read(int fd, void *data, size_t max_size, ssize_t *bytes_read) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); -/* if(resp.error() == managarm::fs::Errors::NO_SUCH_FD) { - return EBADF; - }else*/ - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + /* if(resp.error() == managarm::fs::Errors::NO_SUCH_FD) { + return EBADF; + }else*/ + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else if(resp.error() == managarm::fs::Errors::WOULD_BLOCK) { + } else if (resp.error() == managarm::fs::Errors::WOULD_BLOCK) { return EAGAIN; - }else if(resp.error() == managarm::fs::Errors::IS_DIRECTORY) { + } else if (resp.error() == managarm::fs::Errors::IS_DIRECTORY) { return EISDIR; - }else if(resp.error() == managarm::fs::Errors::NOT_CONNECTED) { + } else if (resp.error() == managarm::fs::Errors::NOT_CONNECTED) { return ENOTCONN; - }else if(resp.error() == managarm::fs::Errors::END_OF_FILE) { + } else if (resp.error() == managarm::fs::Errors::END_OF_FILE) { *bytes_read = 0; return 0; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); HEL_CHECK(recv_data.error()); *bytes_read = recv_data.actualLength(); @@ -1680,12 +1681,12 @@ int sys_read(int fd, void *data, size_t max_size, ssize_t *bytes_read) { } int sys_readv(int fd, const struct iovec *iovs, int iovc, ssize_t *bytes_read) { - for(int i = 0; i < iovc; i++) { + for (int i = 0; i < iovc; i++) { ssize_t intermed = 0; - if(int e = sys_read(fd, iovs[i].iov_base, iovs[i].iov_len, &intermed); e) + if (int e = sys_read(fd, iovs[i].iov_base, iovs[i].iov_len, &intermed); e) return e; - else if(intermed == 0) + else if (intermed == 0) break; *bytes_read += intermed; @@ -1707,12 +1708,13 @@ int sys_write(int fd, const void *data, size_t size, ssize_t *bytes_written) { req.set_size(size); auto [offer, send_req, imbue_creds, send_data, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::sendBuffer(data, size), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::sendBuffer(data, size), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -1724,19 +1726,20 @@ int sys_write(int fd, const void *data, size_t size, ssize_t *bytes_written) { resp.ParseFromArray(recv_resp.data(), recv_resp.length()); // TODO: implement NO_SUCH_FD -/* if(resp.error() == managarm::fs::Errors::NO_SUCH_FD) { - return EBADF; - }else*/ if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + /* if(resp.error() == managarm::fs::Errors::NO_SUCH_FD) { + return EBADF; + }else*/ + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return EINVAL; // FD does not support writes. - }else if(resp.error() == managarm::fs::Errors::NO_SPACE_LEFT) { + } else if (resp.error() == managarm::fs::Errors::NO_SPACE_LEFT) { return ENOSPC; - }else if(resp.error() == managarm::fs::Errors::WOULD_BLOCK) { + } else if (resp.error() == managarm::fs::Errors::WOULD_BLOCK) { return EAGAIN; - }else if(resp.error() == managarm::fs::Errors::NOT_CONNECTED) { + } else if (resp.error() == managarm::fs::Errors::NOT_CONNECTED) { return ENOTCONN; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - if(bytes_written) { + if (bytes_written) { *bytes_written = resp.size(); } return 0; @@ -1757,12 +1760,13 @@ int sys_pread(int fd, void *buf, size_t n, off_t off, ssize_t *bytes_read) { req.set_offset(off); auto [offer, send_req, imbue_creds, recv_resp, recv_data] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::recvInline(), - helix_ng::recvBuffer(buf, n)) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::recvInline(), + helix_ng::recvBuffer(buf, n) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -1771,17 +1775,17 @@ int sys_pread(int fd, void *buf, size_t n, off_t off, ssize_t *bytes_read) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); -/* if(resp.error() == managarm::fs::Errors::NO_SUCH_FD) { - return EBADF; - }else*/ - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + /* if(resp.error() == managarm::fs::Errors::NO_SUCH_FD) { + return EBADF; + }else*/ + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else if(resp.error() == managarm::fs::Errors::WOULD_BLOCK) { + } else if (resp.error() == managarm::fs::Errors::WOULD_BLOCK) { return EAGAIN; - }else if(resp.error() == managarm::fs::Errors::END_OF_FILE) { + } else if (resp.error() == managarm::fs::Errors::END_OF_FILE) { *bytes_read = 0; return 0; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); HEL_CHECK(recv_data.error()); *bytes_read = recv_data.actualLength(); @@ -1806,13 +1810,13 @@ int sys_pwrite(int fd, const void *buf, size_t n, off_t off, ssize_t *bytes_writ req.SerializeToString(&ser); auto [offer, send_head, imbue_creds, to_write, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::sendBuffer(buf, n), - helix_ng::recvInline() - ) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::sendBuffer(buf, n), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1823,17 +1827,17 @@ int sys_pwrite(int fd, const void *buf, size_t n, off_t off, ssize_t *bytes_writ managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else if(resp.error() == managarm::fs::Errors::WOULD_BLOCK) { + } else if (resp.error() == managarm::fs::Errors::WOULD_BLOCK) { return EAGAIN; - }else if(resp.error() == managarm::fs::Errors::NO_SPACE_LEFT) { + } else if (resp.error() == managarm::fs::Errors::NO_SPACE_LEFT) { return ENOSPC; - }else if(resp.error() == managarm::fs::Errors::SEEK_ON_PIPE) { + } else if (resp.error() == managarm::fs::Errors::SEEK_ON_PIPE) { return ESPIPE; - }else if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *bytes_written = n; return 0; @@ -1844,20 +1848,20 @@ int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { SignalGuard sguard; auto handle = getHandleForFd(fd); - if(!handle) + if (!handle) return EBADF; managarm::fs::CntRequest req(getSysdepsAllocator()); req.set_fd(fd); req.set_rel_offset(offset); - if(whence == SEEK_SET) { + if (whence == SEEK_SET) { req.set_req_type(managarm::fs::CntReqType::SEEK_ABS); - }else if(whence == SEEK_CUR) { + } else if (whence == SEEK_CUR) { req.set_req_type(managarm::fs::CntReqType::SEEK_REL); - }else if(whence == SEEK_END) { + } else if (whence == SEEK_END) { req.set_req_type(managarm::fs::CntReqType::SEEK_EOF); - }else{ + } else { return EINVAL; } @@ -1865,11 +1869,8 @@ int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { req.SerializeToString(&ser); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::recvInline() - ) + handle, + helix_ng::offer(helix_ng::sendBuffer(ser.data(), ser.size()), helix_ng::recvInline()) ); HEL_CHECK(offer.error()); @@ -1878,9 +1879,9 @@ int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::SEEK_ON_PIPE) { + if (resp.error() == managarm::fs::Errors::SEEK_ON_PIPE) { return ESPIPE; - } else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -1889,7 +1890,6 @@ int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { } } - int sys_close(int fd) { SignalGuard sguard; @@ -1897,11 +1897,10 @@ int sys_close(int fd) { req.set_fd(fd); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1911,11 +1910,11 @@ int sys_close(int fd) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) { + if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::SUCCESS) { + } else if (resp.error() == managarm::posix::Errors::SUCCESS) { return 0; - }else{ + } else { __ensure(!"Unexpected error"); __builtin_unreachable(); } @@ -1927,7 +1926,7 @@ int sys_dup(int fd, int flags, int *newfd) { __ensure(!(flags & ~(O_CLOEXEC))); uint32_t proto_flags = 0; - if(flags & O_CLOEXEC) + if (flags & O_CLOEXEC) proto_flags |= managarm::posix::OpenFlags::OF_CLOEXEC; managarm::posix::CntRequest req(getSysdepsAllocator()); @@ -1936,10 +1935,10 @@ int sys_dup(int fd, int flags, int *newfd) { req.set_flags(proto_flags); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1970,10 +1969,10 @@ int sys_dup2(int fd, int flags, int newfd) { req.set_flags(flags); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -2020,14 +2019,12 @@ int sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, struct stat req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2036,31 +2033,38 @@ int sys_stat(fsfd_target fsfdt, int fd, const char *path, int flags, struct stat managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { return ENOTDIR; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); memset(result, 0, sizeof(struct stat)); - switch(resp.file_type()) { + switch (resp.file_type()) { case managarm::posix::FileType::FT_REGULAR: - result->st_mode = S_IFREG; break; + result->st_mode = S_IFREG; + break; case managarm::posix::FileType::FT_DIRECTORY: - result->st_mode = S_IFDIR; break; + result->st_mode = S_IFDIR; + break; case managarm::posix::FileType::FT_SYMLINK: - result->st_mode = S_IFLNK; break; + result->st_mode = S_IFLNK; + break; case managarm::posix::FileType::FT_CHAR_DEVICE: - result->st_mode = S_IFCHR; break; + result->st_mode = S_IFCHR; + break; case managarm::posix::FileType::FT_BLOCK_DEVICE: - result->st_mode = S_IFBLK; break; + result->st_mode = S_IFBLK; + break; case managarm::posix::FileType::FT_SOCKET: - result->st_mode = S_IFSOCK; break; + result->st_mode = S_IFSOCK; + break; case managarm::posix::FileType::FT_FIFO: - result->st_mode = S_IFIFO; break; + result->st_mode = S_IFIFO; + break; default: __ensure(!resp.file_type()); } @@ -2097,11 +2101,12 @@ int sys_readlinkat(int dirfd, const char *path, void *data, size_t max_size, ssi req.set_path(frg::string(getSysdepsAllocator(), path)); auto [offer, send_head, send_tail, recv_resp, recv_data] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(data, max_size)) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(data, max_size) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2110,11 +2115,11 @@ int sys_readlinkat(int dirfd, const char *path, void *data, size_t max_size, ssi managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *length = recv_data.actualLength(); return 0; @@ -2127,14 +2132,12 @@ int sys_rmdir(const char *path) { managarm::posix::RmdirRequest req(getSysdepsAllocator()); req.set_path(frg::string(getSysdepsAllocator(), path)); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2143,15 +2146,15 @@ int sys_rmdir(const char *path) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::DIRECTORY_NOT_EMPTY) { + } else if (resp.error() == managarm::posix::Errors::DIRECTORY_NOT_EMPTY) { return ENOTEMPTY; - }else if(resp.error() == managarm::posix::Errors::INTERNAL_ERROR) { + } else if (resp.error() == managarm::posix::Errors::INTERNAL_ERROR) { return EIEIO; - }else if(resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { return ENOTDIR; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -2169,10 +2172,10 @@ int sys_ftruncate(int fd, size_t size) { req.set_size(size); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -2180,7 +2183,7 @@ int sys_ftruncate(int fd, size_t size) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return EINVAL; } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -2201,10 +2204,10 @@ int sys_fallocate(int fd, off_t offset, size_t size) { req.set_size(size); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -2212,13 +2215,13 @@ int sys_fallocate(int fd, off_t offset, size_t size) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return EINVAL; - }else if(resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { + } else if (resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { return EPERM; - }else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); return 0; } @@ -2233,14 +2236,12 @@ int sys_unlinkat(int fd, const char *path, int flags) { req.set_path(frg::string(getSysdepsAllocator(), path)); req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2249,29 +2250,27 @@ int sys_unlinkat(int fd, const char *path, int flags) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::RESOURCE_IN_USE) { + } else if (resp.error() == managarm::posix::Errors::RESOURCE_IN_USE) { return EBUSY; - }else if(resp.error() == managarm::posix::Errors::IS_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::IS_DIRECTORY) { return EISDIR; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::BAD_FD) { + } else if (resp.error() == managarm::posix::Errors::BAD_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { + } else if (resp.error() == managarm::posix::Errors::NOT_A_DIRECTORY) { return ENOTDIR; - }else if(resp.error() == managarm::posix::Errors::DIRECTORY_NOT_EMPTY) { + } else if (resp.error() == managarm::posix::Errors::DIRECTORY_NOT_EMPTY) { return ENOTEMPTY; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } } -int sys_access(const char *path, int mode) { - return sys_faccessat(AT_FDCWD, path, mode, 0); -} +int sys_access(const char *path, int mode) { return sys_faccessat(AT_FDCWD, path, mode, 0); } int sys_faccessat(int dirfd, const char *pathname, int, int flags) { SignalGuard sguard; @@ -2281,14 +2280,12 @@ int sys_faccessat(int dirfd, const char *pathname, int, int flags) { req.set_fd(dirfd); req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2297,13 +2294,13 @@ int sys_faccessat(int dirfd, const char *pathname, int, int flags) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) { + } else if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -2317,15 +2314,15 @@ int sys_flock(int fd, int opts) { req.set_fd(fd); req.set_flock_flags(opts); auto handle = getHandleForFd(fd); - if(!handle) { + if (!handle) { return EBADF; } auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -2333,9 +2330,9 @@ int sys_flock(int fd, int opts) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::WOULD_BLOCK) { + if (resp.error() == managarm::posix::Errors::WOULD_BLOCK) { return EWOULDBLOCK; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); @@ -2350,11 +2347,10 @@ int sys_isatty(int fd) { req.set_fd(fd); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -2363,11 +2359,11 @@ int sys_isatty(int fd) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) { + if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) { return EBADF; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); - if(resp.mode()) + if (resp.mode()) return 0; return ENOTTY; } @@ -2377,9 +2373,7 @@ int sys_chmod(const char *pathname, mode_t mode) { return sys_fchmodat(AT_FDCWD, pathname, mode, 0); } -int sys_fchmod(int fd, mode_t mode) { - return sys_fchmodat(fd, "", mode, AT_EMPTY_PATH); -} +int sys_fchmod(int fd, mode_t mode) { return sys_fchmodat(fd, "", mode, AT_EMPTY_PATH); } int sys_fchmodat(int fd, const char *pathname, mode_t mode, int flags) { SignalGuard sguard; @@ -2390,14 +2384,12 @@ int sys_fchmodat(int fd, const char *pathname, mode_t mode, int flags) { req.set_mode(mode); req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2406,15 +2398,15 @@ int sys_fchmodat(int fd, const char *pathname, mode_t mode, int flags) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) { + } else if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::NOT_SUPPORTED) { + } else if (resp.error() == managarm::posix::Errors::NOT_SUPPORTED) { return ENOTSUP; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -2442,9 +2434,9 @@ int sys_utimensat(int dirfd, const char *pathname, const struct timespec times[2 managarm::posix::UtimensAtRequest req(getSysdepsAllocator()); req.set_fd(dirfd); - if(pathname != nullptr) + if (pathname != nullptr) req.set_path(frg::string(getSysdepsAllocator(), pathname)); - if(times) { + if (times) { req.set_atimeSec(times[0].tv_sec); req.set_atimeNsec(times[0].tv_nsec); req.set_mtimeSec(times[1].tv_sec); @@ -2457,14 +2449,12 @@ int sys_utimensat(int dirfd, const char *pathname, const struct timespec times[2 } req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2473,15 +2463,15 @@ int sys_utimensat(int dirfd, const char *pathname, const struct timespec times[2 managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) { return ENOENT; - }else if(resp.error() == managarm::posix::Errors::NO_SUCH_FD) { + } else if (resp.error() == managarm::posix::Errors::NO_SUCH_FD) { return EBADF; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else if(resp.error() == managarm::posix::Errors::NOT_SUPPORTED) { + } else if (resp.error() == managarm::posix::Errors::NOT_SUPPORTED) { return ENOTSUP; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -2492,10 +2482,10 @@ int sys_getentropy(void *buffer, size_t length) { auto p = reinterpret_cast(buffer); size_t n = 0; - while(n < length) { + while (n < length) { size_t chunk; HEL_CHECK(helGetRandomBytes(p + n, length - n, &chunk)); - n+= chunk; + n += chunk; } return 0; @@ -2505,7 +2495,7 @@ int sys_gethostname(char *buffer, size_t bufsize) { SignalGuard sguard; mlibc::infoLogger() << "mlibc: gethostname always returns managarm" << frg::endlog; char name[10] = "managarm\0"; - if(bufsize < 10) + if (bufsize < 10) return ENAMETOOLONG; strncpy(buffer, name, 10); return 0; @@ -2523,14 +2513,12 @@ int sys_memfd_create(const char *name, int flags, int *fd) { req.set_name(frg::string(getSysdepsAllocator(), name)); req.set_flags(flags); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -2539,7 +2527,7 @@ int sys_memfd_create(const char *name, int flags, int *fd) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; } @@ -2558,10 +2546,10 @@ int sys_uname(struct utsname *buf) { strcpy(buf->version, "Managarm is not Managram"); #if defined(__x86_64__) strcpy(buf->machine, "x86_64"); -#elif defined (__aarch64__) +#elif defined(__aarch64__) strcpy(buf->machine, "aarch64"); #else -# error Unknown architecture +#error Unknown architecture #endif return 0; @@ -2574,9 +2562,9 @@ int sys_madvise(void *, size_t, int) { int sys_ptsname(int fd, char *buffer, size_t length) { int index; - if(int e = sys_ioctl(fd, TIOCGPTN, &index, NULL); e) + if (int e = sys_ioctl(fd, TIOCGPTN, &index, NULL); e) return e; - if((size_t)snprintf(buffer, length, "/dev/pts/%d", index) >= length) { + if ((size_t)snprintf(buffer, length, "/dev/pts/%d", index) >= length) { return ERANGE; } return 0; @@ -2585,62 +2573,62 @@ int sys_ptsname(int fd, char *buffer, size_t length) { int sys_unlockpt(int fd) { int unlock = 0; - if(int e = sys_ioctl(fd, TIOCSPTLCK, &unlock, NULL); e) + if (int e = sys_ioctl(fd, TIOCSPTLCK, &unlock, NULL); e) return e; return 0; } int sys_getrlimit(int resource, struct rlimit *limit) { - switch(resource) { - case RLIMIT_NOFILE: - /* TODO: change this once we support more than 512 */ - limit->rlim_cur = 512; - limit->rlim_max = 512; - return 0; - default: - return EINVAL; + switch (resource) { + case RLIMIT_NOFILE: + /* TODO: change this once we support more than 512 */ + limit->rlim_cur = 512; + limit->rlim_max = 512; + return 0; + default: + return EINVAL; } } int sys_sysconf(int num, long *ret) { - switch(num) { - case _SC_OPEN_MAX: { - struct rlimit ru; - if(int e = sys_getrlimit(RLIMIT_NOFILE, &ru); e) { - return e; - } - *ret = (ru.rlim_cur == RLIM_INFINITY) ? -1 : ru.rlim_cur; - break; + switch (num) { + case _SC_OPEN_MAX: { + struct rlimit ru; + if (int e = sys_getrlimit(RLIMIT_NOFILE, &ru); e) { + return e; } - default: { - SignalGuard sguard; - - managarm::posix::SysconfRequest req(getSysdepsAllocator()); - req.set_num(num); - - auto [offer, send_req, recv_resp] = exchangeMsgsSync(getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); - - HEL_CHECK(offer.error()); - HEL_CHECK(send_req.error()); - HEL_CHECK(recv_resp.error()); - - managarm::posix::SysconfResponse resp(getSysdepsAllocator()); - resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { - return EINVAL; - } + *ret = (ru.rlim_cur == RLIM_INFINITY) ? -1 : ru.rlim_cur; + break; + } + default: { + SignalGuard sguard; - *ret = resp.value(); + managarm::posix::SysconfRequest req(getSysdepsAllocator()); + req.set_num(num); - __ensure(resp.error() == managarm::posix::Errors::SUCCESS); - return 0; + auto [offer, send_req, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); + + HEL_CHECK(offer.error()); + HEL_CHECK(send_req.error()); + HEL_CHECK(recv_resp.error()); + + managarm::posix::SysconfResponse resp(getSysdepsAllocator()); + resp.ParseFromArray(recv_resp.data(), recv_resp.length()); + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + return EINVAL; } + + *ret = resp.value(); + + __ensure(resp.error() == managarm::posix::Errors::SUCCESS); + return 0; + } } return 0; @@ -2651,11 +2639,11 @@ int sys_sysinfo(struct sysinfo *info) { managarm::posix::GetMemoryInformationRequest req(getSysdepsAllocator()); - auto [offer, send_req, recv_resp] = exchangeMsgsSync(getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_req, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -2684,5 +2672,4 @@ int sys_sysinfo(struct sysinfo *info) { return 0; } -} //namespace mlibc - +} // namespace mlibc diff --git a/sysdeps/managarm/generic/fork-exec.cpp b/sysdeps/managarm/generic/fork-exec.cpp index ee1bcd43a6..858b9dbedb 100644 --- a/sysdeps/managarm/generic/fork-exec.cpp +++ b/sysdeps/managarm/generic/fork-exec.cpp @@ -2,8 +2,8 @@ // for _Exit() #include -#include #include +#include // for fork() and execve() #include @@ -13,15 +13,15 @@ // for getrusage() #include // for waitpid() -#include #include +#include #include +#include #include #include #include #include -#include #include #include @@ -29,27 +29,26 @@ namespace mlibc { int sys_futex_tid() { HelWord tid = 0; - HEL_CHECK(helSyscall0_1(kHelCallSuper + posix::superGetTid, - &tid)); + HEL_CHECK(helSyscall0_1(kHelCallSuper + posix::superGetTid, &tid)); return tid; } int sys_futex_wait(int *pointer, int expected, const struct timespec *time) { // This implementation is inherently signal-safe. - if(time) { - if(helFutexWait(pointer, expected, time->tv_nsec + time->tv_sec * 1000000000)) + if (time) { + if (helFutexWait(pointer, expected, time->tv_nsec + time->tv_sec * 1000000000)) return -1; return 0; } - if(helFutexWait(pointer, expected, -1)) + if (helFutexWait(pointer, expected, -1)) return -1; return 0; } int sys_futex_wake(int *pointer) { // This implementation is inherently signal-safe. - if(helFutexWake(pointer)) + if (helFutexWake(pointer)) return -1; return 0; } @@ -62,14 +61,12 @@ int sys_waitpid(pid_t pid, int *status, int flags, struct rusage *ru, pid_t *ret req.set_pid(pid); req.set_flags(flags); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -77,15 +74,15 @@ int sys_waitpid(pid_t pid, int *status, int flags, struct rusage *ru, pid_t *ret managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; } __ensure(resp.error() == managarm::posix::Errors::SUCCESS); - if(status) + if (status) *status = resp.mode(); *ret_pid = resp.pid(); - if(ru != nullptr) { + if (ru != nullptr) { ru->ru_utime.tv_sec = resp.ru_user_time() / 1'000'000'000; ru->ru_utime.tv_usec = (resp.ru_user_time() % 1'000'000'000) / 1'000; } @@ -102,14 +99,12 @@ int sys_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { req.set_id(id); req.set_flags(options); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -117,7 +112,7 @@ int sys_waitid(idtype_t idtype, id_t id, siginfo_t *info, int options) { managarm::posix::WaitIdResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; } __ensure(resp.error() == managarm::posix::Errors::SUCCESS); @@ -148,8 +143,9 @@ int sys_sleep(time_t *secs, long *nanos) { HEL_CHECK(helGetClock(&now)); uint64_t async_id; - HEL_CHECK(helSubmitAwaitClock(now + uint64_t(*secs) * 1000000000 + uint64_t(*nanos), - globalQueue.getQueue(), 0, &async_id)); + HEL_CHECK(helSubmitAwaitClock( + now + uint64_t(*secs) * 1000000000 + uint64_t(*nanos), globalQueue.getQueue(), 0, &async_id + )); auto element = globalQueue.dequeueSingle(); auto result = parseSimple(element); @@ -177,7 +173,7 @@ int sys_fork(pid_t *child) { HEL_CHECK(helSyscall0_1(kHelCallSuper + posix::superFork, &out)); *child = out; - if(!out) { + if (!out) { clearCachedInfos(); globalQueue.recreateQueue(); } @@ -191,23 +187,25 @@ int sys_fork(pid_t *child) { int sys_execve(const char *path, char *const argv[], char *const envp[]) { // TODO: Make this function signal-safe! frg::string args_area(getSysdepsAllocator()); - for(auto it = argv; *it; ++it) + for (auto it = argv; *it; ++it) args_area += frg::string_view{*it, strlen(*it) + 1}; frg::string env_area(getSysdepsAllocator()); - for(auto it = envp; *it; ++it) + for (auto it = envp; *it; ++it) env_area += frg::string_view{*it, strlen(*it) + 1}; uintptr_t out; - HEL_CHECK(helSyscall6_1(kHelCallSuper + posix::superExecve, - reinterpret_cast(path), - strlen(path), - reinterpret_cast(args_area.data()), - args_area.size(), - reinterpret_cast(env_area.data()), - env_area.size(), - &out)); + HEL_CHECK(helSyscall6_1( + kHelCallSuper + posix::superExecve, + reinterpret_cast(path), + strlen(path), + reinterpret_cast(args_area.data()), + args_area.size(), + reinterpret_cast(env_area.data()), + env_area.size(), + &out + )); return out; } @@ -217,14 +215,12 @@ gid_t sys_getgid() { managarm::posix::GetGidRequest req(getSysdepsAllocator()); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -243,14 +239,12 @@ int sys_setgid(gid_t gid) { req.set_uid(gid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -258,11 +252,11 @@ int sys_setgid(gid_t gid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ACCESS_DENIED) { + if (resp.error() == managarm::posix::Errors::ACCESS_DENIED) { return EPERM; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -273,14 +267,12 @@ gid_t sys_getegid() { managarm::posix::GetEgidRequest req(getSysdepsAllocator()); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -299,14 +291,12 @@ int sys_setegid(gid_t egid) { req.set_uid(egid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -314,11 +304,11 @@ int sys_setegid(gid_t egid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ACCESS_DENIED) { + if (resp.error() == managarm::posix::Errors::ACCESS_DENIED) { return EPERM; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -329,14 +319,12 @@ uid_t sys_getuid() { managarm::posix::GetUidRequest req(getSysdepsAllocator()); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -355,14 +343,12 @@ int sys_setuid(uid_t uid) { req.set_uid(uid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -370,11 +356,11 @@ int sys_setuid(uid_t uid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ACCESS_DENIED) { + if (resp.error() == managarm::posix::Errors::ACCESS_DENIED) { return EPERM; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -385,14 +371,12 @@ uid_t sys_geteuid() { managarm::posix::GetEuidRequest req(getSysdepsAllocator()); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -411,14 +395,12 @@ int sys_seteuid(uid_t euid) { req.set_uid(euid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -426,11 +408,11 @@ int sys_seteuid(uid_t euid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ACCESS_DENIED) { + if (resp.error() == managarm::posix::Errors::ACCESS_DENIED) { return EPERM; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -446,14 +428,12 @@ pid_t sys_getpid() { managarm::posix::GetPidRequest req(getSysdepsAllocator()); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -470,14 +450,12 @@ pid_t sys_getppid() { managarm::posix::GetPpidRequest req(getSysdepsAllocator()); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -495,14 +473,12 @@ int sys_getsid(pid_t pid, pid_t *sid) { managarm::posix::GetSidRequest req(getSysdepsAllocator()); req.set_pid(pid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -510,7 +486,7 @@ int sys_getsid(pid_t pid, pid_t *sid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_RESOURCE) { + if (resp.error() == managarm::posix::Errors::NO_SUCH_RESOURCE) { *sid = 0; return ESRCH; } else { @@ -526,14 +502,12 @@ int sys_getpgid(pid_t pid, pid_t *pgid) { managarm::posix::GetPgidRequest req(getSysdepsAllocator()); req.set_pid(pid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -541,7 +515,7 @@ int sys_getpgid(pid_t pid, pid_t *pgid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::NO_SUCH_RESOURCE) { + if (resp.error() == managarm::posix::Errors::NO_SUCH_RESOURCE) { *pgid = 0; return ESRCH; } else { @@ -559,14 +533,12 @@ int sys_setpgid(pid_t pid, pid_t pgid) { req.set_pid(pid); req.set_pgid(pgid); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -574,13 +546,13 @@ int sys_setpgid(pid_t pid, pid_t pgid) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::INSUFFICIENT_PERMISSION) { + if (resp.error() == managarm::posix::Errors::INSUFFICIENT_PERMISSION) { return EPERM; - }else if(resp.error() == managarm::posix::Errors::NO_SUCH_RESOURCE) { + } else if (resp.error() == managarm::posix::Errors::NO_SUCH_RESOURCE) { return ESRCH; - }else if(resp.error() == managarm::posix::Errors::ACCESS_DENIED) { + } else if (resp.error() == managarm::posix::Errors::ACCESS_DENIED) { return EACCES; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } @@ -595,14 +567,12 @@ int sys_getrusage(int scope, struct rusage *usage) { req.set_request_type(managarm::posix::CntReqType::GET_RESOURCE_USAGE); req.set_mode(scope); - auto [offer, send_head, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -619,25 +589,26 @@ int sys_getrusage(int scope, struct rusage *usage) { } int sys_getschedparam(void *tcb, int *policy, struct sched_param *param) { - if(tcb != mlibc::get_current_tcb()) { + if (tcb != mlibc::get_current_tcb()) { return ESRCH; } *policy = SCHED_OTHER; int prio = 0; // TODO(no92): use helGetPriority(kHelThisThread) here - mlibc::infoLogger() << "\e[31mlibc: sys_getschedparam always returns priority 0\e[39m" << frg::endlog; + mlibc::infoLogger() << "\e[31mlibc: sys_getschedparam always returns priority 0\e[39m" + << frg::endlog; param->sched_priority = prio; return 0; } int sys_setschedparam(void *tcb, int policy, const struct sched_param *param) { - if(tcb != mlibc::get_current_tcb()) { + if (tcb != mlibc::get_current_tcb()) { return ESRCH; } - if(policy != SCHED_OTHER) { + if (policy != SCHED_OTHER) { return EINVAL; } @@ -648,10 +619,12 @@ int sys_setschedparam(void *tcb, int policy, const struct sched_param *param) { int sys_clone(void *tcb, pid_t *pid_out, void *stack) { HelWord pid = 0; - HEL_CHECK(helSyscall2_1(kHelCallSuper + posix::superClone, - reinterpret_cast(__mlibc_start_thread), - reinterpret_cast(stack), - &pid)); + HEL_CHECK(helSyscall2_1( + kHelCallSuper + posix::superClone, + reinterpret_cast(__mlibc_start_thread), + reinterpret_cast(stack), + &pid + )); if (pid_out) *pid_out = pid; @@ -663,7 +636,7 @@ int sys_tcb_set(void *pointer) { #if defined(__aarch64__) uintptr_t addr = reinterpret_cast(pointer); addr += sizeof(Tcb) - 0x10; - asm volatile ("msr tpidr_el0, %0" :: "r"(addr)); + asm volatile("msr tpidr_el0, %0" ::"r"(addr)); #else HEL_CHECK(helWriteFsBase(pointer)); #endif @@ -677,7 +650,7 @@ void sys_thread_exit() { } int sys_thread_setname(void *tcb, const char *name) { - if(strlen(name) > 15) { + if (strlen(name) > 15) { return ERANGE; } @@ -685,18 +658,18 @@ int sys_thread_setname(void *tcb, const char *name) { char *path; int cs = 0; - if(asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { + if (asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { return ENOMEM; } pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); int fd; - if(int e = sys_open(path, O_WRONLY, 0, &fd); e) { + if (int e = sys_open(path, O_WRONLY, 0, &fd); e) { return e; } - if(int e = sys_write(fd, name, strlen(name) + 1, NULL)) { + if (int e = sys_write(fd, name, strlen(name) + 1, NULL)) { return e; } @@ -713,18 +686,18 @@ int sys_thread_getname(void *tcb, char *name, size_t size) { int cs = 0; ssize_t real_size = 0; - if(asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { + if (asprintf(&path, "/proc/self/task/%d/comm", t->tid) < 0) { return ENOMEM; } pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs); int fd; - if(int e = sys_open(path, O_RDONLY | O_CLOEXEC, 0, &fd); e) { + if (int e = sys_open(path, O_RDONLY | O_CLOEXEC, 0, &fd); e) { return e; } - if(int e = sys_read(fd, name, size, &real_size)) { + if (int e = sys_read(fd, name, size, &real_size)) { return e; } @@ -733,13 +706,11 @@ int sys_thread_getname(void *tcb, char *name, size_t size) { pthread_setcancelstate(cs, 0); - if(static_cast(size) <= real_size) { + if (static_cast(size) <= real_size) { return ERANGE; } return 0; } - -} //namespace mlibc - +} // namespace mlibc diff --git a/sysdeps/managarm/generic/ioctl.cpp b/sysdeps/managarm/generic/ioctl.cpp index b0925e6929..738c4c08d7 100644 --- a/sysdeps/managarm/generic/ioctl.cpp +++ b/sysdeps/managarm/generic/ioctl.cpp @@ -3,12 +3,12 @@ #include #include #include -#include #include -#include +#include #include #include #include +#include #include #include @@ -28,26 +28,28 @@ static constexpr bool logIoctls = false; int ioctl_drm(int fd, unsigned long request, void *arg, int *result, HelHandle handle); int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { - if(logIoctls) + if (logIoctls) mlibc::infoLogger() << "mlibc: ioctl with" - << " type: 0x" << frg::hex_fmt(_IOC_TYPE(request)) - << ", number: 0x" << frg::hex_fmt(_IOC_NR(request)) - << " (raw request: " << frg::hex_fmt(request) << ")" - << " on fd " << fd << frg::endlog; + << " type: 0x" << frg::hex_fmt(_IOC_TYPE(request)) << ", number: 0x" + << frg::hex_fmt(_IOC_NR(request)) + << " (raw request: " << frg::hex_fmt(request) << ")" + << " on fd " << fd << frg::endlog; SignalGuard sguard; auto handle = getHandleForFd(fd); - if(!handle) + if (!handle) return EBADF; - if(_IOC_TYPE(request) == 'd') { + if (_IOC_TYPE(request) == 'd') { return ioctl_drm(fd, request, arg, result, handle); } - auto handle_siocgif = [&arg, &request, &result] - (void (*req_setup)(managarm::fs::IfreqRequest &req, struct ifreq *ifr), - int (*resp_parse)(managarm::fs::IfreqReply &resp, struct ifreq *ifr)) -> int { - if(!arg) + auto handle_siocgif = + [&arg, &request, &result]( + void (*req_setup)(managarm::fs::IfreqRequest &req, struct ifreq *ifr), + int (*resp_parse)(managarm::fs::IfreqReply &resp, struct ifreq *ifr) + ) -> int { + if (!arg) return EFAULT; auto ifr = reinterpret_cast(arg); @@ -58,14 +60,13 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req_setup(req, ifr); - auto [offer, send_token_req, send_req, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(token_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_token_req, send_req, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(token_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -78,21 +79,21 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { int ret = resp_parse(resp, ifr); - if(result) + if (result) *result = 0; return ret; }; managarm::fs::IoctlRequest ioctl_req(getSysdepsAllocator()); - switch(request) { + switch (request) { case FIONBIO: { auto mode = reinterpret_cast(arg); int flags = fcntl(fd, F_GETFL, 0); - if(*mode) { - fcntl(fd, F_SETFL, flags | O_NONBLOCK); - }else{ - fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); + if (*mode) { + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } else { + fcntl(fd, F_SETFL, flags & ~O_NONBLOCK); } return 0; } @@ -103,20 +104,19 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { if (!handle) return EBADF; - if(!argp) + if (!argp) return EINVAL; managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(FIONREAD); - auto [offer, send_ioctl_req, send_req, recv_resp] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -126,7 +126,7 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::NOT_CONNECTED) { + if (resp.error() == managarm::fs::Errors::NOT_CONNECTED) { return ENOTCONN; } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -141,16 +141,15 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_fd(fd); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(sendReq.error()); - if(recvResp.error() == kHelErrDismissed) + if (recvResp.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(recvResp.error()); @@ -165,18 +164,19 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); - auto [offer, send_ioctl_req, send_req, recv_resp, recv_attrs] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(param, sizeof(struct termios)) - ) + auto [offer, send_ioctl_req, send_req, recv_resp, recv_attrs] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(param, sizeof(struct termios)) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -195,18 +195,19 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); - auto [offer, send_ioctl_req, send_req, send_attrs, recv_resp] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::sendBuffer(param, sizeof(struct termios)), - helix_ng::recvInline() - ) + auto [offer, send_ioctl_req, send_req, send_attrs, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::sendBuffer(param, sizeof(struct termios)), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(send_attrs.error()); @@ -215,7 +216,7 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - if(result) + if (result) *result = resp.result(); return 0; } @@ -224,16 +225,17 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_command(request); auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_ioctl_req.error()); HEL_CHECK(imbue_creds.error()); @@ -243,9 +245,9 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - }else if(resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { + } else if (resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { return EPERM; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -258,26 +260,27 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); - auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); - if(recv_resp.error() == kHelErrDismissed) + if (recv_resp.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(recv_resp.error()); managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) return EINVAL; __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -299,15 +302,16 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_pts_pixel_height(param->ws_ypixel); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -326,15 +330,16 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_command(request); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -343,7 +348,7 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { resp.ParseFromArray(recv_resp.data(), recv_resp.length()); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *param = resp.pts_index(); - if(result) + if (result) *result = resp.result(); return 0; } @@ -354,24 +359,24 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::string ser(getSysdepsAllocator()); req.SerializeToString(&ser); - auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::imbueCredentials(), - helix_ng::recvInline() - ) - ); + auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::imbueCredentials(), + helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error()) + if (send_req.error()) return EINVAL; HEL_CHECK(send_req.error()); - if(imbue_creds.error()) { - infoLogger() << "mlibc: TIOCGPGRP used on unexpected socket, returning EINVAL (FIXME)" << frg::endlog; + if (imbue_creds.error()) { + infoLogger() << "mlibc: TIOCGPGRP used on unexpected socket, returning EINVAL (FIXME)" + << frg::endlog; return EINVAL; } HEL_CHECK(imbue_creds.error()); @@ -379,7 +384,7 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::NOT_A_TERMINAL) { + if (resp.error() == managarm::fs::Errors::NOT_A_TERMINAL) { return ENOTTY; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -397,20 +402,19 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::string ser(getSysdepsAllocator()); req.SerializeToString(&ser); - auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::imbueCredentials(), - helix_ng::recvInline() - ) - ); + auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::imbueCredentials(), + helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(imbue_creds.error()); @@ -418,9 +422,9 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { + if (resp.error() == managarm::fs::Errors::INSUFFICIENT_PERMISSIONS) { return EPERM; - } else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -434,32 +438,31 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::string ser(getSysdepsAllocator()); req.SerializeToString(&ser); - auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::imbueCredentials(), - helix_ng::recvInline() - ) - ); + auto [offer, send_ioctl_req, send_req, imbue_creds, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::imbueCredentials(), + helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); - if(send_ioctl_req.error()) + if (send_ioctl_req.error()) return EINVAL; HEL_CHECK(send_ioctl_req.error()); - if(send_req.error()) + if (send_req.error()) return EINVAL; HEL_CHECK(send_req.error()); - if(imbue_creds.error() == kHelErrDismissed) + if (imbue_creds.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(imbue_creds.error()); HEL_CHECK(recv_resp.error()); managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::NOT_A_TERMINAL) { + if (resp.error() == managarm::fs::Errors::NOT_A_TERMINAL) { return ENOTTY; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -474,28 +477,27 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::string ser(getSysdepsAllocator()); req.SerializeToString(&ser); - auto [offer, send_ioctl_req, send_req, recv_resp] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::recvInline() - ) - ); + auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); - if(send_ioctl_req.error()) + if (send_ioctl_req.error()) return EINVAL; HEL_CHECK(send_ioctl_req.error()); - if(send_req.error()) + if (send_req.error()) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); managarm::fs::GenericIoctlReply resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::NOT_A_TERMINAL) { + if (resp.error() == managarm::fs::Errors::NOT_A_TERMINAL) { return ENOTTY; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -504,26 +506,24 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { } } // end of switch() - - if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGVERSION)) { + if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGVERSION)) { *reinterpret_cast(arg) = EV_VERSION; *result = 0; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGID)) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGID)) { memset(arg, 0, sizeof(struct input_id)); auto param = reinterpret_cast(arg); managarm::fs::EvioGetIdRequest req(getSysdepsAllocator()); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::want_lane, - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::want_lane, + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); auto conversation = offer.descriptor(); @@ -531,7 +531,8 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); - auto resp = *bragi::parse_head_only(recv_resp, getSysdepsAllocator()); + auto resp = + *bragi::parse_head_only(recv_resp, getSysdepsAllocator()); recv_resp.reset(); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -542,17 +543,17 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { *result = 0; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGNAME(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGNAME(0))) { managarm::fs::EvioGetNameRequest req(getSysdepsAllocator()); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::want_lane, - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::want_lane, + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); auto conversation = offer.descriptor(); @@ -566,13 +567,14 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::vector tailBuffer{getSysdepsAllocator()}; tailBuffer.resize(preamble.tail_size()); auto [recv_tail] = exchangeMsgsSync( - conversation.getHandle(), - helix_ng::recvBuffer(tailBuffer.data(), tailBuffer.size()) + conversation.getHandle(), helix_ng::recvBuffer(tailBuffer.data(), tailBuffer.size()) ); HEL_CHECK(recv_tail.error()); - auto resp = *bragi::parse_head_tail(recv_resp, tailBuffer, getSysdepsAllocator()); + auto resp = *bragi::parse_head_tail( + recv_resp, tailBuffer, getSysdepsAllocator() + ); recv_resp.reset(); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -580,43 +582,37 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { memcpy(arg, resp.name().data(), chunk); *result = chunk; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGRAB)) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGRAB)) { mlibc::infoLogger() << "mlibc: EVIOCGRAB is a no-op" << frg::endlog; *result = 0; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGPHYS(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGPHYS(0))) { // Returns the sysfs path of the device. const char *s = "input0"; auto chunk = frg::min(_IOC_SIZE(request), strlen(s) + 1); memcpy(arg, s, chunk); *result = chunk; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGUNIQ(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGUNIQ(0))) { // Returns a unique ID for the device. const char *s = "0"; auto chunk = frg::min(_IOC_SIZE(request), strlen(s) + 1); memcpy(arg, s, chunk); *result = chunk; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGPROP(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGPROP(0))) { // Returns a bitmask of properties of the device. auto size = _IOC_SIZE(request); memset(arg, 0, size); *result = size; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGKEY(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGKEY(0))) { // Returns the current key state. auto size = _IOC_SIZE(request); memset(arg, 0, size); *result = size; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGMTSLOTS(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGMTSLOTS(0))) { // this ioctl is completely, utterly undocumented // the _IOC_SIZE is a buffer size in bytes, which should be a multiple of int32_t // bytes should be at least sizeof(int32_t) large. @@ -627,7 +623,7 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { // the length argument is the buffer size, in bytes auto bytes = _IOC_SIZE(request); // the length argument should be a multiple of int32_t - if(!bytes || bytes % sizeof(int32_t)) + if (!bytes || bytes % sizeof(int32_t)) return EINVAL; // the number of entries the buffer can hold @@ -637,12 +633,13 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_code(*reinterpret_cast(arg)); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::want_lane, - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::want_lane, + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); auto conversation = offer.descriptor(); @@ -656,47 +653,45 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::vector tailBuffer{getSysdepsAllocator()}; tailBuffer.resize(preamble.tail_size()); auto [recv_tail] = exchangeMsgsSync( - conversation.getHandle(), - helix_ng::recvBuffer(tailBuffer.data(), tailBuffer.size()) + conversation.getHandle(), helix_ng::recvBuffer(tailBuffer.data(), tailBuffer.size()) ); HEL_CHECK(recv_tail.error()); - auto resp = *bragi::parse_head_tail(recv_resp, tailBuffer, getSysdepsAllocator()); + auto resp = *bragi::parse_head_tail( + recv_resp, tailBuffer, getSysdepsAllocator() + ); recv_resp.reset(); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); auto param = reinterpret_cast(arg); - for(size_t i = 0; i < resp.values_size() && i < entries; i++) { + for (size_t i = 0; i < resp.values_size() && i < entries; i++) { param[i + 1] = resp.values(i); } param[0] = resp.values_size(); return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGLED(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGLED(0))) { // Returns the current LED state. auto size = _IOC_SIZE(request); memset(arg, 0, size); *result = size; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCGSW(0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCGSW(0))) { auto size = _IOC_SIZE(request); memset(arg, 0, size); *result = size; return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) >= _IOC_NR(EVIOCGBIT(0, 0)) - && _IOC_NR(request) <= _IOC_NR(EVIOCGBIT(EV_MAX, 0))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) >= _IOC_NR(EVIOCGBIT(0, 0)) && + _IOC_NR(request) <= _IOC_NR(EVIOCGBIT(EV_MAX, 0))) { // Returns a bitmask of capabilities of the device. // If type is zero, return a mask of supported types. // As EV_SYN is zero, this implies that it is impossible // to get the mask of supported synthetic events. auto type = _IOC_NR(request) - _IOC_NR(EVIOCGBIT(0, 0)); - if(!type) { + if (!type) { // TODO: Check with the Linux ABI if we have to do this. memset(arg, 0, _IOC_SIZE(request)); @@ -705,17 +700,18 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_size(_IOC_SIZE(request)); auto [offer, send_ioctl_req, send_req, recv_resp, recv_data] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(arg, _IOC_SIZE(request))) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(arg, _IOC_SIZE(request)) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -726,7 +722,7 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = recv_data.actualLength(); return 0; - }else{ + } else { // TODO: Check with the Linux ABI if we have to do this. memset(arg, 0, _IOC_SIZE(request)); @@ -736,17 +732,18 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_size(_IOC_SIZE(request)); auto [offer, send_ioctl_req, send_req, recv_resp, recv_data] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(arg, _IOC_SIZE(request))) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(arg, _IOC_SIZE(request)) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -758,25 +755,25 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { *result = recv_data.actualLength(); return 0; } - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) == _IOC_NR(EVIOCSCLOCKID)) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) == _IOC_NR(EVIOCSCLOCKID)) { auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); req.set_input_clock(*param); - auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -786,9 +783,8 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *result = resp.result(); return 0; - }else if(_IOC_TYPE(request) == 'E' - && _IOC_NR(request) >= _IOC_NR(EVIOCGABS(0)) - && _IOC_NR(request) <= _IOC_NR(EVIOCGABS(ABS_MAX))) { + } else if (_IOC_TYPE(request) == 'E' && _IOC_NR(request) >= _IOC_NR(EVIOCGABS(0)) && + _IOC_NR(request) <= _IOC_NR(EVIOCGABS(ABS_MAX))) { auto param = reinterpret_cast(arg); auto type = _IOC_NR(request) - _IOC_NR(EVIOCGABS(0)); @@ -796,17 +792,18 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { req.set_command(EVIOCGABS(0)); req.set_input_type(type); - auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync(handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_ioctl_req.error()); - if(send_req.error() == kHelErrDismissed) + if (send_req.error() == kHelErrDismissed) return EINVAL; HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); @@ -824,32 +821,34 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { *result = resp.result(); return 0; - }else if(request == KDSETMODE) { + } else if (request == KDSETMODE) { auto param = reinterpret_cast(arg); - mlibc::infoLogger() << "\e[35mmlibc: KD_SETMODE(" << frg::hex_fmt(param) << ") is a no-op" << frg::endlog; + mlibc::infoLogger() << "\e[35mmlibc: KD_SETMODE(" << frg::hex_fmt(param) << ") is a no-op" + << frg::endlog; *result = 0; return 0; - }else if(request == KDGETMODE) { + } else if (request == KDGETMODE) { auto param = reinterpret_cast(arg); mlibc::infoLogger() << "\e[35mmlibc: KD_GETMODE is a no-op" << frg::endlog; *param = 0; *result = 0; return 0; - }else if(request == KDSKBMODE) { + } else if (request == KDSKBMODE) { auto param = reinterpret_cast(arg); - mlibc::infoLogger() << "\e[35mmlibc: KD_SKBMODE(" << frg::hex_fmt(param) << ") is a no-op" << frg::endlog; + mlibc::infoLogger() << "\e[35mmlibc: KD_SKBMODE(" << frg::hex_fmt(param) << ") is a no-op" + << frg::endlog; *result = 0; return 0; - }else if(request == VT_SETMODE) { + } else if (request == VT_SETMODE) { // auto param = reinterpret_cast(arg); mlibc::infoLogger() << "\e[35mmlibc: VT_SETMODE is a no-op" << frg::endlog; *result = 0; return 0; - }else if(request == VT_GETSTATE) { + } else if (request == VT_GETSTATE) { auto param = reinterpret_cast(arg); param->v_active = 0; @@ -860,26 +859,27 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { *result = 0; return 0; - }else if(request == VT_ACTIVATE || request == VT_WAITACTIVE) { + } else if (request == VT_ACTIVATE || request == VT_WAITACTIVE) { mlibc::infoLogger() << "\e[35mmlibc: VT_ACTIVATE/VT_WAITACTIVE are no-ops" << frg::endlog; *result = 0; return 0; - }else if(request == TIOCSPTLCK) { + } else if (request == TIOCSPTLCK) { mlibc::infoLogger() << "\e[35mmlibc: TIOCSPTLCK is a no-op" << frg::endlog; - if(result) + if (result) *result = 0; return 0; - } else if(request == SIOCGIFNAME) { - return handle_siocgif([](auto req, auto ifr) { - req.set_index(ifr->ifr_ifindex); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - strncpy(ifr->ifr_name, resp.name().data(), IFNAMSIZ); - return 0; - }); - }else if(request == SIOCGIFCONF) { - if(!arg) + } else if (request == SIOCGIFNAME) { + return handle_siocgif( + [](auto req, auto ifr) { req.set_index(ifr->ifr_ifindex); }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + strncpy(ifr->ifr_name, resp.name().data(), IFNAMSIZ); + return 0; + } + ); + } else if (request == SIOCGIFCONF) { + if (!arg) return EFAULT; auto ifc = reinterpret_cast(arg); @@ -888,15 +888,14 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { managarm::fs::IfreqRequest req(getSysdepsAllocator()); req.set_command(request); - auto [offer, send_token_req, send_req, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::want_lane, - helix_ng::sendBragiHeadOnly(token_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + auto [offer, send_token_req, send_req, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::want_lane, + helix_ng::sendBragiHeadOnly(token_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); auto conversation = offer.descriptor(); @@ -912,25 +911,27 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { frg::vector tailBuffer{getSysdepsAllocator()}; tailBuffer.resize(preamble.tail_size()); auto [recv_tail] = exchangeMsgsSync( - conversation.getHandle(), - helix_ng::recvBuffer(tailBuffer.data(), tailBuffer.size()) + conversation.getHandle(), helix_ng::recvBuffer(tailBuffer.data(), tailBuffer.size()) ); HEL_CHECK(recv_tail.error()); - auto resp = *bragi::parse_head_tail(recv_resp, tailBuffer, getSysdepsAllocator()); + auto resp = *bragi::parse_head_tail( + recv_resp, tailBuffer, getSysdepsAllocator() + ); recv_resp.reset(); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - if(ifc->ifc_buf == nullptr) { + if (ifc->ifc_buf == nullptr) { ifc->ifc_len = int(resp.ifconf_size() * sizeof(struct ifreq)); return 0; } ifc->ifc_len = frg::min(int(resp.ifconf_size() * sizeof(struct ifreq)), ifc->ifc_len); - for(size_t i = 0; i < frg::min(resp.ifconf_size() , ifc->ifc_len / sizeof(struct ifreq)); ++i) { + for (size_t i = 0; i < frg::min(resp.ifconf_size(), ifc->ifc_len / sizeof(struct ifreq)); + ++i) { auto &conf = resp.ifconf()[i]; sockaddr_in addr{}; @@ -942,107 +943,128 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { memcpy(&req->ifr_addr, &addr, sizeof(addr)); } - if(result) + if (result) *result = 0; return 0; - }else if(request == SIOCGIFNETMASK) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - - sockaddr_in addr{}; - addr.sin_family = AF_INET; - addr.sin_addr = { htonl(resp.ip4_netmask()) }; - memcpy(&ifr->ifr_netmask, &addr, sizeof(addr)); - - return 0; - }); - }else if(request == SIOCGIFINDEX) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - ifr->ifr_ifindex = resp.index(); - return 0; - }); - }else if(request == SIOCGIFFLAGS) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - ifr->ifr_flags = resp.flags(); - return 0; - }); - }else if(request == SIOCGIFADDR) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - - sockaddr_in addr{}; - addr.sin_family = AF_INET; - addr.sin_addr = { htonl(resp.ip4_addr()) }; - memcpy(&ifr->ifr_addr, &addr, sizeof(addr)); - - return 0; - }); - }else if(request == SIOCGIFMTU) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - - ifr->ifr_mtu = resp.mtu(); - - return 0; - }); - }else if(request == SIOCGIFBRDADDR) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - - sockaddr_in addr{}; - addr.sin_family = AF_INET; - addr.sin_addr = { htonl(resp.ip4_broadcast_addr()) }; - memcpy(&ifr->ifr_broadaddr, &addr, sizeof(addr)); - - return 0; - }); - } else if(request == SIOCGIFHWADDR) { - return handle_siocgif([](auto req, auto ifr) { - req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); - }, [](auto resp, auto ifr) { - if(resp.error() != managarm::fs::Errors::SUCCESS) - return EINVAL; - - sockaddr addr{}; - addr.sa_family = ARPHRD_ETHER; - memcpy(addr.sa_data, resp.mac().data(), 6); - memcpy(&ifr->ifr_hwaddr, &addr, sizeof(addr)); - - return 0; - }); - } else if(request == IOCTL_WDM_MAX_COMMAND) { + } else if (request == SIOCGIFNETMASK) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr = {htonl(resp.ip4_netmask())}; + memcpy(&ifr->ifr_netmask, &addr, sizeof(addr)); + + return 0; + } + ); + } else if (request == SIOCGIFINDEX) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + ifr->ifr_ifindex = resp.index(); + return 0; + } + ); + } else if (request == SIOCGIFFLAGS) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + ifr->ifr_flags = resp.flags(); + return 0; + } + ); + } else if (request == SIOCGIFADDR) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr = {htonl(resp.ip4_addr())}; + memcpy(&ifr->ifr_addr, &addr, sizeof(addr)); + + return 0; + } + ); + } else if (request == SIOCGIFMTU) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + + ifr->ifr_mtu = resp.mtu(); + + return 0; + } + ); + } else if (request == SIOCGIFBRDADDR) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr = {htonl(resp.ip4_broadcast_addr())}; + memcpy(&ifr->ifr_broadaddr, &addr, sizeof(addr)); + + return 0; + } + ); + } else if (request == SIOCGIFHWADDR) { + return handle_siocgif( + [](auto req, auto ifr) { + req.set_name(frg::string{ifr->ifr_name, getSysdepsAllocator()}); + }, + [](auto resp, auto ifr) { + if (resp.error() != managarm::fs::Errors::SUCCESS) + return EINVAL; + + sockaddr addr{}; + addr.sa_family = ARPHRD_ETHER; + memcpy(addr.sa_data, resp.mac().data(), 6); + memcpy(&ifr->ifr_hwaddr, &addr, sizeof(addr)); + + return 0; + } + ); + } else if (request == IOCTL_WDM_MAX_COMMAND) { auto param = reinterpret_cast(arg); managarm::fs::GenericIoctlRequest req(getSysdepsAllocator()); req.set_command(request); auto [offer, send_ioctl_req, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(ioctl_req, getSysdepsAllocator()), + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -1059,11 +1081,11 @@ int sys_ioctl(int fd, unsigned long request, void *arg, int *result) { } mlibc::infoLogger() << "mlibc: Unexpected ioctl with" - << " type: 0x" << frg::hex_fmt(_IOC_TYPE(request)) - << ", number: 0x" << frg::hex_fmt(_IOC_NR(request)) - << " (raw request: " << frg::hex_fmt(request) << ")" << frg::endlog; + << " type: 0x" << frg::hex_fmt(_IOC_TYPE(request)) << ", number: 0x" + << frg::hex_fmt(_IOC_NR(request)) + << " (raw request: " << frg::hex_fmt(request) << ")" << frg::endlog; __ensure(!"Illegal ioctl request"); __builtin_unreachable(); } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/memory.cpp b/sysdeps/managarm/generic/memory.cpp index 91e47af3e9..5695f0d9b5 100644 --- a/sysdeps/managarm/generic/memory.cpp +++ b/sysdeps/managarm/generic/memory.cpp @@ -2,12 +2,12 @@ #include #include -#include #include +#include #include -#include #include +#include namespace mlibc { @@ -26,5 +26,4 @@ int sys_anon_free(void *pointer, size_t size) { return 0; } -} //namespace mlibc - +} // namespace mlibc diff --git a/sysdeps/managarm/generic/mount.cpp b/sysdeps/managarm/generic/mount.cpp index 5677b20a70..b50b4fa703 100644 --- a/sysdeps/managarm/generic/mount.cpp +++ b/sysdeps/managarm/generic/mount.cpp @@ -3,16 +3,16 @@ #include #include +#include +#include #include #include -#include #include -#include namespace mlibc { -int sys_mount(const char *source, const char *target, - const char *fstype, unsigned long, const void *) { +int +sys_mount(const char *source, const char *target, const char *fstype, unsigned long, const void *) { SignalGuard sguard; managarm::posix::MountRequest req(getSysdepsAllocator()); @@ -20,25 +20,24 @@ int sys_mount(const char *source, const char *target, req.set_target_path(frg::string(getSysdepsAllocator(), target)); req.set_fs_type(frg::string(getSysdepsAllocator(), fstype)); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); HEL_CHECK(send_tail.error()); HEL_CHECK(recv_resp.error()); - auto resp = *bragi::parse_head_only(recv_resp, getSysdepsAllocator()); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) + auto resp = + *bragi::parse_head_only(recv_resp, getSysdepsAllocator()); + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) return ENOENT; __ensure(resp.error() == managarm::posix::Errors::SUCCESS); return 0; } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/net.cpp b/sysdeps/managarm/generic/net.cpp index 5435f09496..010ff59308 100644 --- a/sysdeps/managarm/generic/net.cpp +++ b/sysdeps/managarm/generic/net.cpp @@ -11,7 +11,7 @@ int sys_if_indextoname(unsigned int index, char *name) { int fd = 0; int r = sys_socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, AF_UNSPEC, &fd); - if(r) + if (r) return r; struct ifreq ifr; @@ -21,8 +21,8 @@ int sys_if_indextoname(unsigned int index, char *name) { int ret = sys_ioctl(fd, SIOCGIFNAME, &ifr, &res); close(fd); - if(ret) { - if(ret == ENODEV) + if (ret) { + if (ret == ENODEV) return ENXIO; return ret; } @@ -36,7 +36,7 @@ int sys_if_nametoindex(const char *name, unsigned int *ret) { int fd = 0; int r = sys_socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, AF_UNSPEC, &fd); - if(r) + if (r) return r; struct ifreq ifr; @@ -46,7 +46,7 @@ int sys_if_nametoindex(const char *name, unsigned int *ret) { r = sys_ioctl(fd, SIOCGIFINDEX, &ifr, &res); close(fd); - if(r) + if (r) return r; *ret = ifr.ifr_ifindex; @@ -66,4 +66,4 @@ int sys_getifaddrs(struct ifaddrs **out) { return 0; } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/sched.cpp b/sysdeps/managarm/generic/sched.cpp index bce8db8601..f5f3ee5c5e 100644 --- a/sysdeps/managarm/generic/sched.cpp +++ b/sysdeps/managarm/generic/sched.cpp @@ -1,10 +1,10 @@ #include #include -#include #include -#include +#include #include +#include #include #include @@ -24,15 +24,14 @@ int sys_getthreadaffinity(pid_t tid, size_t cpusetsize, cpu_set_t *mask) { req.set_pid(tid); req.set_size(cpusetsize); - auto [offer, send_head, recv_resp, recv_data] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(mask, cpusetsize) - ) - ); + auto [offer, send_head, recv_resp, recv_data] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(mask, cpusetsize) + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -40,11 +39,12 @@ int sys_getthreadaffinity(pid_t tid, size_t cpusetsize, cpu_set_t *mask) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - } else if(resp.error() != managarm::posix::Errors::SUCCESS) { - mlibc::infoLogger() << "mlibc: got unexpected error from posix in sys_getaffinity!" << frg::endlog; + } else if (resp.error() != managarm::posix::Errors::SUCCESS) { + mlibc::infoLogger() << "mlibc: got unexpected error from posix in sys_getaffinity!" + << frg::endlog; return EIEIO; } HEL_CHECK(recv_data.error()); @@ -67,14 +67,12 @@ int sys_setthreadaffinity(pid_t tid, size_t cpusetsize, const cpu_set_t *mask) { req.set_pid(tid); req.set_mask(affinity_mask); - auto [offer, send_head, send_tail, recv_resp] = - exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) - ); + auto [offer, send_head, send_tail, recv_resp] = exchangeMsgsSync( + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadTail(req, getSysdepsAllocator()), helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_head.error()); @@ -83,11 +81,12 @@ int sys_setthreadaffinity(pid_t tid, size_t cpusetsize, const cpu_set_t *mask) { managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - - if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + + if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; - } else if(resp.error() != managarm::posix::Errors::SUCCESS) { - mlibc::infoLogger() << "mlibc: got unexpected error from posix in sys_getaffinity!" << frg::endlog; + } else if (resp.error() != managarm::posix::Errors::SUCCESS) { + mlibc::infoLogger() << "mlibc: got unexpected error from posix in sys_getaffinity!" + << frg::endlog; return EIEIO; } @@ -99,4 +98,4 @@ int sys_getcpu(int *cpu) { return 0; } -} +} // namespace mlibc diff --git a/sysdeps/managarm/generic/signals.cpp b/sysdeps/managarm/generic/signals.cpp index 634f9917e6..f313887115 100644 --- a/sysdeps/managarm/generic/signals.cpp +++ b/sysdeps/managarm/generic/signals.cpp @@ -1,17 +1,17 @@ #include +#include #include #include #include #include -#include -#include #include +#include -#include +#include #include +#include #include -#include #include #include @@ -26,18 +26,26 @@ namespace mlibc { int sys_sigprocmask(int how, const sigset_t *set, sigset_t *retrieve) { // This implementation is inherently signal-safe. uint64_t former, unused; - if(set) { - HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + posix::superSigMask, how, *reinterpret_cast(set), &former, &unused)); - }else{ - HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + posix::superSigMask, 0, 0, &former, &unused)); + if (set) { + HEL_CHECK(helSyscall2_2( + kHelObserveSuperCall + posix::superSigMask, + how, + *reinterpret_cast(set), + &former, + &unused + )); + } else { + HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + posix::superSigMask, 0, 0, &former, &unused) + ); } - if(retrieve) + if (retrieve) *reinterpret_cast(retrieve) = former; return 0; } -int sys_sigaction(int number, const struct sigaction *__restrict action, - struct sigaction *__restrict saved_action) { +int sys_sigaction( + int number, const struct sigaction *__restrict action, struct sigaction *__restrict saved_action +) { SignalGuard sguard; // TODO: Respect restorer. __ensure(!(action->sa_flags & SA_RESTORER)); @@ -45,13 +53,13 @@ int sys_sigaction(int number, const struct sigaction *__restrict action, managarm::posix::CntRequest req(getSysdepsAllocator()); req.set_request_type(managarm::posix::CntReqType::SIG_ACTION); req.set_sig_number(number); - if(action) { + if (action) { req.set_mode(1); req.set_flags(action->sa_flags); req.set_sig_mask(*reinterpret_cast(&action->sa_mask)); - if(action->sa_flags & SA_SIGINFO) { + if (action->sa_flags & SA_SIGINFO) { req.set_sig_handler(reinterpret_cast(action->sa_sigaction)); - }else{ + } else { req.set_sig_handler(reinterpret_cast(action->sa_handler)); } req.set_sig_restorer(reinterpret_cast(&__mlibc_signal_restore)); @@ -60,10 +68,10 @@ int sys_sigaction(int number, const struct sigaction *__restrict action, } auto [offer, send_req, recv_resp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -72,21 +80,21 @@ int sys_sigaction(int number, const struct sigaction *__restrict action, managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::posix::Errors::ILLEGAL_REQUEST) { + if (resp.error() == managarm::posix::Errors::ILLEGAL_REQUEST) { // This is only returned for servers, not for normal userspace. return ENOSYS; - }else if(resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { + } else if (resp.error() == managarm::posix::Errors::ILLEGAL_ARGUMENTS) { return EINVAL; } __ensure(resp.error() == managarm::posix::Errors::SUCCESS); - if(saved_action) { + if (saved_action) { saved_action->sa_flags = resp.flags(); *reinterpret_cast(&saved_action->sa_mask) = resp.sig_mask(); - if(resp.flags() & SA_SIGINFO) { + if (resp.flags() & SA_SIGINFO) { saved_action->sa_sigaction = - reinterpret_cast(resp.sig_handler()); - }else{ + reinterpret_cast(resp.sig_handler()); + } else { saved_action->sa_handler = reinterpret_cast(resp.sig_handler()); } // TODO: saved_action->sa_restorer = resp.sig_restorer; @@ -100,29 +108,37 @@ int sys_kill(int pid, int number) { return 0; } -int sys_tgkill(int, int tid, int number) { - return sys_kill(tid, number); -} +int sys_tgkill(int, int tid, int number) { return sys_kill(tid, number); } int sys_sigaltstack(const stack_t *ss, stack_t *oss) { HelWord out; // This implementation is inherently signal-safe. - HEL_CHECK(helSyscall2_1(kHelObserveSuperCall + posix::superSigAltStack, - reinterpret_cast(ss), - reinterpret_cast(oss), - &out)); + HEL_CHECK(helSyscall2_1( + kHelObserveSuperCall + posix::superSigAltStack, + reinterpret_cast(ss), + reinterpret_cast(oss), + &out + )); return out; } int sys_sigsuspend(const sigset_t *set) { - //SignalGuard sguard; + // SignalGuard sguard; uint64_t former, seq, unused; - HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + posix::superSigMask, SIG_SETMASK, *reinterpret_cast(set), &former, &seq)); + HEL_CHECK(helSyscall2_2( + kHelObserveSuperCall + posix::superSigMask, + SIG_SETMASK, + *reinterpret_cast(set), + &former, + &seq + )); HEL_CHECK(helSyscall1(kHelObserveSuperCall + posix::superSigSuspend, seq)); - HEL_CHECK(helSyscall2_2(kHelObserveSuperCall + posix::superSigMask, SIG_SETMASK, former, &unused, &unused)); + HEL_CHECK(helSyscall2_2( + kHelObserveSuperCall + posix::superSigMask, SIG_SETMASK, former, &unused, &unused + )); return EINTR; } @@ -136,4 +152,4 @@ int sys_sigpending(sigset_t *set) { return 0; } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/socket.cpp b/sysdeps/managarm/generic/socket.cpp index 4121bd5b99..ea93fa830c 100644 --- a/sysdeps/managarm/generic/socket.cpp +++ b/sysdeps/managarm/generic/socket.cpp @@ -1,18 +1,18 @@ #include #include #include -#include #include -#include #include -#include +#include #include +#include +#include +#include +#include #include #include #include -#include -#include #include namespace { @@ -20,7 +20,7 @@ namespace { int fcntl_helper(int fd, int request, int *result, ...) { va_list args; va_start(args, result); - if(!mlibc::sys_fcntl) { + if (!mlibc::sys_fcntl) { return ENOSYS; } int ret = mlibc::sys_fcntl(fd, request, args, result); @@ -28,7 +28,7 @@ int fcntl_helper(int fd, int request, int *result, ...) { return ret; } -} +} // namespace namespace mlibc { @@ -39,11 +39,10 @@ int sys_accept(int fd, int *newfd, struct sockaddr *addr_ptr, socklen_t *addr_le req.set_fd(fd); auto [offer, sendReq, recvResp] = exchangeMsgsSync( - getPosixLane(), - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline() - ) + getPosixLane(), + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); @@ -52,27 +51,27 @@ int sys_accept(int fd, int *newfd, struct sockaddr *addr_ptr, socklen_t *addr_le managarm::posix::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::posix::Errors::WOULD_BLOCK) { + if (resp.error() == managarm::posix::Errors::WOULD_BLOCK) { return EWOULDBLOCK; - }else{ + } else { __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *newfd = resp.fd(); } - if(addr_ptr && addr_length) { - if(int e = mlibc::sys_peername(*newfd, addr_ptr, *addr_length, addr_length); e) { + if (addr_ptr && addr_length) { + if (int e = mlibc::sys_peername(*newfd, addr_ptr, *addr_length, addr_length); e) { errno = e; return -1; } } - if(flags & SOCK_NONBLOCK) { + if (flags & SOCK_NONBLOCK) { int fcntl_ret = 0; fcntl_helper(*newfd, F_GETFL, &fcntl_ret); fcntl_helper(*newfd, F_SETFL, &fcntl_ret, fcntl_ret | O_NONBLOCK); } - if(flags & SOCK_CLOEXEC) { + if (flags & SOCK_CLOEXEC) { int fcntl_ret = 0; fcntl_helper(*newfd, F_GETFD, &fcntl_ret); fcntl_helper(*newfd, F_SETFD, &fcntl_ret, fcntl_ret | FD_CLOEXEC); @@ -91,12 +90,13 @@ int sys_bind(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length) { req.set_req_type(managarm::fs::CntReqType::PT_BIND); auto [offer, send_req, send_creds, send_buf, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::imbueCredentials(), - helix_ng::sendBuffer(addr_ptr, addr_length), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::imbueCredentials(), + helix_ng::sendBuffer(addr_ptr, addr_length), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -106,19 +106,19 @@ int sys_bind(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length) { managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::fs::Errors::FILE_NOT_FOUND) { return ENOENT; - } else if(resp.error() == managarm::fs::Errors::ADDRESS_IN_USE) { + } else if (resp.error() == managarm::fs::Errors::ADDRESS_IN_USE) { return EADDRINUSE; - } else if(resp.error() == managarm::fs::Errors::ALREADY_EXISTS) { + } else if (resp.error() == managarm::fs::Errors::ALREADY_EXISTS) { return EINVAL; - } else if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return EINVAL; - } else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - } else if(resp.error() == managarm::fs::Errors::ACCESS_DENIED) { + } else if (resp.error() == managarm::fs::Errors::ACCESS_DENIED) { return EACCES; - } else if(resp.error() == managarm::fs::Errors::ADDRESS_NOT_AVAILABLE) { + } else if (resp.error() == managarm::fs::Errors::ADDRESS_NOT_AVAILABLE) { return EADDRNOTAVAIL; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -138,16 +138,15 @@ int sys_connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length) frg::string ser(getSysdepsAllocator()); req.SerializeToString(&ser); - auto [offer, send_req, imbue_creds, send_addr, recv_resp] = - exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::imbueCredentials(), - helix_ng::sendBuffer(const_cast(addr_ptr), addr_length), - helix_ng::recvInline() - ) - ); + auto [offer, send_req, imbue_creds, send_addr, recv_resp] = exchangeMsgsSync( + handle, + helix_ng::offer( + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::imbueCredentials(), + helix_ng::sendBuffer(const_cast(addr_ptr), addr_length), + helix_ng::recvInline() + ) + ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -157,11 +156,11 @@ int sys_connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length) managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::FILE_NOT_FOUND) { + if (resp.error() == managarm::fs::Errors::FILE_NOT_FOUND) { return ENOENT; - } else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { + } else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) { return EINVAL; - } else if(resp.error() == managarm::fs::Errors::CONNECTION_REFUSED) { + } else if (resp.error() == managarm::fs::Errors::CONNECTION_REFUSED) { return ECONNREFUSED; } @@ -169,8 +168,9 @@ int sys_connect(int fd, const struct sockaddr *addr_ptr, socklen_t addr_length) return 0; } -int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, - socklen_t *actual_length) { +int sys_sockname( + int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, socklen_t *actual_length +) { SignalGuard sguard; auto handle = getHandleForFd(fd); @@ -183,11 +183,12 @@ int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, req.set_size(max_addr_length); auto [offer, send_req, recv_resp, recv_addr] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline(), - helix_ng::recvBuffer(addr_ptr, max_addr_length)) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::recvInline(), + helix_ng::recvBuffer(addr_ptr, max_addr_length) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -195,7 +196,7 @@ int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return ENOTSOCK; } __ensure(resp.error() == managarm::fs::Errors::SUCCESS); @@ -204,8 +205,9 @@ int sys_sockname(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, return 0; } -int sys_peername(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, - socklen_t *actual_length) { +int sys_peername( + int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, socklen_t *actual_length +) { SignalGuard sguard; auto handle = getHandleForFd(fd); @@ -221,40 +223,40 @@ int sys_peername(int fd, struct sockaddr *addr_ptr, socklen_t max_addr_length, req.SerializeToString(&ser); auto [offer, sendReq, recvResp, recvData] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::recvInline(), - helix_ng::recvBuffer(addr_ptr, max_addr_length) - ) + handle, + helix_ng::offer( + helix_ng::sendBuffer(ser.data(), ser.size()), + helix_ng::recvInline(), + helix_ng::recvBuffer(addr_ptr, max_addr_length) + ) ); HEL_CHECK(offer.error()); HEL_CHECK(sendReq.error()); - if(recvResp.error() == kHelErrDismissed) + if (recvResp.error() == kHelErrDismissed) return ENOTSOCK; HEL_CHECK(recvResp.error()); HEL_CHECK(recvData.error()); managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recvResp.data(), recvResp.length()); - if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { + if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) { return ENOTSOCK; - }else if(resp.error() == managarm::fs::Errors::NOT_CONNECTED) { + } else if (resp.error() == managarm::fs::Errors::NOT_CONNECTED) { return ENOTCONN; - }else{ + } else { __ensure(resp.error() == managarm::fs::Errors::SUCCESS); *actual_length = resp.file_size(); return 0; } } -int sys_getsockopt(int fd, int layer, int number, - void *__restrict buffer, socklen_t *__restrict size) { +int +sys_getsockopt(int fd, int layer, int number, void *__restrict buffer, socklen_t *__restrict size) { SignalGuard sguard; - if(layer == SOL_SOCKET && number == SO_PEERCRED) { - if(*size != sizeof(struct ucred)) + if (layer == SOL_SOCKET && number == SO_PEERCRED) { + if (*size != sizeof(struct ucred)) return EINVAL; auto handle = getHandleForFd(fd); @@ -266,10 +268,10 @@ int sys_getsockopt(int fd, int layer, int number, req.set_command(SO_PEERCRED); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -285,44 +287,63 @@ int sys_getsockopt(int fd, int layer, int number, creds.gid = resp.gid(); memcpy(buffer, &creds, sizeof(struct ucred)); return 0; - }else if(layer == SOL_SOCKET && number == SO_SNDBUF) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_SNDBUF is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_SNDBUF) { + mlibc::infoLogger( + ) << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_SNDBUF is unimplemented\e[39m" + << frg::endlog; *(int *)buffer = 4096; return 0; - }else if(layer == SOL_SOCKET && number == SO_RCVBUF) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_RCVBUF is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_RCVBUF) { + mlibc::infoLogger( + ) << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_RCVBUF is unimplemented\e[39m" + << frg::endlog; *(int *)buffer = 4096; return 0; - }else if(layer == SOL_SOCKET && number == SO_TYPE) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_TYPE is unimplemented, hardcoding SOCK_STREAM\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_TYPE) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_TYPE is " + "unimplemented, hardcoding SOCK_STREAM\e[39m" + << frg::endlog; *(int *)buffer = SOCK_STREAM; return 0; - }else if(layer == SOL_SOCKET && number == SO_ERROR) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_ERROR is unimplemented, hardcoding 0\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_ERROR) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_ERROR is " + "unimplemented, hardcoding 0\e[39m" + << frg::endlog; *(int *)buffer = 0; return 0; - }else if(layer == SOL_SOCKET && number == SO_KEEPALIVE) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_KEEPALIVE is unimplemented, hardcoding 0\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_KEEPALIVE) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_KEEPALIVE is " + "unimplemented, hardcoding 0\e[39m" + << frg::endlog; *(int *)buffer = 0; return 0; - }else if(layer == SOL_SOCKET && number == SO_LINGER) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_LINGER is unimplemented, hardcoding 0\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_LINGER) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_LINGER is " + "unimplemented, hardcoding 0\e[39m" + << frg::endlog; *(int *)buffer = 0; return 0; - }else if(layer == SOL_SOCKET && number == SO_PEERSEC) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_PEERSEC is unimplemented, hardcoding 0\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_PEERSEC) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_PEERSEC is " + "unimplemented, hardcoding 0\e[39m" + << frg::endlog; *(int *)buffer = 0; return 0; - }else if(layer == SOL_SOCKET && number == SO_PEERGROUPS) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_PEERGROUPS is unimplemented, hardcoding 0\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_PEERGROUPS) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_PEERGROUPS " + "is unimplemented, hardcoding 0\e[39m" + << frg::endlog; *(int *)buffer = 0; return 0; - }else if(layer == SOL_SOCKET && number == SO_ACCEPTCONN) { - mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_ACCEPTCONN is unimplemented, hardcoding 1\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_ACCEPTCONN) { + mlibc::infoLogger() << "\e[31mmlibc: getsockopt() call with SOL_SOCKET and SO_ACCEPTCONN " + "is unimplemented, hardcoding 1\e[39m" + << frg::endlog; *(int *)buffer = 1; return 0; - }else{ - mlibc::panicLogger() << "\e[31mmlibc: Unexpected getsockopt() call, layer: " << layer << " number: " << number << "\e[39m" << frg::endlog; + } else { + mlibc::panicLogger() << "\e[31mmlibc: Unexpected getsockopt() call, layer: " << layer + << " number: " << number << "\e[39m" << frg::endlog; __builtin_unreachable(); } } @@ -330,32 +351,31 @@ int sys_getsockopt(int fd, int layer, int number, namespace { std::array, 5> setsockopt_readonly = {{ - { SOL_SOCKET, SO_ACCEPTCONN }, - { SOL_SOCKET, SO_DOMAIN }, - { SOL_SOCKET, SO_ERROR }, - { SOL_SOCKET, SO_PROTOCOL }, - { SOL_SOCKET, SO_TYPE }, + {SOL_SOCKET, SO_ACCEPTCONN}, + {SOL_SOCKET, SO_DOMAIN}, + {SOL_SOCKET, SO_ERROR}, + {SOL_SOCKET, SO_PROTOCOL}, + {SOL_SOCKET, SO_TYPE}, }}; std::array, 5> setsockopt_passthrough = {{ - { SOL_PACKET, PACKET_AUXDATA }, - { SOL_SOCKET, SO_LOCK_FILTER }, - { SOL_SOCKET, SO_BINDTODEVICE }, - { SOL_IP, IP_PKTINFO }, - { SOL_NETLINK, NETLINK_ADD_MEMBERSHIP }, + {SOL_PACKET, PACKET_AUXDATA}, + {SOL_SOCKET, SO_LOCK_FILTER}, + {SOL_SOCKET, SO_BINDTODEVICE}, + {SOL_IP, IP_PKTINFO}, + {SOL_NETLINK, NETLINK_ADD_MEMBERSHIP}, }}; std::array, 2> setsockopt_passthrough_noopt = {{ - { SOL_SOCKET, SO_DETACH_FILTER }, + {SOL_SOCKET, SO_DETACH_FILTER}, }}; -} +} // namespace -int sys_setsockopt(int fd, int layer, int number, - const void *buffer, socklen_t size) { +int sys_setsockopt(int fd, int layer, int number, const void *buffer, socklen_t size) { SignalGuard sguard; - if(layer == SOL_SOCKET && number == SO_PASSCRED) { + if (layer == SOL_SOCKET && number == SO_PASSCRED) { int value; __ensure(size == sizeof(int)); memcpy(&value, buffer, sizeof(int)); @@ -370,10 +390,10 @@ int sys_setsockopt(int fd, int layer, int number, req.set_value(value); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -383,9 +403,13 @@ int sys_setsockopt(int fd, int layer, int number, resp.ParseFromArray(recv_resp.data(), recv_resp.length()); __ensure(resp.error() == managarm::fs::Errors::SUCCESS); return 0; - }else if(std::find(setsockopt_passthrough.begin(), setsockopt_passthrough.end(), std::pair{layer, number}) != setsockopt_passthrough.end()) { + } else if (std::find( + setsockopt_passthrough.begin(), + setsockopt_passthrough.end(), + std::pair{layer, number} + ) != setsockopt_passthrough.end()) { auto handle = getHandleForFd(fd); - if(!handle) + if (!handle) return EBADF; managarm::fs::SetSockOpt req(getSysdepsAllocator()); @@ -394,11 +418,12 @@ int sys_setsockopt(int fd, int layer, int number, req.set_optlen(size); auto [offer, send_req, send_buf, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::sendBuffer(buffer, size), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::sendBuffer(buffer, size), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -407,19 +432,23 @@ int sys_setsockopt(int fd, int layer, int number, managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::SUCCESS) + if (resp.error() == managarm::fs::Errors::SUCCESS) return 0; - else if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) + else if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) return EINVAL; - else if(resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) + else if (resp.error() == managarm::fs::Errors::ILLEGAL_ARGUMENT) return EINVAL; - else if(resp.error() == managarm::fs::Errors::INVALID_PROTOCOL_OPTION) + else if (resp.error() == managarm::fs::Errors::INVALID_PROTOCOL_OPTION) return ENOPROTOOPT; else __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - }else if(std::find(setsockopt_passthrough_noopt.begin(), setsockopt_passthrough_noopt.end(), std::pair{layer, number}) != setsockopt_passthrough_noopt.end()) { + } else if (std::find( + setsockopt_passthrough_noopt.begin(), + setsockopt_passthrough_noopt.end(), + std::pair{layer, number} + ) != setsockopt_passthrough_noopt.end()) { auto handle = getHandleForFd(fd); - if(!handle) + if (!handle) return EBADF; managarm::fs::SetSockOpt req(getSysdepsAllocator()); @@ -428,10 +457,10 @@ int sys_setsockopt(int fd, int layer, int number, req.set_optlen(0); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -439,21 +468,25 @@ int sys_setsockopt(int fd, int layer, int number, managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::SUCCESS) + if (resp.error() == managarm::fs::Errors::SUCCESS) return 0; - else if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) + else if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) return EINVAL; else __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - }else if(std::find(setsockopt_readonly.begin(), setsockopt_readonly.end(), std::pair{layer, number}) != setsockopt_readonly.end()) { + } else if (std::find( + setsockopt_readonly.begin(), + setsockopt_readonly.end(), + std::pair{layer, number} + ) != setsockopt_readonly.end()) { // this is purely read-only return ENOPROTOOPT; - }else if(layer == SOL_SOCKET && number == SO_ATTACH_FILTER) { + } else if (layer == SOL_SOCKET && number == SO_ATTACH_FILTER) { auto handle = getHandleForFd(fd); - if(!handle) + if (!handle) return EBADF; - if(size != sizeof(sock_fprog)) + if (size != sizeof(sock_fprog)) return EINVAL; auto fprog = reinterpret_cast(buffer); @@ -464,11 +497,12 @@ int sys_setsockopt(int fd, int layer, int number, req.set_optlen(fprog->len * sizeof(*fprog->filter)); auto [offer, send_req, send_buf, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), - helix_ng::sendBuffer(fprog->filter, req.optlen()), - helix_ng::recvInline()) + handle, + helix_ng::offer( + helix_ng::sendBragiHeadOnly(req, getSysdepsAllocator()), + helix_ng::sendBuffer(fprog->filter, req.optlen()), + helix_ng::recvInline() + ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); @@ -477,66 +511,100 @@ int sys_setsockopt(int fd, int layer, int number, managarm::fs::SvrResponse resp(getSysdepsAllocator()); resp.ParseFromArray(recv_resp.data(), recv_resp.length()); - if(resp.error() == managarm::fs::Errors::SUCCESS) + if (resp.error() == managarm::fs::Errors::SUCCESS) return 0; - else if(resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) + else if (resp.error() == managarm::fs::Errors::ILLEGAL_OPERATION_TARGET) return EINVAL; else __ensure(resp.error() == managarm::fs::Errors::SUCCESS); - }else if(layer == SOL_SOCKET && number == SO_RCVBUFFORCE) { + } else if (layer == SOL_SOCKET && number == SO_RCVBUFFORCE) { mlibc::infoLogger() << "\e[31mmlibc: setsockopt(SO_RCVBUFFORCE) is not implemented" - " correctly\e[39m" << frg::endlog; + " correctly\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_SNDBUF) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_SNDBUF is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_SNDBUF) { + mlibc::infoLogger( + ) << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_SNDBUF is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_SNDBUFFORCE) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_SNDBUFFORCE is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_SNDBUFFORCE) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_SNDBUFFORCE " + "is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_KEEPALIVE) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_KEEPALIVE is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_KEEPALIVE) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_KEEPALIVE is " + "unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_REUSEADDR) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_REUSEADDR is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_REUSEADDR) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_REUSEADDR is " + "unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_REUSEPORT) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_REUSEPORT is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_REUSEPORT) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_REUSEPORT is " + "unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_RCVBUF) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_RCVBUF is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_RCVBUF) { + mlibc::infoLogger( + ) << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_RCVBUF is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == IPPROTO_TCP && number == TCP_NODELAY) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_NODELAY is unimplemented\e[39m" << frg::endlog; + } else if (layer == IPPROTO_TCP && number == TCP_NODELAY) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_NODELAY is " + "unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == IPPROTO_TCP && number == TCP_KEEPIDLE) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_KEEPIDLE is unimplemented\e[39m" << frg::endlog; + } else if (layer == IPPROTO_TCP && number == TCP_KEEPIDLE) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_KEEPIDLE " + "is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_NETLINK && number == NETLINK_BROADCAST_ERROR) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_NETLINK and NETLINK_BROADCAST_ERROR is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_NETLINK && number == NETLINK_BROADCAST_ERROR) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_NETLINK and " + "NETLINK_BROADCAST_ERROR is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_NETLINK && number == NETLINK_EXT_ACK) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_NETLINK and NETLINK_EXT_ACK is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_NETLINK && number == NETLINK_EXT_ACK) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_NETLINK and " + "NETLINK_EXT_ACK is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_NETLINK && number == NETLINK_GET_STRICT_CHK) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_NETLINK and NETLINK_EXT_ACK is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_NETLINK && number == NETLINK_GET_STRICT_CHK) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_NETLINK and " + "NETLINK_EXT_ACK is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == IPPROTO_TCP && number == TCP_KEEPINTVL) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_KEEPINTVL is unimplemented\e[39m" << frg::endlog; + } else if (layer == IPPROTO_TCP && number == TCP_KEEPINTVL) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_KEEPINTVL " + "is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == IPPROTO_TCP && number == TCP_KEEPCNT) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_KEEPCNT is unimplemented\e[39m" << frg::endlog; + } else if (layer == IPPROTO_TCP && number == TCP_KEEPCNT) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with IPPROTO_TCP and TCP_KEEPCNT is " + "unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_SNDTIMEO) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_SNDTIMEO is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_SNDTIMEO) { + mlibc::infoLogger( + ) << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_SNDTIMEO is unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_OOBINLINE) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_OOBINLINE is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_OOBINLINE) { + mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_OOBINLINE is " + "unimplemented\e[39m" + << frg::endlog; return 0; - }else if(layer == SOL_SOCKET && number == SO_PRIORITY) { - mlibc::infoLogger() << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_PRIORITY is unimplemented\e[39m" << frg::endlog; + } else if (layer == SOL_SOCKET && number == SO_PRIORITY) { + mlibc::infoLogger( + ) << "\e[31mmlibc: setsockopt() call with SOL_SOCKET and SO_PRIORITY is unimplemented\e[39m" + << frg::endlog; return 0; - }else{ - mlibc::panicLogger() << "\e[31mmlibc: Unexpected setsockopt() call, layer: " << layer << " number: " << number << "\e[39m" << frg::endlog; + } else { + mlibc::panicLogger() << "\e[31mmlibc: Unexpected setsockopt() call, layer: " << layer + << " number: " << number << "\e[39m" << frg::endlog; __builtin_unreachable(); } } @@ -555,11 +623,8 @@ int sys_listen(int fd, int) { req.SerializeToString(&ser); auto [offer, send_req, recv_resp] = exchangeMsgsSync( - handle, - helix_ng::offer( - helix_ng::sendBuffer(ser.data(), ser.size()), - helix_ng::recvInline() - ) + handle, + helix_ng::offer(helix_ng::sendBuffer(ser.data(), ser.size()), helix_ng::recvInline()) ); HEL_CHECK(offer.error()); @@ -572,4 +637,4 @@ int sys_listen(int fd, int) { return 0; } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/managarm/generic/time.cpp b/sysdeps/managarm/generic/time.cpp index 468a738b9b..6727189c14 100644 --- a/sysdeps/managarm/generic/time.cpp +++ b/sysdeps/managarm/generic/time.cpp @@ -1,15 +1,15 @@ #include -#include #include #include +#include -#include #include -#include +#include +#include #include +#include #include -#include struct TrackerPage { uint64_t seqlock; @@ -25,12 +25,13 @@ namespace mlibc { int sys_clock_get(int clock, time_t *secs, long *nanos) { // This implementation is inherently signal-safe. - if(clock == CLOCK_MONOTONIC || clock == CLOCK_MONOTONIC_RAW || clock == CLOCK_MONOTONIC_COARSE) { + if (clock == CLOCK_MONOTONIC || clock == CLOCK_MONOTONIC_RAW || + clock == CLOCK_MONOTONIC_COARSE) { uint64_t tick; HEL_CHECK(helGetClock(&tick)); *secs = tick / 1000000000; *nanos = tick % 1000000000; - }else if(clock == CLOCK_REALTIME) { + } else if (clock == CLOCK_REALTIME) { cacheFileTable(); // Start the seqlock read. @@ -48,22 +49,26 @@ int sys_clock_get(int clock, time_t *secs, long *nanos) { // Calculate the current time. uint64_t tick; HEL_CHECK(helGetClock(&tick)); - __ensure(tick >= (uint64_t)__mlibc_clk_tracker_page->refClock); // TODO: Respect the seqlock! + __ensure( + tick >= (uint64_t)__mlibc_clk_tracker_page->refClock + ); // TODO: Respect the seqlock! tick -= ref; tick += base; *secs = tick / 1000000000; *nanos = tick % 1000000000; - }else if(clock == CLOCK_PROCESS_CPUTIME_ID) { + } else if (clock == CLOCK_PROCESS_CPUTIME_ID) { mlibc::infoLogger() << "\e[31mmlibc: clock_gettime does not support the CPU time clocks" - "\e[39m" << frg::endlog; + "\e[39m" + << frg::endlog; *secs = 0; *nanos = 0; - }else if(clock == CLOCK_BOOTTIME) { + } else if (clock == CLOCK_BOOTTIME) { mlibc::infoLogger() << "\e[31mmlibc: clock_gettime does not support CLOCK_BOOTTIME" - "\e[39m" << frg::endlog; + "\e[39m" + << frg::endlog; *secs = 0; *nanos = 0; - }else{ + } else { mlibc::panicLogger() << "mlibc: Unexpected clock " << clock << frg::endlog; } return 0; @@ -77,5 +82,4 @@ int sys_clock_getres(int clock, time_t *secs, long *nanos) { return 0; } -} //namespace mlibc - +} // namespace mlibc diff --git a/sysdeps/managarm/include/mlibc/posix-pipe.hpp b/sysdeps/managarm/include/mlibc/posix-pipe.hpp index 4bcf1cba2c..c0040fbbcb 100644 --- a/sysdeps/managarm/include/mlibc/posix-pipe.hpp +++ b/sysdeps/managarm/include/mlibc/posix-pipe.hpp @@ -1,13 +1,13 @@ #ifndef MLIBC_POSIX_PIPE #define MLIBC_POSIX_PIPE +#include #include #include #include -#include -#include #include +#include struct SignalGuard { SignalGuard(); @@ -16,7 +16,7 @@ struct SignalGuard { ~SignalGuard(); - SignalGuard &operator= (const SignalGuard &) = delete; + SignalGuard &operator=(const SignalGuard &) = delete; }; // We need an allocator for message structs in sysdeps functions; the "normal" mlibc @@ -33,54 +33,46 @@ struct ElementHandle { swap(u._data, v._data); } - ElementHandle() - : _queue{nullptr}, _n{-1}, _data{nullptr} { } + ElementHandle() : _queue{nullptr}, _n{-1}, _data{nullptr} {} - ElementHandle(Queue *queue, int n, void *data) - : _queue{queue}, _n{n}, _data{data} { } + ElementHandle(Queue *queue, int n, void *data) : _queue{queue}, _n{n}, _data{data} {} ElementHandle(const ElementHandle &other); - ElementHandle(ElementHandle &&other) - : ElementHandle{} { - swap(*this, other); - } + ElementHandle(ElementHandle &&other) : ElementHandle{} { swap(*this, other); } ~ElementHandle(); - ElementHandle &operator= (ElementHandle other) { + ElementHandle &operator=(ElementHandle other) { swap(*this, other); return *this; } - void *data() { - return _data; - } + void *data() { return _data; } - void advance(size_t size) { - _data = reinterpret_cast(_data) + size; - } + void advance(size_t size) { _data = reinterpret_cast(_data) + size; } -private: + private: Queue *_queue; int _n; void *_data; }; struct Queue { - Queue() - : _handle{kHelNullHandle} { + Queue() : _handle{kHelNullHandle} { // We do not need to protect those allocations against signals as this constructor // is only called during library initialization. - _chunks[0] = reinterpret_cast(getSysdepsAllocator().allocate(sizeof(HelChunk) + 4096)); - _chunks[1] = reinterpret_cast(getSysdepsAllocator().allocate(sizeof(HelChunk) + 4096)); + _chunks[0] = + reinterpret_cast(getSysdepsAllocator().allocate(sizeof(HelChunk) + 4096)); + _chunks[1] = + reinterpret_cast(getSysdepsAllocator().allocate(sizeof(HelChunk) + 4096)); recreateQueue(); } Queue(const Queue &) = delete; - Queue &operator= (const Queue &) = delete; + Queue &operator=(const Queue &) = delete; void recreateQueue() { // Reset the internal queue state. @@ -89,12 +81,7 @@ struct Queue { _lastProgress = 0; // Setup the queue header. - HelQueueParameters params { - .flags = 0, - .ringShift = 1, - .numChunks = 2, - .chunkSize = 4096 - }; + HelQueueParameters params{.flags = 0, .ringShift = 1, .numChunks = 2, .chunkSize = 4096}; HEL_CHECK(helCreateQueue(¶ms, &_handle)); auto chunksOffset = (sizeof(HelQueue) + (sizeof(int) << 1) + 63) & ~size_t(63); @@ -102,13 +89,19 @@ struct Queue { auto overallSize = chunksOffset + params.numChunks * reservedPerChunk; void *mapping; - HEL_CHECK(helMapMemory(_handle, kHelNullHandle, nullptr, - 0, (overallSize + 0xFFF) & ~size_t(0xFFF), - kHelMapProtRead | kHelMapProtWrite, &mapping)); + HEL_CHECK(helMapMemory( + _handle, + kHelNullHandle, + nullptr, + 0, + (overallSize + 0xFFF) & ~size_t(0xFFF), + kHelMapProtRead | kHelMapProtWrite, + &mapping + )); _queue = reinterpret_cast(mapping); auto chunksPtr = reinterpret_cast(mapping) + chunksOffset; - for(unsigned int i = 0; i < 2; ++i) + for (unsigned int i = 0; i < 2; ++i) _chunks[i] = reinterpret_cast(chunksPtr + i * reservedPerChunk); // Reset and enqueue the chunks. @@ -124,14 +117,12 @@ struct Queue { _wakeHeadFutex(); } - HelHandle getQueue() { - return _handle; - } + HelHandle getQueue() { return _handle; } + + void trim() {} - void trim() { } - ElementHandle dequeueSingle() { - while(true) { + while (true) { __ensure(_retrieveIndex != _nextIndex); bool done; @@ -140,7 +131,7 @@ struct Queue { auto n = _numberOf(_retrieveIndex); __ensure(_refCount[n]); - if(done) { + if (done) { retire(n); _lastProgress = 0; @@ -159,7 +150,7 @@ struct Queue { void retire(int n) { __ensure(_refCount[n]); - if(_refCount[n]-- > 1) + if (_refCount[n]-- > 1) return; // Reset and enqueue the chunk again. @@ -171,54 +162,54 @@ struct Queue { _wakeHeadFutex(); } - void reference(int n) { - _refCount[n]++; - } + void reference(int n) { _refCount[n]++; } -private: - int _numberOf(int index) { - return _queue->indexQueue[index & 1]; - } + private: + int _numberOf(int index) { return _queue->indexQueue[index & 1]; } - HelChunk *_retrieveChunk() { - return _chunks[_numberOf(_retrieveIndex)]; - } + HelChunk *_retrieveChunk() { return _chunks[_numberOf(_retrieveIndex)]; } void _wakeHeadFutex() { auto futex = __atomic_exchange_n(&_queue->headFutex, _nextIndex, __ATOMIC_RELEASE); - if(futex & kHelHeadWaiters) + if (futex & kHelHeadWaiters) HEL_CHECK(helFutexWake(&_queue->headFutex)); } void _waitProgressFutex(bool *done) { - while(true) { + while (true) { auto futex = __atomic_load_n(&_retrieveChunk()->progressFutex, __ATOMIC_ACQUIRE); __ensure(!(futex & ~(kHelProgressMask | kHelProgressWaiters | kHelProgressDone))); do { - if(_lastProgress != (futex & kHelProgressMask)) { + if (_lastProgress != (futex & kHelProgressMask)) { *done = false; return; - }else if(futex & kHelProgressDone) { + } else if (futex & kHelProgressDone) { *done = true; return; } - if(futex & kHelProgressWaiters) + if (futex & kHelProgressWaiters) break; // Waiters bit is already set (in a previous iteration). - } while(!__atomic_compare_exchange_n(&_retrieveChunk()->progressFutex, &futex, - _lastProgress | kHelProgressWaiters, - false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)); - - HEL_CHECK(helFutexWait(&_retrieveChunk()->progressFutex, - _lastProgress | kHelProgressWaiters, -1)); + } while (!__atomic_compare_exchange_n( + &_retrieveChunk()->progressFutex, + &futex, + _lastProgress | kHelProgressWaiters, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )); + + HEL_CHECK(helFutexWait( + &_retrieveChunk()->progressFutex, _lastProgress | kHelProgressWaiters, -1 + )); } } -private: + private: HelHandle _handle; HelQueue *_queue; HelChunk *_chunks[2]; - + // Index of the chunk that we are currently retrieving/inserting next. int _retrieveIndex; int _nextIndex; @@ -231,7 +222,7 @@ struct Queue { }; inline ElementHandle::~ElementHandle() { - if(_queue) + if (_queue) _queue->retire(_n); } @@ -243,7 +234,6 @@ inline ElementHandle::ElementHandle(const ElementHandle &other) { _queue->reference(_n); } - inline HelSimpleResult *parseSimple(ElementHandle &element) { auto result = reinterpret_cast(element.data()); element.advance(sizeof(HelSimpleResult)); @@ -278,23 +268,22 @@ extern thread_local Queue globalQueue; // This include is here because it needs ElementHandle to be declared #include -template -auto exchangeMsgsSync(HelHandle descriptor, Args &&...args) { +template auto exchangeMsgsSync(HelHandle descriptor, Args &&...args) { auto results = helix_ng::createResultsTuple(args...); auto actions = helix_ng::chainActionArrays(args...); - HEL_CHECK(helSubmitAsync(descriptor, actions.data(), - actions.size(), globalQueue.getQueue(), 0, 0)); + HEL_CHECK( + helSubmitAsync(descriptor, actions.data(), actions.size(), globalQueue.getQueue(), 0, 0) + ); auto element = globalQueue.dequeueSingle(); void *ptr = element.data(); - [&](std::index_sequence) { + [&](std::index_sequence) { (results.template get

().parse(ptr, element), ...); - } (std::make_index_sequence>{}); + }(std::make_index_sequence>{}); return results; } - #endif // MLIBC_POSIX_PIPE diff --git a/sysdeps/managarm/include/mlibc/thread-entry.hpp b/sysdeps/managarm/include/mlibc/thread-entry.hpp index 2dd88a6461..0154307c4a 100644 --- a/sysdeps/managarm/include/mlibc/thread-entry.hpp +++ b/sysdeps/managarm/include/mlibc/thread-entry.hpp @@ -6,5 +6,5 @@ extern "C" void __mlibc_start_thread(void); extern "C" void __mlibc_enter_thread(void *entry, void *user_arg, Tcb *tcb); namespace mlibc { - void *prepare_stack(void *entry, void *user_arg, void *tcb); +void *prepare_stack(void *entry, void *user_arg, void *tcb); } diff --git a/sysdeps/managarm/rtld-generic/support.cpp b/sysdeps/managarm/rtld-generic/support.cpp index 895bc3ee74..9c9d488680 100644 --- a/sysdeps/managarm/rtld-generic/support.cpp +++ b/sysdeps/managarm/rtld-generic/support.cpp @@ -1,17 +1,17 @@ +#include #include #include #include -#include #include #include -#include #include +#include -#include +#include #include +#include #include -#include #include #include @@ -24,17 +24,18 @@ HelHandle posixLane; HelHandle *fileTable; void cacheFileTable() { - if(fileTable) + if (fileTable) return; posix::ManagarmProcessData data; - HEL_CHECK(helSyscall1(kHelCallSuper + posix::superGetProcessData, reinterpret_cast(&data))); + HEL_CHECK( + helSyscall1(kHelCallSuper + posix::superGetProcessData, reinterpret_cast(&data)) + ); posixLane = data.posixLane; fileTable = data.fileTable; } -template -T load(void *ptr) { +template T load(void *ptr) { T result; memcpy(&result, ptr, sizeof(T)); return result; @@ -43,14 +44,8 @@ T load(void *ptr) { // This Queue implementation is more simplistic than the ones in mlibc and helix. // In fact, we only manage a single chunk; this minimizes the memory usage of the queue. struct Queue { - Queue() - : _handle{kHelNullHandle}, _lastProgress(0) { - HelQueueParameters params { - .flags = 0, - .ringShift = 0, - .numChunks = 1, - .chunkSize = 4096 - }; + Queue() : _handle{kHelNullHandle}, _lastProgress(0) { + HelQueueParameters params{.flags = 0, .ringShift = 0, .numChunks = 1, .chunkSize = 4096}; HEL_CHECK(helCreateQueue(¶ms, &_handle)); auto chunksOffset = (sizeof(HelQueue) + (sizeof(int) << 0) + 63) & ~size_t(63); @@ -58,13 +53,19 @@ struct Queue { auto overallSize = chunksOffset + params.numChunks * reservedPerChunk; void *mapping; - HEL_CHECK(helMapMemory(_handle, kHelNullHandle, nullptr, - 0, (overallSize + 0xFFF) & ~size_t(0xFFF), - kHelMapProtRead | kHelMapProtWrite, &mapping)); + HEL_CHECK(helMapMemory( + _handle, + kHelNullHandle, + nullptr, + 0, + (overallSize + 0xFFF) & ~size_t(0xFFF), + kHelMapProtRead | kHelMapProtWrite, + &mapping + )); _queue = reinterpret_cast(mapping); - _chunk = reinterpret_cast( - reinterpret_cast(mapping) + chunksOffset); + _chunk = + reinterpret_cast(reinterpret_cast(mapping) + chunksOffset); // Reset and enqueue the first chunk. _chunk->progressFutex = 0; @@ -77,17 +78,15 @@ struct Queue { Queue(const Queue &) = delete; - Queue &operator= (const Queue &) = delete; + Queue &operator=(const Queue &) = delete; - HelHandle getHandle() { - return _handle; - } + HelHandle getHandle() { return _handle; } void *dequeueSingle() { - while(true) { + while (true) { bool done; _waitProgressFutex(&done); - if(done) { + if (done) { // Reset and enqueue the chunk again. _chunk->progressFutex = 0; @@ -107,38 +106,43 @@ struct Queue { } } -private: + private: void _wakeHeadFutex() { auto futex = __atomic_exchange_n(&_queue->headFutex, _nextIndex, __ATOMIC_RELEASE); - if(futex & kHelHeadWaiters) + if (futex & kHelHeadWaiters) HEL_CHECK(helFutexWake(&_queue->headFutex)); } void _waitProgressFutex(bool *done) { - while(true) { + while (true) { auto futex = __atomic_load_n(&_chunk->progressFutex, __ATOMIC_ACQUIRE); __ensure(!(futex & ~(kHelProgressMask | kHelProgressWaiters | kHelProgressDone))); do { - if(_lastProgress != (futex & kHelProgressMask)) { + if (_lastProgress != (futex & kHelProgressMask)) { *done = false; return; - }else if(futex & kHelProgressDone) { + } else if (futex & kHelProgressDone) { *done = true; return; } - if(futex & kHelProgressWaiters) + if (futex & kHelProgressWaiters) break; // Waiters bit is already set (in a previous iteration). - } while(!__atomic_compare_exchange_n(&_chunk->progressFutex, &futex, - _lastProgress | kHelProgressWaiters, - false, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE)); - - HEL_CHECK(helFutexWait(&_chunk->progressFutex, - _lastProgress | kHelProgressWaiters, -1)); + } while (!__atomic_compare_exchange_n( + &_chunk->progressFutex, + &futex, + _lastProgress | kHelProgressWaiters, + false, + __ATOMIC_ACQUIRE, + __ATOMIC_ACQUIRE + )); + + HEL_CHECK(helFutexWait(&_chunk->progressFutex, _lastProgress | kHelProgressWaiters, -1) + ); } } -private: + private: HelHandle _handle; HelQueue *_queue; HelChunk *_chunk; @@ -156,8 +160,7 @@ HelSimpleResult *parseSimple(void *&element) { HelInlineResult *parseInline(void *&element) { auto result = reinterpret_cast(element); - element = (char *)element + sizeof(HelInlineResult) - + ((result->length + 7) & ~size_t(7)); + element = (char *)element + sizeof(HelInlineResult) + ((result->length + 7) & ~size_t(7)); return result; } @@ -179,7 +182,7 @@ int sys_tcb_set(void *pointer) { #if defined(__aarch64__) uintptr_t addr = reinterpret_cast(pointer); addr += sizeof(Tcb) - 0x10; - asm volatile ("msr tpidr_el0, %0" :: "r"(addr)); + asm volatile("msr tpidr_el0, %0" ::"r"(addr)); #else HEL_CHECK(helWriteFsBase(pointer)); #endif @@ -196,7 +199,7 @@ int sys_open(const char *path, int flags, mode_t mode, int *fd) { req.set_mode(mode); req.set_path(frg::string(getAllocator(), path)); - if(!globalQueue.valid()) + if (!globalQueue.valid()) globalQueue.initialize(); frg::string head(getAllocator()); @@ -237,7 +240,7 @@ int sys_open(const char *path, int flags, mode_t mode, int *fd) { managarm::posix::SvrResponse resp(getAllocator()); resp.ParseFromArray(recv_resp->data, recv_resp->length); - if(resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) + if (resp.error() == managarm::posix::Errors::FILE_NOT_FOUND) return -1; __ensure(resp.error() == managarm::posix::Errors::SUCCESS); *fd = resp.fd(); @@ -255,7 +258,7 @@ int sys_seek(int fd, off_t offset, int whence, off_t *new_offset) { req.set_req_type(managarm::fs::CntReqType::SEEK_ABS); req.set_rel_offset(offset); - if(!globalQueue.valid()) + if (!globalQueue.valid()) globalQueue.initialize(); frg::string ser(getAllocator()); @@ -294,7 +297,7 @@ int sys_read(int fd, void *data, size_t length, ssize_t *bytes_read) { req.set_req_type(managarm::fs::CntReqType::READ); req.set_size(length); - if(!globalQueue.valid()) + if (!globalQueue.valid()) globalQueue.initialize(); frg::string ser(getAllocator()); @@ -347,7 +350,7 @@ int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offse req.set_fd(fd); req.set_rel_offset(offset); - if(!globalQueue.valid()) + if (!globalQueue.valid()) globalQueue.initialize(); frg::string ser(getAllocator()); @@ -360,8 +363,7 @@ int sys_vm_map(void *hint, size_t size, int prot, int flags, int fd, off_t offse actions[1].length = ser.size(); actions[2].type = kHelActionRecvInline; actions[2].flags = 0; - HEL_CHECK(helSubmitAsync(posixLane, actions, 3, - globalQueue->getHandle(), 0, 0)); + HEL_CHECK(helSubmitAsync(posixLane, actions, 3, globalQueue->getHandle(), 0, 0)); auto element = globalQueue->dequeueSingle(); auto offer = parseHandle(element); @@ -386,7 +388,7 @@ int sys_close(int fd) { managarm::posix::CloseRequest req(getAllocator()); req.set_fd(fd); - if(!globalQueue.valid()) + if (!globalQueue.valid()) globalQueue.initialize(); frg::string ser(getAllocator()); @@ -417,30 +419,28 @@ int sys_close(int fd) { int sys_futex_tid() { HelWord tid = 0; - HEL_CHECK(helSyscall0_1(kHelCallSuper + posix::superGetTid, - &tid)); + HEL_CHECK(helSyscall0_1(kHelCallSuper + posix::superGetTid, &tid)); return tid; } int sys_futex_wait(int *pointer, int expected, const struct timespec *time) { // This implementation is inherently signal-safe. - if(time) { - if(helFutexWait(pointer, expected, time->tv_nsec + time->tv_sec * 1000000000)) + if (time) { + if (helFutexWait(pointer, expected, time->tv_nsec + time->tv_sec * 1000000000)) return -1; return 0; } - if(helFutexWait(pointer, expected, -1)) + if (helFutexWait(pointer, expected, -1)) return -1; return 0; } int sys_futex_wake(int *pointer) { // This implementation is inherently signal-safe. - if(helFutexWake(pointer)) + if (helFutexWake(pointer)) return -1; return 0; } - } // namespace mlibc diff --git a/sysdeps/managarm/x86_64/thread.cpp b/sysdeps/managarm/x86_64/thread.cpp index 88f1bf3588..129267d3e7 100644 --- a/sysdeps/managarm/x86_64/thread.cpp +++ b/sysdeps/managarm/x86_64/thread.cpp @@ -1,18 +1,18 @@ -#include -#include -#include #include -#include #include -#include +#include +#include +#include #include +#include +#include extern "C" void __mlibc_enter_thread(void *entry, void *user_arg, Tcb *tcb) { // Wait until our parent sets up the TID. - while(!__atomic_load_n(&tcb->tid, __ATOMIC_RELAXED)) + while (!__atomic_load_n(&tcb->tid, __ATOMIC_RELAXED)) mlibc::sys_futex_wait(&tcb->tid, 0, nullptr); - if(mlibc::sys_tcb_set(tcb)) + if (mlibc::sys_tcb_set(tcb)) __ensure(!"sys_tcb_set() failed"); tcb->invokeThreadFunc(entry, user_arg); @@ -29,7 +29,15 @@ namespace mlibc { static constexpr size_t default_stacksize = 0x200000; -int sys_prepare_stack(void **stack, void *entry, void *user_arg, void *tcb, size_t *stack_size, size_t *guard_size, void **stack_base) { +int sys_prepare_stack( + void **stack, + void *entry, + void *user_arg, + void *tcb, + size_t *stack_size, + size_t *guard_size, + void **stack_base +) { if (!*stack_size) *stack_size = default_stacksize; *guard_size = 0; @@ -37,20 +45,21 @@ int sys_prepare_stack(void **stack, void *entry, void *user_arg, void *tcb, size if (*stack) { *stack_base = *stack; } else { - *stack_base = mmap(nullptr, *stack_size, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if(*stack_base == MAP_FAILED) { + *stack_base = + mmap(nullptr, *stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (*stack_base == MAP_FAILED) { return errno; } } - - uintptr_t *sp = reinterpret_cast(reinterpret_cast(*stack_base) + *stack_size); + + uintptr_t *sp = + reinterpret_cast(reinterpret_cast(*stack_base) + *stack_size); *--sp = reinterpret_cast(tcb); *--sp = reinterpret_cast(user_arg); *--sp = reinterpret_cast(entry); - *stack = reinterpret_cast(sp); + *stack = reinterpret_cast(sp); return 0; } -} //namespace mlibc +} // namespace mlibc diff --git a/sysdeps/vinix/.clang-format b/sysdeps/vinix/.clang-format new file mode 100644 index 0000000000..46626920cf --- /dev/null +++ b/sysdeps/vinix/.clang-format @@ -0,0 +1,2 @@ +--- +DisableFormat: true diff --git a/tests/ansi/abs.c b/tests/ansi/abs.c index 492040ccfe..51b51c8073 100644 --- a/tests/ansi/abs.c +++ b/tests/ansi/abs.c @@ -1,16 +1,16 @@ -#include #include #include +#include -int main(){ - assert(abs(-10) == 10); - assert(abs(2021) == 2021); +int main() { + assert(abs(-10) == 10); + assert(abs(2021) == 2021); - assert(labs(-256) == 256); - assert(labs(10034890) == 10034890); + assert(labs(-256) == 256); + assert(labs(10034890) == 10034890); - assert(llabs(-0x2deadbeef) == 0x2deadbeef); - assert(llabs(49238706947) == 49238706947); + assert(llabs(-0x2deadbeef) == 0x2deadbeef); + assert(llabs(49238706947) == 49238706947); - return 0; -} \ No newline at end of file + return 0; +} diff --git a/tests/ansi/alloc.c b/tests/ansi/alloc.c index 4f5082b7f4..c4ca5ea7b5 100644 --- a/tests/ansi/alloc.c +++ b/tests/ansi/alloc.c @@ -1,7 +1,7 @@ -#include #include -#include #include +#include +#include int main() { void *p; diff --git a/tests/ansi/calloc.c b/tests/ansi/calloc.c index 025174fa03..7400b170ad 100644 --- a/tests/ansi/calloc.c +++ b/tests/ansi/calloc.c @@ -13,7 +13,7 @@ int main() { errno = 0; ptr = calloc(sizeof(size_t), 10); assert(ptr); - for(size_t i = 0; i < 10; i++) { + for (size_t i = 0; i < 10; i++) { size_t *p = ptr; assert(!p[i]); } diff --git a/tests/ansi/creal-cimag.c b/tests/ansi/creal-cimag.c index 1529865609..63c7e1a32d 100644 --- a/tests/ansi/creal-cimag.c +++ b/tests/ansi/creal-cimag.c @@ -1,6 +1,6 @@ #include -#include #include +#include // FIXME: We should create a proper floating point facility // in order for other functions to be tested properly @@ -9,31 +9,26 @@ #define APPROXIMATELY_EQUALF(calculated, expected) fabsf((calculated) - (expected)) <= 0.0000005f #define APPROXIMATELY_EQUALL(calculated, expected) fabsl((calculated) - (expected)) <= 0.0000005L -#define IS_COMPLEX_NUMBER(Z) \ - _Generic((Z), \ - double complex: 1, \ - float complex: 1, \ - long double complex: 1, \ - default: 0 \ - ) +#define IS_COMPLEX_NUMBER(Z) \ + _Generic((Z), double complex: 1, float complex: 1, long double complex: 1, default: 0) int main() { #if !(defined(USE_HOST_LIBC) && defined(__clang__)) - assert(IS_COMPLEX_NUMBER(CMPLX(5.2, 4.3))); - double complex cz = CMPLX(5.2, 4.3); - assert(APPROXIMATELY_EQUAL(creal(cz), 5.2)); - assert(APPROXIMATELY_EQUAL(cimag(cz), 4.3)); + assert(IS_COMPLEX_NUMBER(CMPLX(5.2, 4.3))); + double complex cz = CMPLX(5.2, 4.3); + assert(APPROXIMATELY_EQUAL(creal(cz), 5.2)); + assert(APPROXIMATELY_EQUAL(cimag(cz), 4.3)); - assert(IS_COMPLEX_NUMBER(CMPLXF(1.2f, 2.5f))); - float complex czf = CMPLXF(1.2f, 2.5f); - assert(APPROXIMATELY_EQUALF(crealf(czf), 1.2f)); - assert(APPROXIMATELY_EQUALF(cimagf(czf), 2.5f)); + assert(IS_COMPLEX_NUMBER(CMPLXF(1.2f, 2.5f))); + float complex czf = CMPLXF(1.2f, 2.5f); + assert(APPROXIMATELY_EQUALF(crealf(czf), 1.2f)); + assert(APPROXIMATELY_EQUALF(cimagf(czf), 2.5f)); - assert(IS_COMPLEX_NUMBER(CMPLXL(0.1L, 123.54L))); - long double complex czl = CMPLXL(0.1L, 123.54L); - assert(APPROXIMATELY_EQUALL(creall(czl), 0.1L)); - assert(APPROXIMATELY_EQUALL(cimagl(czl), 123.54L)); + assert(IS_COMPLEX_NUMBER(CMPLXL(0.1L, 123.54L))); + long double complex czl = CMPLXL(0.1L, 123.54L); + assert(APPROXIMATELY_EQUALL(creall(czl), 0.1L)); + assert(APPROXIMATELY_EQUALL(cimagl(czl), 123.54L)); #endif - return 0; + return 0; } diff --git a/tests/ansi/fenv.c b/tests/ansi/fenv.c index 0dfaff0f2c..e9fcca1e9e 100644 --- a/tests/ansi/fenv.c +++ b/tests/ansi/fenv.c @@ -1,16 +1,14 @@ #include -#include #include #include #include +#include /* qemu-m68k < version 9.1.0 cannot run the test due to missing FPU logic. */ #ifdef __m68k__ -int main() { - return 0; -} +int main() { return 0; } #else -#define NO_OPTIMIZE(x) asm volatile("" :: "r,m" (x) : "memory") +#define NO_OPTIMIZE(x) asm volatile("" ::"r,m"(x) : "memory") static void div_by_zero() { volatile float zero = 0.0f; diff --git a/tests/ansi/fgetpos.c b/tests/ansi/fgetpos.c index 66ea2e8b69..01c6fc6da0 100644 --- a/tests/ansi/fgetpos.c +++ b/tests/ansi/fgetpos.c @@ -2,7 +2,7 @@ #include int main(int argc, char *argv[]) { - (void) argc; + (void)argc; FILE *f = fopen(argv[0], "r"); assert(f); diff --git a/tests/ansi/fopen.c b/tests/ansi/fopen.c index f4818b2b37..877ffc1963 100644 --- a/tests/ansi/fopen.c +++ b/tests/ansi/fopen.c @@ -1,5 +1,5 @@ -#include #include +#include #include #ifdef USE_HOST_LIBC @@ -38,7 +38,8 @@ int main() { assert(!strcmp(buffer, str)); fclose(file); - // Open the file in appending mode, append string 2 (minus the null terminator) to the file, flush and close. + // Open the file in appending mode, append string 2 (minus the null terminator) to the file, + // flush and close. file = fopen(TEST_FILE, "a"); fwrite(str2, 1, sizeof(str2) - 1, file); fflush(file); diff --git a/tests/ansi/locale.c b/tests/ansi/locale.c index 056298b58d..824f4d33ce 100644 --- a/tests/ansi/locale.c +++ b/tests/ansi/locale.c @@ -1,17 +1,16 @@ +#include +#include #include #include -#include -#include int main() { wchar_t c = 0xC9; - unsigned char buf[sizeof(wchar_t)] = { 0 }; + unsigned char buf[sizeof(wchar_t)] = {0}; setlocale(LC_ALL, ""); if (sprintf(buf, "%lc", c) < 0) return -1; - assert(buf[0] == 0xc3 && buf[1] == 0x89 - && buf[2] == '\0' && buf[3] == '\0'); + assert(buf[0] == 0xc3 && buf[1] == 0x89 && buf[2] == '\0' && buf[3] == '\0'); return 0; } diff --git a/tests/ansi/longjmp.c b/tests/ansi/longjmp.c index 9fde66a922..ce8989a571 100644 --- a/tests/ansi/longjmp.c +++ b/tests/ansi/longjmp.c @@ -1,13 +1,11 @@ -#include +#include #include +#include #include -#include jmp_buf buf; -noreturn void do_jump(int arg) { - longjmp(buf, 2 * arg); -} +noreturn void do_jump(int arg) { longjmp(buf, 2 * arg); } int main(void) { volatile int times_called = 0; diff --git a/tests/ansi/mbrtoc32.c b/tests/ansi/mbrtoc32.c index a71bf02a5a..4e71eb6d96 100644 --- a/tests/ansi/mbrtoc32.c +++ b/tests/ansi/mbrtoc32.c @@ -10,10 +10,10 @@ struct { char32_t c32; uint8_t bytes[4]; } expected_results[] = { - {1, 0x7A, {0x7A, 0, 0, 0}}, - {2, 0xDF, {0xC3, 0x9F, 0, 0}}, - {3, 0x6C34, {0xE6, 0xB0, 0xB4, 0}}, - {4, 0x1F34C, {0xF0, 0x9F, 0x8D, 0x8C}}, + {1, 0x7A, {0x7A, 0, 0, 0}}, + {2, 0xDF, {0xC3, 0x9F, 0, 0}}, + {3, 0x6C34, {0xE6, 0xB0, 0xB4, 0}}, + {4, 0x1F34C, {0xF0, 0x9F, 0x8D, 0x8C}}, }; int main() { @@ -28,23 +28,23 @@ int main() { mbstate_t state = {}; char32_t c32; size_t loop = 0; - while((ret = mbrtoc32(&c32, str, strlen(str), &state))) { + while ((ret = mbrtoc32(&c32, str, strlen(str), &state))) { assert(ret != (size_t)-3); - if(ret == (size_t)-1) + if (ret == (size_t)-1) break; - if(ret == (size_t)-2) + if (ret == (size_t)-2) break; fprintf(stderr, "Next UTF-32 char: 0x%x obtained from %zu bytes [", c32, ret); - for(size_t n = 0; n < ret; ++n) { - fprintf(stderr, " 0x%02x ", (uint8_t) str[n]); + for (size_t n = 0; n < ret; ++n) { + fprintf(stderr, " 0x%02x ", (uint8_t)str[n]); } fprintf(stderr, "]\n"); assert(ret == expected_results[loop].ret); assert(c32 == expected_results[loop].c32); - for(size_t n = 0; n < ret; ++n) { - assert((uint8_t) str[n] == expected_results[loop].bytes[n]); + for (size_t n = 0; n < ret; ++n) { + assert((uint8_t)str[n] == expected_results[loop].bytes[n]); } str += ret; diff --git a/tests/ansi/memmem.c b/tests/ansi/memmem.c index c210a16bb8..dc54539978 100644 --- a/tests/ansi/memmem.c +++ b/tests/ansi/memmem.c @@ -1,5 +1,5 @@ -#include #include +#include int main() { char *haystack = "abc123\0x45"; diff --git a/tests/ansi/qsort.c b/tests/ansi/qsort.c index bb48a232de..fbed629b8d 100644 --- a/tests/ansi/qsort.c +++ b/tests/ansi/qsort.c @@ -1,9 +1,9 @@ #include -#include #include +#include #include -static const char *arr[] = { "xyz", "abc", "ghi", "def" }; +static const char *arr[] = {"xyz", "abc", "ghi", "def"}; static const size_t magic = 0xDEADBEEF; @@ -11,19 +11,19 @@ static int cmpstringp(const void *p1, const void *p2, void *ctx) { /* The actual arguments to this function are "pointers to * pointers to char", but strcmp(3) arguments are "pointers * to char", hence the following cast plus dereference. */ - assert(*(size_t *) ctx == magic); - return strcmp(*(const char **) p1, *(const char **) p2); + assert(*(size_t *)ctx == magic); + return strcmp(*(const char **)p1, *(const char **)p2); } int main() { - qsort_r(&arr[0], sizeof(arr) / sizeof(*arr), sizeof(char *), cmpstringp, (void *) &magic); + qsort_r(&arr[0], sizeof(arr) / sizeof(*arr), sizeof(char *), cmpstringp, (void *)&magic); assert(!strcmp(arr[0], "abc")); assert(!strcmp(arr[1], "def")); assert(!strcmp(arr[2], "ghi")); assert(!strcmp(arr[3], "xyz")); - for(size_t i = 0; i < sizeof(arr) / sizeof(*arr); i++) { + for (size_t i = 0; i < sizeof(arr) / sizeof(*arr); i++) { fprintf(stderr, "%s\n", arr[i]); } diff --git a/tests/ansi/snprintf.c b/tests/ansi/snprintf.c index 82e4640d65..e7eeab9bbd 100644 --- a/tests/ansi/snprintf.c +++ b/tests/ansi/snprintf.c @@ -1,5 +1,5 @@ -#include #include +#include #include int main() { diff --git a/tests/ansi/sprintf.c b/tests/ansi/sprintf.c index e239bda962..878bcf9fd0 100644 --- a/tests/ansi/sprintf.c +++ b/tests/ansi/sprintf.c @@ -1,10 +1,10 @@ -#include #include #include +#include #include int main() { - char buf[11] = { 0 }; + char buf[11] = {0}; sprintf(buf, "%d", 12); assert(!strcmp(buf, "12")); sprintf(buf, "%f", 3.14); @@ -141,9 +141,9 @@ int main() { assert(!strcmp(buf, "12")); sprintf(buf, "%zd", (size_t)12); assert(!strcmp(buf, "12")); - sprintf(buf, "%hd", (short) 12); + sprintf(buf, "%hd", (short)12); assert(!strcmp(buf, "12")); - sprintf(buf, "%hhd", (char) 12); + sprintf(buf, "%hhd", (char)12); assert(!strcmp(buf, "12")); // Test 'x' with different size mods to see @@ -156,9 +156,9 @@ int main() { assert(!strcmp(buf, "c")); sprintf(buf, "%zx", (size_t)12); assert(!strcmp(buf, "c")); - sprintf(buf, "%hx", (unsigned short) 12); + sprintf(buf, "%hx", (unsigned short)12); assert(!strcmp(buf, "c")); - sprintf(buf, "%hhx", (unsigned char) 12); + sprintf(buf, "%hhx", (unsigned char)12); assert(!strcmp(buf, "c")); // Test 'X' with different size mods to see @@ -171,9 +171,9 @@ int main() { assert(!strcmp(buf, "C")); sprintf(buf, "%zX", (size_t)12); assert(!strcmp(buf, "C")); - sprintf(buf, "%hX", (unsigned short) 12); + sprintf(buf, "%hX", (unsigned short)12); assert(!strcmp(buf, "C")); - sprintf(buf, "%hhX", (unsigned char) 12); + sprintf(buf, "%hhX", (unsigned char)12); assert(!strcmp(buf, "C")); // Test 'o' with different size mods to see @@ -186,9 +186,9 @@ int main() { assert(!strcmp(buf, "14")); sprintf(buf, "%zo", (size_t)12); assert(!strcmp(buf, "14")); - sprintf(buf, "%ho", (unsigned short) 12); + sprintf(buf, "%ho", (unsigned short)12); assert(!strcmp(buf, "14")); - sprintf(buf, "%hho", (unsigned char) 12); + sprintf(buf, "%hho", (unsigned char)12); assert(!strcmp(buf, "14")); // Disable -Wformat here because the compiler might not know about the b specifier. @@ -204,9 +204,9 @@ int main() { assert(!strcmp(buf, "1100")); sprintf(buf, "%zb", (size_t)12); assert(!strcmp(buf, "1100")); - sprintf(buf, "%hb", (unsigned short) 12); + sprintf(buf, "%hb", (unsigned short)12); assert(!strcmp(buf, "1100")); - sprintf(buf, "%hhb", (unsigned char) 12); + sprintf(buf, "%hhb", (unsigned char)12); assert(!strcmp(buf, "1100")); #pragma GCC diagnostic pop diff --git a/tests/ansi/sscanf.c b/tests/ansi/sscanf.c index cfb63d9744..33e3a6793a 100644 --- a/tests/ansi/sscanf.c +++ b/tests/ansi/sscanf.c @@ -1,7 +1,7 @@ -#include +#include #include +#include #include -#include struct format_test_cases { const char *format; @@ -15,57 +15,56 @@ struct format_test_cases { } type; int ret; } formats[] = { - {"%i", "0x420", 0x420, T_INT, 1}, - {"%i", "0420", 0420, T_INT, 1}, - {"%i", "420", 420, T_INT, 1}, - {"%i", "-420", -420, T_INT, 1}, - {"%d", "-12345", -12345, T_INT, 1}, - {"%u", "69", 69, T_UINT, 1}, - {"%u", "0420", 420, T_UINT, 1}, - {"%o", "0420", 0420, T_UINT, 1}, - {"%x", "0xCB7", 0xCB7, T_UINT, 1}, + {"%i", "0x420", 0x420, T_INT, 1}, + {"%i", "0420", 0420, T_INT, 1}, + {"%i", "420", 420, T_INT, 1}, + {"%i", "-420", -420, T_INT, 1}, + {"%d", "-12345", -12345, T_INT, 1}, + {"%u", "69", 69, T_UINT, 1}, + {"%u", "0420", 420, T_UINT, 1}, + {"%o", "0420", 0420, T_UINT, 1}, + {"%x", "0xCB7", 0xCB7, T_UINT, 1}, #ifndef USE_HOST_LIBC - {"%b", "0b1011", 0b1011, T_UINT, 1}, - {"%b", "0B1011", 0b1011, T_UINT, 1}, + {"%b", "0b1011", 0b1011, T_UINT, 1}, + {"%b", "0B1011", 0b1011, T_UINT, 1}, #endif - {"%%", "%", 0, T_NONE, 0}, - {"%c", " I am not a fan of this solution.", ' ', T_CHAR, 1}, - {" %c", " CBT (capybara therapy)", 'C', T_CHAR, 1}, - {"%d %d %d", " 111111 I<3Managarm 1234", 111111, T_UINT, 1}, - {"%c %d", "C", 'C', T_CHAR, 1} + {"%%", "%", 0, T_NONE, 0}, + {"%c", " I am not a fan of this solution.", ' ', T_CHAR, 1}, + {" %c", " CBT (capybara therapy)", 'C', T_CHAR, 1}, + {"%d %d %d", " 111111 I<3Managarm 1234", 111111, T_UINT, 1}, + {"%c %d", "C", 'C', T_CHAR, 1} }; #pragma GCC diagnostic ignored "-Wformat-security" static void test_matrix() { - for(size_t i = 0; i < (sizeof(formats) / sizeof(*formats)); i++) { + for (size_t i = 0; i < (sizeof(formats) / sizeof(*formats)); i++) { struct format_test_cases *f = &formats[i]; int ret = -1; int data_int; unsigned int data_uint; char data_char; - switch(f->type) { - case T_INT: { - ret = sscanf(f->data, f->format, &data_int); - assert(data_int == f->expected_int); - break; - } - case T_UINT: { - ret = sscanf(f->data, f->format, &data_uint); - assert(data_uint == (unsigned int) f->expected_int); - break; - } - case T_CHAR: { - ret = sscanf(f->data, f->format, &data_char); - assert(data_char == (unsigned char) f->expected_int); - break; - } - case T_NONE: { - ret = sscanf(f->data, f->format); - break; - } - + switch (f->type) { + case T_INT: { + ret = sscanf(f->data, f->format, &data_int); + assert(data_int == f->expected_int); + break; + } + case T_UINT: { + ret = sscanf(f->data, f->format, &data_uint); + assert(data_uint == (unsigned int)f->expected_int); + break; + } + case T_CHAR: { + ret = sscanf(f->data, f->format, &data_char); + assert(data_char == (unsigned char)f->expected_int); + break; + } + case T_NONE: { + ret = sscanf(f->data, f->format); + break; + } } assert(ret == f->ret); @@ -84,7 +83,8 @@ int main() { char c; int n1; int n2; - char buf[] = "z$ 7 5 440";; + char buf[] = "z$ 7 5 440"; + ; int count = sscanf(buf, "%*c%c %d %*d %d", &c, &n1, &n2); assert(count == 3); assert(c == '$'); diff --git a/tests/ansi/strchr.c b/tests/ansi/strchr.c index a80a1f9634..b89ab10ccb 100644 --- a/tests/ansi/strchr.c +++ b/tests/ansi/strchr.c @@ -1,20 +1,20 @@ #include -#include #include +#include int main() { - char str[] = "This is a sample string"; - char *pch; - // The character 's' is at position 4, 7, 11 and 18 - pch = strchr(str, 's'); - assert(pch - str + 1 == 4); - pch = strchr(pch + 1, 's'); - assert(pch - str + 1 == 7); - pch = strchr(pch + 1, 's'); - assert(pch - str + 1 == 11); - pch = strchr(pch + 1, 's'); - assert(pch - str + 1 == 18); - pch = strchr(pch + 1, 's'); - assert(pch == NULL); - return 0; + char str[] = "This is a sample string"; + char *pch; + // The character 's' is at position 4, 7, 11 and 18 + pch = strchr(str, 's'); + assert(pch - str + 1 == 4); + pch = strchr(pch + 1, 's'); + assert(pch - str + 1 == 7); + pch = strchr(pch + 1, 's'); + assert(pch - str + 1 == 11); + pch = strchr(pch + 1, 's'); + assert(pch - str + 1 == 18); + pch = strchr(pch + 1, 's'); + assert(pch == NULL); + return 0; } diff --git a/tests/ansi/strftime.c b/tests/ansi/strftime.c index e30df21cb6..c37c6fc562 100644 --- a/tests/ansi/strftime.c +++ b/tests/ansi/strftime.c @@ -1,13 +1,13 @@ -#include -#include #include #include #include +#include +#include int main() { // Date representation depends on locale, here only C is tested. // Maybe consider testing more locales? - if (setlocale (LC_ALL, "C") == NULL) { + if (setlocale(LC_ALL, "C") == NULL) { fputs("strftime testcase could not set locale, errors may be expected!", stderr); } diff --git a/tests/ansi/strrchr.c b/tests/ansi/strrchr.c index 2de98219a8..b16384ee2e 100644 --- a/tests/ansi/strrchr.c +++ b/tests/ansi/strrchr.c @@ -1,11 +1,11 @@ -#include #include +#include int main() { - char str[] = "This is a sample string"; - char *pch; - pch = strrchr(str, 's'); - // The last occurence of 's' is at position 18 - assert(pch - str + 1 == 18); - return 0; + char str[] = "This is a sample string"; + char *pch; + pch = strrchr(str, 's'); + // The last occurence of 's' is at position 18 + assert(pch - str + 1 == 18); + return 0; } diff --git a/tests/ansi/strtof.c b/tests/ansi/strtof.c index a13af90d5d..b2e37ff1c5 100644 --- a/tests/ansi/strtof.c +++ b/tests/ansi/strtof.c @@ -1,27 +1,31 @@ -#include #include -#include #include +#include +#include #define FLT_RANGE 0.000001f #define DBL_RANGE 0.000001 #define LDBL_RANGE 0.000001 -#define DO_TEST(str, value, off, func, range) ({ \ - char s[] = (str); \ - char *pEnd = NULL; \ - __typeof(func(s, &pEnd)) result = func(s, &pEnd); \ - assert(result >= (value) - (range)); \ - assert(result <= (value) + (range)); \ - assert(pEnd == (off == -1 ? s + strlen(s) : s + off)); }) +#define DO_TEST(str, value, off, func, range) \ + ({ \ + char s[] = (str); \ + char *pEnd = NULL; \ + __typeof(func(s, &pEnd)) result = func(s, &pEnd); \ + assert(result >= (value) - (range)); \ + assert(result <= (value) + (range)); \ + assert(pEnd == (off == -1 ? s + strlen(s) : s + off)); \ + }) -#define DO_TEST_SUCCESS_FUNC(str, success_func, off, func) ({ \ - char s[] = (str); \ - char *pEnd = NULL; \ - assert(success_func(func(s, &pEnd))); \ - assert(pEnd == (off == -1 ? s + strlen(s) : s + off)); }) +#define DO_TEST_SUCCESS_FUNC(str, success_func, off, func) \ + ({ \ + char s[] = (str); \ + char *pEnd = NULL; \ + assert(success_func(func(s, &pEnd))); \ + assert(pEnd == (off == -1 ? s + strlen(s) : s + off)); \ + }) -int main () { +int main() { DO_TEST("0", 0.0f, -1, strtof, FLT_RANGE); DO_TEST("0.12", 0.12f, -1, strtof, FLT_RANGE); DO_TEST("12", 12.0f, -1, strtof, FLT_RANGE); diff --git a/tests/ansi/strtol.c b/tests/ansi/strtol.c index 600248697e..9723f70859 100644 --- a/tests/ansi/strtol.c +++ b/tests/ansi/strtol.c @@ -1,44 +1,52 @@ -#include #include -#include -#include #include +#include #include +#include +#include #include -#define DO_TEST(str, value, off, func, base) ({ \ - char s[] = (str); \ - char *pEnd = NULL; \ - errno = 0; \ - assert(func(s, &pEnd, base) == (value)); \ - assert(errno == 0); \ - assert(pEnd == (off == -1 ? s + strlen(s) : s + off)); }) +#define DO_TEST(str, value, off, func, base) \ + ({ \ + char s[] = (str); \ + char *pEnd = NULL; \ + errno = 0; \ + assert(func(s, &pEnd, base) == (value)); \ + assert(errno == 0); \ + assert(pEnd == (off == -1 ? s + strlen(s) : s + off)); \ + }) -#define DO_ERR_TEST(str, value, err, func, base) ({ \ - char s[] = (str); \ - char *pEnd = NULL; \ - errno = 0; \ - assert(func(s, &pEnd, base) == (value)); \ - assert(errno == err); \ - assert(pEnd == (err == ERANGE ? s + strlen(s) : s)); }) +#define DO_ERR_TEST(str, value, err, func, base) \ + ({ \ + char s[] = (str); \ + char *pEnd = NULL; \ + errno = 0; \ + assert(func(s, &pEnd, base) == (value)); \ + assert(errno == err); \ + assert(pEnd == (err == ERANGE ? s + strlen(s) : s)); \ + }) -#define DO_TESTL(str, value, off, func, base) ({ \ - wchar_t s[] = (str); \ - wchar_t *pEnd = NULL; \ - errno = 0; \ - assert(func(s, &pEnd, base) == (value)); \ - assert(errno == 0); \ - assert(pEnd == (off == -1 ? s + wcslen(s) : s + off)); }) +#define DO_TESTL(str, value, off, func, base) \ + ({ \ + wchar_t s[] = (str); \ + wchar_t *pEnd = NULL; \ + errno = 0; \ + assert(func(s, &pEnd, base) == (value)); \ + assert(errno == 0); \ + assert(pEnd == (off == -1 ? s + wcslen(s) : s + off)); \ + }) -#define DO_ERR_TESTL(str, value, err, func, base) ({ \ - wchar_t s[] = (str); \ - wchar_t *pEnd = NULL; \ - errno = 0; \ - assert(func(s, &pEnd, base) == (value)); \ - assert(errno == err); \ - assert(pEnd == (err == ERANGE ? s + wcslen(s) : s)); }) +#define DO_ERR_TESTL(str, value, err, func, base) \ + ({ \ + wchar_t s[] = (str); \ + wchar_t *pEnd = NULL; \ + errno = 0; \ + assert(func(s, &pEnd, base) == (value)); \ + assert(errno == err); \ + assert(pEnd == (err == ERANGE ? s + wcslen(s) : s)); \ + }) -int main () { +int main() { // A few generic checks. DO_TEST("0", 0, -1, strtol, 0); DO_TEST("0", 0, -1, strtol, 10); @@ -64,9 +72,9 @@ int main () { // strtol #if defined(__i386__) || defined(__m68k__) - DO_TEST("-2147483648", LONG_MIN, -1, strtol, 10); + DO_TEST("-2147483648", LONG_MIN, -1, strtol, 10); DO_TEST("2147483647", LONG_MAX, -1, strtol, 10); - DO_ERR_TEST("-2147483649", LONG_MIN, ERANGE, strtol, 10); + DO_ERR_TEST("-2147483649", LONG_MIN, ERANGE, strtol, 10); DO_ERR_TEST("2147483648", LONG_MAX, ERANGE, strtol, 10); #else DO_TEST("-9223372036854775808", LONG_MIN, -1, strtol, 10); diff --git a/tests/ansi/strverscmp.c b/tests/ansi/strverscmp.c index f54c81dbfa..ec049390a8 100644 --- a/tests/ansi/strverscmp.c +++ b/tests/ansi/strverscmp.c @@ -1,18 +1,18 @@ -#include -#include #include +#include +#include int main() { - int res; + int res; - res = strverscmp("jan1", "jan10"); - assert(res < 0); + res = strverscmp("jan1", "jan10"); + assert(res < 0); - res = strverscmp("jan11", "jan10"); - assert(res > 0); + res = strverscmp("jan11", "jan10"); + assert(res > 0); - res = strverscmp("jan1", "jan1"); - assert(res == 0); + res = strverscmp("jan1", "jan1"); + assert(res == 0); - return 0; + return 0; } diff --git a/tests/ansi/timegm.c b/tests/ansi/timegm.c index f5af03ea43..9fcc3786b0 100644 --- a/tests/ansi/timegm.c +++ b/tests/ansi/timegm.c @@ -1,6 +1,6 @@ -#include -#include #include +#include +#include int main() { struct tm soon = {}; diff --git a/tests/ansi/ungetc.c b/tests/ansi/ungetc.c index 3701c5315f..883d32ec78 100644 --- a/tests/ansi/ungetc.c +++ b/tests/ansi/ungetc.c @@ -1,5 +1,5 @@ -#include #include +#include #ifdef USE_HOST_LIBC #define TEST_FILE "ungetc-host-libc.tmp" @@ -9,7 +9,7 @@ void test(int buffering) { FILE *f = fopen(TEST_FILE, "w"); - for(int c = '0'; c <= '9'; c++) { + for (int c = '0'; c <= '9'; c++) { fputc(c, f); } fclose(f); diff --git a/tests/ansi/utf8.c b/tests/ansi/utf8.c index b55e73c4c9..ee28617298 100644 --- a/tests/ansi/utf8.c +++ b/tests/ansi/utf8.c @@ -1,10 +1,10 @@ #include #include +#include #include #include #include #include -#include #if UINTPTR_MAX == UINT64_MAX #define WCHAR_SPEC "" @@ -12,19 +12,30 @@ #define WCHAR_SPEC "l" #endif -#define EXPECT(func) ({ \ - if(res != expected_ret) { \ - printf(#func " decoded %d bytes (expected %d bytes), at %s:%d\n", \ - res, expected_ret, __FILE__, line); \ - fflush(stdout); \ - abort(); \ - } \ - if(wc != expected) { \ - printf(#func " output cp %" WCHAR_SPEC "x (expected cp %" WCHAR_SPEC "x), at %s:%d\n", wc, \ - expected, __FILE__, line); \ - fflush(stdout); \ - abort(); \ - } \ +#define EXPECT(func) \ + ({ \ + if (res != expected_ret) { \ + printf( \ + #func " decoded %d bytes (expected %d bytes), at %s:%d\n", \ + res, \ + expected_ret, \ + __FILE__, \ + line \ + ); \ + fflush(stdout); \ + abort(); \ + } \ + if (wc != expected) { \ + printf( \ + #func " output cp %" WCHAR_SPEC "x (expected cp %" WCHAR_SPEC "x), at %s:%d\n", \ + wc, \ + expected, \ + __FILE__, \ + line \ + ); \ + fflush(stdout); \ + abort(); \ + } \ }) void verify_decode(const char *input, wchar_t expected, int line) { diff --git a/tests/ansi/wcsdup.c b/tests/ansi/wcsdup.c index efecee76fb..df427cd4b5 100644 --- a/tests/ansi/wcsdup.c +++ b/tests/ansi/wcsdup.c @@ -1,6 +1,6 @@ #include -#include #include +#include #include int main() { diff --git a/tests/ansi/wcsrtombs.c b/tests/ansi/wcsrtombs.c index 80df25707b..a485881e86 100644 --- a/tests/ansi/wcsrtombs.c +++ b/tests/ansi/wcsrtombs.c @@ -1,7 +1,7 @@ -#include -#include #include +#include #include +#include int main() { const wchar_t str[] = L"wcsrtombs"; diff --git a/tests/ansi/wmemcmp.c b/tests/ansi/wmemcmp.c index 74de9bd0d8..8150d0beda 100644 --- a/tests/ansi/wmemcmp.c +++ b/tests/ansi/wmemcmp.c @@ -1,19 +1,19 @@ #include -#include #include +#include -int main(void){ - wchar_t *ws1 = calloc(10, sizeof(wchar_t)); - wchar_t *ws2 = calloc(10, sizeof(wchar_t)); +int main(void) { + wchar_t *ws1 = calloc(10, sizeof(wchar_t)); + wchar_t *ws2 = calloc(10, sizeof(wchar_t)); - mbstowcs(ws1, "Test 1", 10); - mbstowcs(ws2, "Tester 2", 10); + mbstowcs(ws1, "Test 1", 10); + mbstowcs(ws2, "Tester 2", 10); - assert(wmemcmp(ws1, ws2, 10) < 0); - assert(wmemcmp(ws2, ws1, 10) > 0); - assert(wmemcmp(ws2, ws2, 10) == 0); + assert(wmemcmp(ws1, ws2, 10) < 0); + assert(wmemcmp(ws2, ws1, 10) > 0); + assert(wmemcmp(ws2, ws2, 10) == 0); free(ws1); free(ws2); - return 0; + return 0; } diff --git a/tests/bsd/ns_get_put.c b/tests/bsd/ns_get_put.c index d64bb2a403..c25a31a29b 100644 --- a/tests/bsd/ns_get_put.c +++ b/tests/bsd/ns_get_put.c @@ -1,8 +1,8 @@ -#include #include -#include -#include +#include #include +#include +#include int main() { uint8_t *buf = malloc(256); diff --git a/tests/bsd/sbrk.c b/tests/bsd/sbrk.c index b54b7347f8..f377dcb1c3 100644 --- a/tests/bsd/sbrk.c +++ b/tests/bsd/sbrk.c @@ -4,7 +4,7 @@ int main() { void *ret = sbrk(0); - assert(ret != (void *) -1); + assert(ret != (void *)-1); assert(ret); return 0; diff --git a/tests/glibc/error_print_progname.c b/tests/glibc/error_print_progname.c index b3181c7287..00e037784d 100644 --- a/tests/glibc/error_print_progname.c +++ b/tests/glibc/error_print_progname.c @@ -1,8 +1,8 @@ #include -#include -#include #include #include +#include +#include bool ran = false; diff --git a/tests/glibc/ffsl-ffsll.c b/tests/glibc/ffsl-ffsll.c index ed70ad687f..dc56817448 100644 --- a/tests/glibc/ffsl-ffsll.c +++ b/tests/glibc/ffsl-ffsll.c @@ -1,14 +1,14 @@ #include +#include #include #include -#include -int main(void){ +int main(void) { // ffsl assert(ffsl(0x8000) == 16); assert(ffsl(0) == 0); #if UINTPTR_MAX == UINT64_MAX - assert(ffsl(LLONG_MAX - 1) == 2); + assert(ffsl(LLONG_MAX - 1) == 2); assert(ffsl(LLONG_MAX) == 1); #endif assert(ffsl(LONG_MIN) == (long)(sizeof(long) * CHAR_BIT)); @@ -22,7 +22,7 @@ int main(void){ assert(ffsll(0x8000) == 16); assert(ffsll(0) == 0); #if UINTPTR_MAX == UINT64_MAX - assert(ffsll(LLONG_MAX - 1) == 2); + assert(ffsll(LLONG_MAX - 1) == 2); assert(ffsll(LLONG_MAX) == 1); #endif assert(ffsll(LLONG_MIN) == (long long)(sizeof(long long) * CHAR_BIT)); diff --git a/tests/glibc/getgrouplist.c b/tests/glibc/getgrouplist.c index dbdf5669eb..1d307c1c09 100644 --- a/tests/glibc/getgrouplist.c +++ b/tests/glibc/getgrouplist.c @@ -17,14 +17,14 @@ int main() { int e = 0; groups = malloc(sizeof(*groups) * ngroups); - if(groups == NULL) { + if (groups == NULL) { perror("malloc"); exit(EXIT_FAILURE); } /* Fetch passwd structure */ pw = getpwuid(geteuid()); - if(pw == NULL) { + if (pw == NULL) { perror("getpwnam"); exit(EXIT_FAILURE); } @@ -32,19 +32,21 @@ int main() { /* Retrieve group list */ e = getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups); assert(e > 0); - if(e == -1) { - fprintf(stderr, "getgrouplist() returned -1 (%s); ngroups = %d\n", strerror(errno), ngroups); + if (e == -1) { + fprintf( + stderr, "getgrouplist() returned -1 (%s); ngroups = %d\n", strerror(errno), ngroups + ); exit(EXIT_FAILURE); } /* Display list of retrieved groups, along with group names */ fprintf(stderr, "ngroups = %d\n", ngroups); - for(int j = 0; j < ngroups; j++) { - if(groups[j] == pw->pw_gid) + for (int j = 0; j < ngroups; j++) { + if (groups[j] == pw->pw_gid) gid_checked = true; printf("%d", groups[j]); gr = getgrgid(groups[j]); - if(gr != NULL) + if (gr != NULL) printf(" (%s)", gr->gr_name); printf("\n"); } diff --git a/tests/glibc/getopt.c b/tests/glibc/getopt.c index 5a64a775d4..427e455bb2 100644 --- a/tests/glibc/getopt.c +++ b/tests/glibc/getopt.c @@ -6,38 +6,37 @@ #include #include -#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x]))))) -#define dump(x) fprintf(stderr, "getopt c '%c' (%d), optind %d ('%s'), optarg '%s', optopt '%c' (%d)\n", \ - (x), (x), optind, (size_t)optind >= COUNT_OF(test_argv) ? "out of range" : test_argv[optind], optarg, optopt, optopt); +#define COUNT_OF(x) ((sizeof(x) / sizeof(0 [x])) / ((size_t)(!(sizeof(x) % sizeof(0 [x]))))) +#define dump(x) \ + fprintf( \ + stderr, \ + "getopt c '%c' (%d), optind %d ('%s'), optarg '%s', optopt '%c' (%d)\n", \ + (x), \ + (x), \ + optind, \ + (size_t)optind >= COUNT_OF(test_argv) ? "out of range" : test_argv[optind], \ + optarg, \ + optopt, \ + optopt \ + ); void test1() { const char *shortopts = "b:cdef"; const struct option longopts[] = { - {"foo", required_argument, NULL, 'f'}, - {NULL, no_argument, NULL, 0} + {"foo", required_argument, NULL, 'f'}, {NULL, no_argument, NULL, 0} }; int test_argc = 7; - char *test_argv[] = { - "dummy", - "--foo", - "abc", - "-b", - "abc", - "abc", - "abc" - }; + char *test_argv[] = {"dummy", "--foo", "abc", "-b", "abc", "abc", "abc"}; optind = 0; int c = getopt_long(test_argc, test_argv, shortopts, longopts, NULL); - dump(c) - assert(c == 'f'); + dump(c) assert(c == 'f'); c = getopt_long(test_argc, test_argv, shortopts, longopts, NULL); - dump(c) - assert(optarg && !strcmp(optarg, "abc")); + dump(c) assert(optarg && !strcmp(optarg, "abc")); assert(c == 'b'); c = getopt_long(test_argc, test_argv, shortopts, longopts, NULL); @@ -51,13 +50,12 @@ void test1() { void test2() { const struct option longopts[] = { - {"foo", required_argument, NULL, 'f'}, - {NULL, no_argument, NULL, 0} + {"foo", required_argument, NULL, 'f'}, {NULL, no_argument, NULL, 0} }; char *test_argv[] = { - "dummy", - "-c", + "dummy", + "-c", }; fputs("Situation: we pass a non-existant short option in argv\n", stderr); @@ -68,7 +66,11 @@ void test2() { assert(c == '?'); assert(optopt == 'c'); - fputs("Situation: we pass a non-existant short option in argv, while passing a leading colon in optstring\n", stderr); + fputs( + "Situation: we pass a non-existant short option in argv, while passing a leading colon in " + "optstring\n", + stderr + ); optind = 0; c = getopt_long(COUNT_OF(test_argv), test_argv, ":ab:", longopts, NULL); @@ -84,7 +86,11 @@ void test2() { assert(c == '?'); assert(optopt == 'c'); - fputs("Situation: we omit the required arg to a short option, while passing a leading colon in optstring\n", stderr); + fputs( + "Situation: we omit the required arg to a short option, while passing a leading colon in " + "optstring\n", + stderr + ); optind = 0; c = getopt_long(COUNT_OF(test_argv), test_argv, ":ab:c:", longopts, NULL); @@ -95,13 +101,12 @@ void test2() { void test3() { const struct option longopts[] = { - {"foo", required_argument, NULL, 'f'}, - {NULL, no_argument, NULL, 0} + {"foo", required_argument, NULL, 'f'}, {NULL, no_argument, NULL, 0} }; char *test_argv[] = { - "dummy", - "-cmanagarm", + "dummy", + "-cmanagarm", }; fputs("Situation: we pass a concatenated argument to a short option\n", stderr); @@ -116,13 +121,12 @@ void test3() { void test4() { const struct option longopts[] = { - {"foo", required_argument, NULL, 'f'}, - {NULL, no_argument, NULL, 0} + {"foo", required_argument, NULL, 'f'}, {NULL, no_argument, NULL, 0} }; char *test_argv[] = { - "dummy", - "-acmanagarm", + "dummy", + "-acmanagarm", }; fputs("Situation: we pass concatenated short options to getopt\n", stderr); @@ -139,16 +143,10 @@ void test4() { void test5() { const struct option longopts[] = { - {"foo", required_argument, NULL, 'f'}, - {NULL, no_argument, NULL, 0} + {"foo", required_argument, NULL, 'f'}, {NULL, no_argument, NULL, 0} }; - char *test_argv[] = { - "su", - "-", - "managarm", - 0 - }; + char *test_argv[] = {"su", "-", "managarm", 0}; int test_argc = 3; @@ -169,23 +167,18 @@ void test5() { } void test6() { - char *test_argv[] = { - "telescope", - "gemini://electrode.codes", - "-S", - 0 - }; + char *test_argv[] = {"telescope", "gemini://electrode.codes", "-S", 0}; int test_argc = 3; optind = 0; const struct option longopts[] = { - {"colors", no_argument, NULL, 'C'}, - {"colours", no_argument, NULL, 'C'}, - {"help", no_argument, NULL, 'h'}, - {"safe", no_argument, NULL, 'S'}, - {"version", no_argument, NULL, 'v'}, - {NULL, 0, NULL, 0}, + {"colors", no_argument, NULL, 'C'}, + {"colours", no_argument, NULL, 'C'}, + {"help", no_argument, NULL, 'h'}, + {"safe", no_argument, NULL, 'S'}, + {"version", no_argument, NULL, 'v'}, + {NULL, 0, NULL, 0}, }; int c = getopt_long(test_argc, test_argv, "Cc:hnST:v", longopts, NULL); @@ -199,19 +192,14 @@ void test7() { int c; static const struct option options[] = { - { "debug", no_argument, NULL, 'd' }, - { "help", no_argument, NULL, 'h' }, - { "version", no_argument, NULL, 'V' }, - {} + {"debug", no_argument, NULL, 'd'}, + {"help", no_argument, NULL, 'h'}, + {"version", no_argument, NULL, 'V'}, + {} }; const char *command; - char *test_argv[] = { - "udevadm", - "hwdb", - "--update", - 0 - }; + char *test_argv[] = {"udevadm", "hwdb", "--update", 0}; int test_argc = 3; setenv("POSIXLY_CORRECT", "1", 1); @@ -219,14 +207,14 @@ void test7() { while ((c = getopt_long(test_argc, test_argv, "+dhV", options, NULL)) >= 0) { switch (c) { - case 'd': - break; - case 'h': - break; - case 'V': - break; - default: - break; + case 'd': + break; + case 'h': + break; + case 'V': + break; + default: + break; } } @@ -243,27 +231,20 @@ void test8() { int bar = false; const struct option longopts[] = { - {"foo", required_argument, &foo, 'x'}, - {"bar", required_argument, &bar, 'y'}, - {NULL, no_argument, NULL, 0} + {"foo", required_argument, &foo, 'x'}, + {"bar", required_argument, &bar, 'y'}, + {NULL, no_argument, NULL, 0} }; int test_argc = 6; - char *test_argv[] = { - "dummy", - "-foo", - "abc", - "-bar=def", - "ghi", - "jkl" - }; + char *test_argv[] = {"dummy", "-foo", "abc", "-bar=def", "ghi", "jkl"}; - #ifdef __GLIBC__ - optind = 0; - #else - optreset = 1; - #endif +#ifdef __GLIBC__ + optind = 0; +#else + optreset = 1; +#endif optopt = 0; int c = getopt_long_only(test_argc, test_argv, shortopts, longopts, NULL); dump(c); diff --git a/tests/glibc/linux-syscall.c b/tests/glibc/linux-syscall.c index 2760df44f7..be286ff9c3 100644 --- a/tests/glibc/linux-syscall.c +++ b/tests/glibc/linux-syscall.c @@ -1,8 +1,8 @@ -#include -#include +#include #include #include -#include +#include +#include int main() { char *data = "hello mlibc\n"; diff --git a/tests/linux/cpuset.c b/tests/linux/cpuset.c index 3f5573251a..6d19562c71 100644 --- a/tests/linux/cpuset.c +++ b/tests/linux/cpuset.c @@ -1,6 +1,6 @@ #include -#include #include +#include #define SET_SIZE 15 diff --git a/tests/linux/getifaddrs.c b/tests/linux/getifaddrs.c index f98c7e31bb..6dc2162db2 100644 --- a/tests/linux/getifaddrs.c +++ b/tests/linux/getifaddrs.c @@ -12,49 +12,68 @@ #include int main(int argc, char *argv[]) { - (void) argc; - (void) argv; + (void)argc; + (void)argv; struct ifaddrs *ifaddr = 0; char host[NI_MAXHOST]; bool loopback_found = false; - if(getifaddrs(&ifaddr)) { + if (getifaddrs(&ifaddr)) { perror("getifaddrs"); exit(EXIT_FAILURE); } - for(struct ifaddrs *ifa = ifaddr; ifa; ifa = ifa->ifa_next) { - if(ifa->ifa_addr == NULL) + for (struct ifaddrs *ifa = ifaddr; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == NULL) continue; int family = ifa->ifa_addr->sa_family; - if(family == AF_INET && !strcmp("lo", ifa->ifa_name)) { + if (family == AF_INET && !strcmp("lo", ifa->ifa_name)) { loopback_found = true; - printf("%-10s %s (%d)\n", ifa->ifa_name, - (family == AF_INET) ? "AF_INET" : (family == AF_INET6) ? "AF_INET6" : "???", - family + printf( + "%-10s %s (%d)\n", + ifa->ifa_name, + (family == AF_INET) ? "AF_INET" + : (family == AF_INET6) ? "AF_INET6" + : "???", + family ); - int s = getnameinfo(ifa->ifa_addr, - (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), - host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); + int s = getnameinfo( + ifa->ifa_addr, + (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), + host, + NI_MAXHOST, + NULL, + 0, + NI_NUMERICHOST + ); assert(!s); printf("\t\taddress: <%s>\n", host); - if(ifa->ifa_netmask) - printf("\t\tnetmask: <%s>\n", inet_ntoa(((struct sockaddr_in *) ifa->ifa_netmask)->sin_addr)); + if (ifa->ifa_netmask) + printf( + "\t\tnetmask: <%s>\n", + inet_ntoa(((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr) + ); - if(ifa->ifa_flags & IFF_BROADCAST) { + if (ifa->ifa_flags & IFF_BROADCAST) { assert(ifa->ifa_broadaddr); - printf("\t\tbroadcast: <%s>\n", inet_ntoa(((struct sockaddr_in *) ifa->ifa_broadaddr)->sin_addr)); + printf( + "\t\tbroadcast: <%s>\n", + inet_ntoa(((struct sockaddr_in *)ifa->ifa_broadaddr)->sin_addr) + ); } - if(ifa->ifa_flags & IFF_POINTOPOINT) { + if (ifa->ifa_flags & IFF_POINTOPOINT) { assert(ifa->ifa_dstaddr); - printf("\t\tdest addr: <%s>\n", inet_ntoa(((struct sockaddr_in *) ifa->ifa_dstaddr)->sin_addr)); + printf( + "\t\tdest addr: <%s>\n", + inet_ntoa(((struct sockaddr_in *)ifa->ifa_dstaddr)->sin_addr) + ); } } } diff --git a/tests/linux/pthread_attr.c b/tests/linux/pthread_attr.c index 4c1907c054..99e41635d1 100644 --- a/tests/linux/pthread_attr.c +++ b/tests/linux/pthread_attr.c @@ -1,8 +1,8 @@ #include #include +#include #include #include -#include static void test_affinity() { pthread_attr_t attr; diff --git a/tests/linux/pthread_setname_np.c b/tests/linux/pthread_setname_np.c index 95c95c9922..b013d28a88 100644 --- a/tests/linux/pthread_setname_np.c +++ b/tests/linux/pthread_setname_np.c @@ -4,8 +4,8 @@ #include #include -#include #include +#include int main() { int ret = pthread_setname_np(pthread_self(), "mlibc-test-123"); diff --git a/tests/linux/xattr.c b/tests/linux/xattr.c index c565030cad..3e632bed40 100644 --- a/tests/linux/xattr.c +++ b/tests/linux/xattr.c @@ -1,36 +1,34 @@ +#include #include #include -#include #include -#include #include +#include -#define assert_perror(x) \ - ({ \ - int res = (x); \ - if (res < 0) { \ - perror(#x); \ - return 1; \ - } \ - res; \ +#define assert_perror(x) \ + ({ \ + int res = (x); \ + if (res < 0) { \ + perror(#x); \ + return 1; \ + } \ + res; \ }) -#define soft_assert(x, m) \ - ({ \ - if (!(x)) { \ - fprintf(stderr, "cond \"%s\" failed: %s\n", #x, m); \ - return 1; \ - } \ +#define soft_assert(x, m) \ + ({ \ + if (!(x)) { \ + fprintf(stderr, "cond \"%s\" failed: %s\n", #x, m); \ + return 1; \ + } \ }) -void remove_tmp(const char (*fname)[]) { - unlink(&(*fname)[0]); -} +void remove_tmp(const char (*fname)[]) { unlink(&(*fname)[0]); } #define _cleanup_file_ __attribute__((cleanup(remove_tmp))) int main(void) { int ret; - char buf[32] = { 0 }; + char buf[32] = {0}; _cleanup_file_ char filename[] = "xattr_test.XXXXXX"; _cleanup_file_ char filename2[] = "xattr_test.XXXXXX.2"; diff --git a/tests/posix/abort.c b/tests/posix/abort.c index 5f7bb7d40c..82faeaf900 100644 --- a/tests/posix/abort.c +++ b/tests/posix/abort.c @@ -1,5 +1,5 @@ -#include #include +#include #include void handler(int sig, siginfo_t *info, void *ctx) { diff --git a/tests/posix/accept4.c b/tests/posix/accept4.c index 3bc66625b7..3391a6b80a 100644 --- a/tests/posix/accept4.c +++ b/tests/posix/accept4.c @@ -1,12 +1,12 @@ -#include -#include -#include +#include #include -#include +#include +#include #include +#include #include -#include -#include +#include +#include #ifdef USE_HOST_LIBC #define TEST_PORT 31337 @@ -18,14 +18,13 @@ static struct sockaddr_in connect_addr, accept_addr; static int listen_fd; int permutations[] = { - 0, - SOCK_CLOEXEC, - SOCK_NONBLOCK, - SOCK_CLOEXEC | SOCK_NONBLOCK, + 0, + SOCK_CLOEXEC, + SOCK_NONBLOCK, + SOCK_CLOEXEC | SOCK_NONBLOCK, }; -static bool run_test(int flags) -{ +static bool run_test(int flags) { int connect_fd; int fd_flags, access; socklen_t addrlen; @@ -36,27 +35,42 @@ static bool run_test(int flags) int accept_fd = accept4(listen_fd, (struct sockaddr *)&accept_addr, &addrlen, flags); - if(accept_fd == -1) { + if (accept_fd == -1) { fprintf(stderr, "accept4 failed: %s\n", strerror(errno)); goto cleanup; } fd_flags = fcntl(accept_fd, F_GETFD); - if(!(!!(fd_flags & FD_CLOEXEC) == !!(flags & SOCK_CLOEXEC))) { - fprintf(stderr, "CLOEXEC mismatch, got %d instead of %d\n", !!(fd_flags & FD_CLOEXEC), !!(flags & SOCK_CLOEXEC)); + if (!(!!(fd_flags & FD_CLOEXEC) == !!(flags & SOCK_CLOEXEC))) { + fprintf( + stderr, + "CLOEXEC mismatch, got %d instead of %d\n", + !!(fd_flags & FD_CLOEXEC), + !!(flags & SOCK_CLOEXEC) + ); goto cleanup; } access = fcntl(accept_fd, F_GETFL); - if(!(!!(access & O_NONBLOCK) == !!(flags & SOCK_NONBLOCK))) { - fprintf(stderr, "NONBLOCK flag mismatch, %d vs %d\n", !!(access & O_NONBLOCK), !!(flags & SOCK_NONBLOCK)); + if (!(!!(access & O_NONBLOCK) == !!(flags & SOCK_NONBLOCK))) { + fprintf( + stderr, + "NONBLOCK flag mismatch, %d vs %d\n", + !!(access & O_NONBLOCK), + !!(flags & SOCK_NONBLOCK) + ); goto cleanup; } close(accept_fd); close(connect_fd); - fprintf(stderr, "tested CLOEXEC %d, NONBLOCK %d\n", !!(flags & SOCK_CLOEXEC), !!(flags & SOCK_NONBLOCK)); + fprintf( + stderr, + "tested CLOEXEC %d, NONBLOCK %d\n", + !!(flags & SOCK_CLOEXEC), + !!(flags & SOCK_NONBLOCK) + ); return true; cleanup: @@ -65,8 +79,7 @@ static bool run_test(int flags) return false; } -static int socket_setup(void) -{ +static int socket_setup(void) { struct sockaddr_in addr; int reuseaddr; @@ -77,7 +90,7 @@ static int socket_setup(void) int socket_fd = socket(AF_INET, SOCK_STREAM, 0); - if(socket_fd == -1) { + if (socket_fd == -1) { fprintf(stderr, "socket failed: %s\n", strerror(errno)); exit(1); } @@ -85,21 +98,21 @@ static int socket_setup(void) reuseaddr = 1; int ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)); - if(ret == -1) { + if (ret == -1) { fprintf(stderr, "setsockopt failed: %s\n", strerror(errno)); exit(1); } ret = bind(socket_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); - if(ret == -1) { + if (ret == -1) { fprintf(stderr, "bind failed: %s\n", strerror(errno)); exit(1); } ret = listen(socket_fd, 5); - if(ret == -1) { + if (ret == -1) { fprintf(stderr, "listen failed: %s\n", strerror(errno)); exit(1); } @@ -113,9 +126,9 @@ int main() { connect_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); connect_addr.sin_port = htons(TEST_PORT); - for(size_t i = 0; i < 4; i++) { + for (size_t i = 0; i < 4; i++) { listen_fd = socket_setup(); - if(!run_test(permutations[i])) { + if (!run_test(permutations[i])) { exit(1); } close(listen_fd); diff --git a/tests/posix/access.c b/tests/posix/access.c index ad7c859723..30a0da6339 100644 --- a/tests/posix/access.c +++ b/tests/posix/access.c @@ -1,8 +1,8 @@ -#include -#include -#include #include #include +#include +#include +#include #ifdef USE_HOST_LIBC #define TEST_FILE "access-host-libc.tmp" diff --git a/tests/posix/alarm.c b/tests/posix/alarm.c index 7629846af7..b8c27ae6fd 100644 --- a/tests/posix/alarm.c +++ b/tests/posix/alarm.c @@ -1,4 +1,3 @@ -#include #include #include #include @@ -8,7 +7,7 @@ static volatile int alarms_fired = 0; static void sigalrm_handler(int signal) { - if(signal == SIGALRM) + if (signal == SIGALRM) alarms_fired++; } @@ -27,7 +26,7 @@ int main() { sleep(2); - if(alarms_fired != 1) { + if (alarms_fired != 1) { fprintf(stderr, "alarm handler fired %u times instead of 1\n", alarms_fired); exit(1); } diff --git a/tests/posix/basename.c b/tests/posix/basename.c index c46c709c73..fcee187d32 100644 --- a/tests/posix/basename.c +++ b/tests/posix/basename.c @@ -4,9 +4,10 @@ int main() { /* intentionally a macro: basename modifies its argument */ -#define test_string(x, expectval) do { \ - char str[] = x; \ - assert(strcmp(basename(str), expectval) == 0); \ +#define test_string(x, expectval) \ + do { \ + char str[] = x; \ + assert(strcmp(basename(str), expectval) == 0); \ } while (0) test_string("/usr/lib", "lib"); diff --git a/tests/posix/dprintf.c b/tests/posix/dprintf.c index 4746edb86b..33e50c86a7 100644 --- a/tests/posix/dprintf.c +++ b/tests/posix/dprintf.c @@ -1,8 +1,8 @@ -#include -#include -#include #include #include +#include +#include +#include #ifdef USE_HOST_LIBC #define TEST_FILE "dprintf-host-libc.tmp" @@ -28,9 +28,7 @@ int main() { ssize_t num_read = read(fd, buf, 3); assert(num_read == 3); - assert(buf[0] == 'a' - && buf[1] == 'a' - && buf[2] == 'a'); + assert(buf[0] == 'a' && buf[1] == 'a' && buf[2] == 'a'); // All the tests pass, now we can unlink the file. ret = unlink(TEST_FILE); diff --git a/tests/posix/fdopen.c b/tests/posix/fdopen.c index 10dc1733b4..024c79ccf0 100644 --- a/tests/posix/fdopen.c +++ b/tests/posix/fdopen.c @@ -1,8 +1,8 @@ -#include #include +#include +#include #include #include -#include #define TEST_FILE "fdopen.tmp" diff --git a/tests/posix/ffs.c b/tests/posix/ffs.c index 3f7ba846c7..3c7bb65e4b 100644 --- a/tests/posix/ffs.c +++ b/tests/posix/ffs.c @@ -1,11 +1,11 @@ #include -#include #include +#include -int main(void){ - assert(ffs(0x8000) == 16); - assert(ffs(0) == 0); - assert(ffs(INT_MAX - 1) == 2); +int main(void) { + assert(ffs(0x8000) == 16); + assert(ffs(0) == 0); + assert(ffs(INT_MAX - 1) == 2); assert(ffs(INT_MAX) == 1); assert(ffs(INT_MIN) == (int)(sizeof(int) * CHAR_BIT)); assert(ffs(INT_MIN + 1) == 1); @@ -14,5 +14,5 @@ int main(void){ assert(ffs(i) - 1 == __builtin_ctz(i)); } - return 0; + return 0; } diff --git a/tests/posix/flockfile.c b/tests/posix/flockfile.c index 982311eb0d..80bcab71e3 100644 --- a/tests/posix/flockfile.c +++ b/tests/posix/flockfile.c @@ -1,7 +1,7 @@ #include -#include #include #include +#include #include static void *worker(void *arg) { diff --git a/tests/posix/fmemopen.c b/tests/posix/fmemopen.c index 4d5046eb00..fd2ccb26f9 100644 --- a/tests/posix/fmemopen.c +++ b/tests/posix/fmemopen.c @@ -60,7 +60,7 @@ int main() { assert(f); pos = ftell(f); - assert(pos == (long) (BUFFER1_SIZE - 1)); + assert(pos == (long)(BUFFER1_SIZE - 1)); ret = fseek(f, 0, SEEK_SET); assert(!ret); @@ -70,7 +70,7 @@ int main() { ret = fseek(f, 0, SEEK_END); assert(!ret); pos = ftell(f); - assert(pos == (long) (BUFFER1_SIZE - 1)); + assert(pos == (long)(BUFFER1_SIZE - 1)); fclose(f); @@ -81,7 +81,7 @@ int main() { ret = fseek(f, 0, SEEK_END); assert(!ret); pos = ftell(f); - assert(pos == (long) (BUFFER1_SIZE - 2)); + assert(pos == (long)(BUFFER1_SIZE - 2)); fclose(f); @@ -133,7 +133,7 @@ int main() { f = fmemopen(buf2, 0, "r"); assert(f || errno == EINVAL); - if(f) { + if (f) { memset(buf, 0, BUFFER1_SIZE); read = fread(buf, 10, 1, f); assert(!read); diff --git a/tests/posix/fopencookie.c b/tests/posix/fopencookie.c index 3de1bc0f6d..586c4bc1d4 100644 --- a/tests/posix/fopencookie.c +++ b/tests/posix/fopencookie.c @@ -14,22 +14,22 @@ struct testcookie { }; ssize_t cookie_read(void *c, char *buf, size_t size) { - (void) buf; + (void)buf; struct testcookie *cookie = c; cookie->read = true; return size; } ssize_t cookie_write(void *c, const char *buf, size_t size) { - (void) buf; + (void)buf; struct testcookie *cookie = c; cookie->write = true; return size; } int cookie_seek(void *c, off64_t *offset, int whence) { - (void) offset; - (void) whence; + (void)offset; + (void)whence; struct testcookie *cookie = c; cookie->seek = true; return 0; @@ -42,13 +42,13 @@ int cookie_close(void *c) { } int main() { - struct testcookie cookie = { false, false, false, false }; + struct testcookie cookie = {false, false, false, false}; cookie_io_functions_t funcs = { - .read = cookie_read, - .write = cookie_write, - .seek = cookie_seek, - .close = cookie_close, + .read = cookie_read, + .write = cookie_write, + .seek = cookie_seek, + .close = cookie_close, }; FILE *stream = fopencookie(&cookie, "w+", funcs); diff --git a/tests/posix/getaddrinfo.c b/tests/posix/getaddrinfo.c index d52c93ff8f..d6c1fe59d7 100644 --- a/tests/posix/getaddrinfo.c +++ b/tests/posix/getaddrinfo.c @@ -1,9 +1,9 @@ -#include #include -#include -#include +#include #include +#include #include +#include int main() { struct addrinfo *res = NULL; @@ -15,7 +15,7 @@ int main() { int ret = getaddrinfo(NULL, "443", &hints, &res); assert(ret == 0); - struct sockaddr_in *addr = (struct sockaddr_in*)(res[0].ai_addr); + struct sockaddr_in *addr = (struct sockaddr_in *)(res[0].ai_addr); assert(addr->sin_port == htons(443)); assert(res[0].ai_socktype == SOCK_STREAM); assert(res[0].ai_protocol == IPPROTO_TCP); @@ -34,7 +34,7 @@ int main() { ret = getaddrinfo("10.10.10.10", NULL, &hints, &res); assert(ret == 0); - addr = (struct sockaddr_in*)res[0].ai_addr; + addr = (struct sockaddr_in *)res[0].ai_addr; assert((addr->sin_addr.s_addr & 0xFF) == 10); assert(((addr->sin_addr.s_addr >> 8) & 0xFF) == 10); assert(((addr->sin_addr.s_addr >> 16) & 0xFF) == 10); diff --git a/tests/posix/getcwd.c b/tests/posix/getcwd.c index f3ba8da18b..154dd4de61 100644 --- a/tests/posix/getcwd.c +++ b/tests/posix/getcwd.c @@ -1,8 +1,8 @@ #include #include +#include #include #include -#include int main() { char buf[PATH_MAX]; diff --git a/tests/posix/getdelim.c b/tests/posix/getdelim.c index 9836123503..0c9e86b8d0 100644 --- a/tests/posix/getdelim.c +++ b/tests/posix/getdelim.c @@ -1,8 +1,8 @@ +#include #include #include -#include -#include #include +#include #ifdef USE_HOST_LIBC #define TEST_FILE "getdelim-host-libc.tmp" @@ -69,7 +69,7 @@ int main(void) { /* test with line = NULL and large len */ line = NULL; - len = (size_t) ~0; + len = (size_t)~0; assert(getdelim(&line, &len, 'e', fp) == 5); assert(!memcmp(line, "1234e", 6)); assert(5 < len); diff --git a/tests/posix/getnameinfo.c b/tests/posix/getnameinfo.c index d22a0ebbd9..2c3d0d66c9 100644 --- a/tests/posix/getnameinfo.c +++ b/tests/posix/getnameinfo.c @@ -1,6 +1,6 @@ -#include -#include #include +#include +#include #include #include @@ -10,13 +10,11 @@ int main() { assert(inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr)); char host[64]; - assert(!getnameinfo((struct sockaddr*)&addr, sizeof(addr), host, - sizeof(host), NULL, 0, 0)); + assert(!getnameinfo((struct sockaddr *)&addr, sizeof(addr), host, sizeof(host), NULL, 0, 0)); assert(inet_pton(AF_INET, "8.8.8.8", &addr.sin_addr)); - assert(!getnameinfo((struct sockaddr*)&addr, sizeof(addr), host, - sizeof(host), NULL, 0, 0)); + assert(!getnameinfo((struct sockaddr *)&addr, sizeof(addr), host, sizeof(host), NULL, 0, 0)); assert(!strcmp(host, "dns.google")); return 0; } diff --git a/tests/posix/getservbyname.c b/tests/posix/getservbyname.c index 8c51710d37..355b34db3a 100644 --- a/tests/posix/getservbyname.c +++ b/tests/posix/getservbyname.c @@ -1,7 +1,7 @@ +#include #include #include #include -#include int main() { struct servent *ret = getservbyname("http", "tcp"); diff --git a/tests/posix/getservbyport.c b/tests/posix/getservbyport.c index f522d717c5..4c7203fc7a 100644 --- a/tests/posix/getservbyport.c +++ b/tests/posix/getservbyport.c @@ -1,8 +1,8 @@ -#include #include -#include #include +#include #include +#include int main() { struct servent *ret = getservbyport(htons(80), "tcp"); diff --git a/tests/posix/grp.c b/tests/posix/grp.c index bf4f147134..abaf528e01 100644 --- a/tests/posix/grp.c +++ b/tests/posix/grp.c @@ -1,11 +1,11 @@ -#include -#include -#include -#include #include -#include #include +#include #include +#include +#include +#include +#include void check_root_group(struct group *grp) { assert(grp); @@ -32,8 +32,7 @@ void check_root_group(struct group *grp) { } } -int main() -{ +int main() { struct group grp, *result = NULL; char *buf; size_t bufsize; @@ -87,17 +86,17 @@ int main() result = getgrent(); assert(result); grp.gr_name = strdup(result->gr_name); - if(result->gr_passwd) { + if (result->gr_passwd) { password = true; } grp.gr_passwd = strdup(result->gr_passwd); grp.gr_gid = result->gr_gid; assert(grp.gr_name); - if(password) + if (password) assert(grp.gr_passwd); assert(grp.gr_name); - if(password) + if (password) assert(grp.gr_passwd); endgrent(); @@ -105,12 +104,12 @@ int main() result = getgrent(); assert(result); assert(strcmp(result->gr_name, grp.gr_name) == 0); - if(password) + if (password) assert(strcmp(result->gr_passwd, grp.gr_passwd) == 0); assert(result->gr_gid == grp.gr_gid); free(grp.gr_name); - if(password) + if (password) free(grp.gr_passwd); grp.gr_name = "managarm"; diff --git a/tests/posix/index.c b/tests/posix/index.c index 63be75db9c..2f04a6c1cc 100644 --- a/tests/posix/index.c +++ b/tests/posix/index.c @@ -1,20 +1,20 @@ #include -#include #include +#include int main() { - char str[] = "This is a sample string"; - char *pch; - // The character 's' is at position 4, 7, 11 and 18 - pch = index(str, 's'); - assert(pch - str + 1 == 4); - pch = index(pch + 1, 's'); - assert(pch - str + 1 == 7); - pch = index(pch + 1, 's'); - assert(pch - str + 1 == 11); - pch = index(pch + 1, 's'); - assert(pch - str + 1 == 18); - pch = index(pch + 1, 's'); - assert(pch == NULL); - return 0; + char str[] = "This is a sample string"; + char *pch; + // The character 's' is at position 4, 7, 11 and 18 + pch = index(str, 's'); + assert(pch - str + 1 == 4); + pch = index(pch + 1, 's'); + assert(pch - str + 1 == 7); + pch = index(pch + 1, 's'); + assert(pch - str + 1 == 11); + pch = index(pch + 1, 's'); + assert(pch - str + 1 == 18); + pch = index(pch + 1, 's'); + assert(pch == NULL); + return 0; } diff --git a/tests/posix/inet_ntop.c b/tests/posix/inet_ntop.c index feca26cd2b..8d8007224c 100644 --- a/tests/posix/inet_ntop.c +++ b/tests/posix/inet_ntop.c @@ -1,27 +1,30 @@ #include -#include #include +#include #include int main() { struct in_addr addr; - addr.s_addr = (1 << 24) | - (1 << 16) | (1 << 8) | 1; + addr.s_addr = (1 << 24) | (1 << 16) | (1 << 8) | 1; char buf[INET_ADDRSTRLEN]; assert(inet_ntop(AF_INET, &addr, buf, INET_ADDRSTRLEN) != NULL); assert(strncmp("1.1.1.1", buf, INET_ADDRSTRLEN) == 0); - struct in6_addr addr2 = { .s6_addr = {0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0x1} }; + struct in6_addr addr2 = { + .s6_addr = {0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0x1} + }; char buf2[INET6_ADDRSTRLEN]; assert(inet_ntop(AF_INET6, &addr2, buf2, INET6_ADDRSTRLEN) != NULL); assert(strncmp("2001:db8::1:0:0:1", buf2, INET6_ADDRSTRLEN) == 0); - struct in6_addr addr3 = { .s6_addr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} }; + struct in6_addr addr3 = {.s6_addr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}; char buf3[INET6_ADDRSTRLEN]; assert(inet_ntop(AF_INET6, &addr3, buf3, INET6_ADDRSTRLEN) != NULL); assert(strncmp("::1", buf3, INET6_ADDRSTRLEN) == 0); - struct in6_addr addr4 = { .s6_addr = {0x20, 0x1, 0xd, 0xb8, 00, 00, 00, 0x1, 00, 0x1, 00, 0x1, 00, 0x1, 00, 0x1} }; + struct in6_addr addr4 = { + .s6_addr = {0x20, 0x1, 0xd, 0xb8, 00, 00, 00, 0x1, 00, 0x1, 00, 0x1, 00, 0x1, 00, 0x1} + }; char buf4[INET6_ADDRSTRLEN]; assert(inet_ntop(AF_INET6, &addr4, buf4, INET6_ADDRSTRLEN) != NULL); assert(strncmp("2001:db8:0:1:1:1:1:1", buf4, INET6_ADDRSTRLEN) == 0); diff --git a/tests/posix/inet_pton.c b/tests/posix/inet_pton.c index 6c0f3420ef..0529858135 100644 --- a/tests/posix/inet_pton.c +++ b/tests/posix/inet_pton.c @@ -13,4 +13,3 @@ int main() { assert(!inet_pton(AF_INET, "a.b.c.d", &addr)); return 0; } - diff --git a/tests/posix/memrchr.c b/tests/posix/memrchr.c index 99e3e25a6a..556c6a8feb 100644 --- a/tests/posix/memrchr.c +++ b/tests/posix/memrchr.c @@ -1,11 +1,11 @@ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif +#include #include #include -#include -int main () { +int main() { char str[] = "The Last Supper by Leonardo da Vinci"; char *str_temp; diff --git a/tests/posix/mkstemp.c b/tests/posix/mkstemp.c index 3003b1436c..0d4115c10f 100644 --- a/tests/posix/mkstemp.c +++ b/tests/posix/mkstemp.c @@ -1,10 +1,10 @@ #include -#include -#include -#include #include #include #include +#include +#include +#include void validate_pattern(char *p) { assert(memcmp(p, "XXXXXX", 6)); diff --git a/tests/posix/open_memstream.c b/tests/posix/open_memstream.c index 03470030b9..e330b581a4 100644 --- a/tests/posix/open_memstream.c +++ b/tests/posix/open_memstream.c @@ -1,6 +1,6 @@ +#include #include #include -#include #define WRITE_NO 1024 @@ -28,7 +28,7 @@ int main() { // Stream should be expanded, size should be == 2*WRITE_NO. assert(!fseek(fp, WRITE_NO, SEEK_END)); assert(!fflush(fp)); - assert(size == 2*WRITE_NO); + assert(size == 2 * WRITE_NO); assert(buf[size] == '\0'); // Check if it's filled with zero's. @@ -42,7 +42,7 @@ int main() { assert(fwrite(&c, sizeof(char), 1, fp) == 1); // Check if that happened. - assert(size == 2*WRITE_NO); + assert(size == 2 * WRITE_NO); for (size_t i = WRITE_NO; i < size; i++) assert(buf[i] == c); assert(buf[size] == '\0'); @@ -53,7 +53,7 @@ int main() { assert(fwrite(&c, sizeof(char), 1, fp) == 1); // Check if that happened. - assert(size == 2*WRITE_NO); + assert(size == 2 * WRITE_NO); for (size_t i = 0; i < size; i++) assert(buf[i] == c); assert(buf[size] == '\0'); diff --git a/tests/posix/pause.c b/tests/posix/pause.c index 054c5a48b9..3901d4fed6 100644 --- a/tests/posix/pause.c +++ b/tests/posix/pause.c @@ -1,20 +1,18 @@ #include +#include #include -#include -#include #include -#include +#include #include +#include -static void noop(int x) { - (void)x; -} +static void noop(int x) { (void)x; } int main() { signal(SIGUSR1, &noop); int pid; - switch(pid = fork()) { + switch (pid = fork()) { case -1: perror("fork"); abort(); diff --git a/tests/posix/popen.c b/tests/posix/popen.c index 87bbde274e..18a0259d72 100644 --- a/tests/posix/popen.c +++ b/tests/posix/popen.c @@ -1,6 +1,6 @@ +#include #include #include -#include #include #ifdef USE_HOST_LIBC diff --git a/tests/posix/posix_memalign.c b/tests/posix/posix_memalign.c index b03d62f57d..7378a087ca 100644 --- a/tests/posix/posix_memalign.c +++ b/tests/posix/posix_memalign.c @@ -1,7 +1,7 @@ -#include #include -#include #include +#include +#include int main() { void *p = NULL; @@ -12,7 +12,10 @@ int main() { // align must be a multiple of sizeof(void *) assert(posix_memalign(&p, sizeof(void *) / 2, 8) == EINVAL && p == NULL); - assert(posix_memalign(&p, sizeof(void *), sizeof(void *)) == 0 && p != NULL && (uintptr_t)p % sizeof(void *) == 0); + assert( + posix_memalign(&p, sizeof(void *), sizeof(void *)) == 0 && p != NULL && + (uintptr_t)p % sizeof(void *) == 0 + ); free(p); assert(posix_memalign(&p, 256, 1) == 0 && p != NULL && (uintptr_t)p % 256 == 0); free(p); diff --git a/tests/posix/posix_spawn.c b/tests/posix/posix_spawn.c index cc5ccff293..0da9d38fde 100644 --- a/tests/posix/posix_spawn.c +++ b/tests/posix/posix_spawn.c @@ -1,38 +1,37 @@ -#include #include #include +#include #include -#include #include #include +#include extern char **environ; -void run_cmd(char *cmd) -{ - pid_t pid; - char *argv[] = {"sh", "-c", cmd, NULL}; - int status; - printf("Run command: %s\n", cmd); - status = posix_spawn(&pid, "/bin/sh", NULL, NULL, argv, environ); - if(status == 0) { - printf("Child pid: %i\n", pid); - if(waitpid(pid, &status, 0) != -1) { - printf("Child exited with status %i\n", status); - printf("Child exit status: %i\n", WEXITSTATUS(status)); - assert(WEXITSTATUS(status) == 0); - } else { - perror("waitpid"); - assert(0 == 1); - } - } else { - printf("posix_spawn: %s\n", strerror(status)); - assert(0 == 1); - } +void run_cmd(char *cmd) { + pid_t pid; + char *argv[] = {"sh", "-c", cmd, NULL}; + int status; + printf("Run command: %s\n", cmd); + status = posix_spawn(&pid, "/bin/sh", NULL, NULL, argv, environ); + if (status == 0) { + printf("Child pid: %i\n", pid); + if (waitpid(pid, &status, 0) != -1) { + printf("Child exited with status %i\n", status); + printf("Child exit status: %i\n", WEXITSTATUS(status)); + assert(WEXITSTATUS(status) == 0); + } else { + perror("waitpid"); + assert(0 == 1); + } + } else { + printf("posix_spawn: %s\n", strerror(status)); + assert(0 == 1); + } } int main() { - run_cmd(":"); - return 0; + run_cmd(":"); + return 0; } diff --git a/tests/posix/pthread_atfork.c b/tests/posix/pthread_atfork.c index 45be136b80..3a70f2717d 100644 --- a/tests/posix/pthread_atfork.c +++ b/tests/posix/pthread_atfork.c @@ -1,10 +1,10 @@ #include +#include #include #include #include -#include -#include #include +#include _Atomic int prepare_order = 0; _Atomic int parent_order = 0; diff --git a/tests/posix/pthread_attr.c b/tests/posix/pthread_attr.c index 99b55106dc..03fd3bcc08 100644 --- a/tests/posix/pthread_attr.c +++ b/tests/posix/pthread_attr.c @@ -1,10 +1,10 @@ -#include +#include #include #include -#include +#include +#include #include #include -#include static void test_detachstate() { pthread_attr_t attr; @@ -12,19 +12,22 @@ static void test_detachstate() { int detachstate; assert(!pthread_attr_getdetachstate(&attr, &detachstate)); assert(detachstate == PTHREAD_CREATE_DETACHED); - assert(pthread_attr_setdetachstate(&attr, 2* (PTHREAD_CREATE_DETACHED + - PTHREAD_CREATE_JOINABLE)) == EINVAL); + assert( + pthread_attr_setdetachstate( + &attr, 2 * (PTHREAD_CREATE_DETACHED + PTHREAD_CREATE_JOINABLE) + ) == EINVAL + ); } static void *stacksize_worker(void *arg) { - size_t default_stacksize = (*(size_t*)arg); - size_t alloc_size = default_stacksize + default_stacksize/2; + size_t default_stacksize = (*(size_t *)arg); + size_t alloc_size = default_stacksize + default_stacksize / 2; void *area = alloca(alloc_size); // If the allocated stack was not enough this will crash. // Trample both the start and end of the area so it works on both upwards- // and downwards-growing stacks. - *(volatile char*)area = 1; - *(volatile char*)(area + alloc_size - 1) = 1; + *(volatile char *)area = 1; + *(volatile char *)(area + alloc_size - 1) = 1; return NULL; } @@ -54,8 +57,9 @@ static void test_scope() { int scope; assert(!pthread_attr_getscope(&attr, &scope)); assert(scope == PTHREAD_SCOPE_SYSTEM); - assert(pthread_attr_setscope(&attr, 2* (PTHREAD_SCOPE_SYSTEM + - PTHREAD_SCOPE_PROCESS)) == EINVAL); + assert( + pthread_attr_setscope(&attr, 2 * (PTHREAD_SCOPE_SYSTEM + PTHREAD_SCOPE_PROCESS)) == EINVAL + ); } static void test_inheritsched() { @@ -64,8 +68,10 @@ static void test_inheritsched() { int inheritsched; assert(!pthread_attr_getinheritsched(&attr, &inheritsched)); assert(inheritsched == PTHREAD_INHERIT_SCHED); - assert(pthread_attr_setinheritsched(&attr, 2* (PTHREAD_INHERIT_SCHED + - PTHREAD_EXPLICIT_SCHED)) == EINVAL); + assert( + pthread_attr_setinheritsched(&attr, 2 * (PTHREAD_INHERIT_SCHED + PTHREAD_EXPLICIT_SCHED)) == + EINVAL + ); } static void test_schedparam() { @@ -83,26 +89,27 @@ static void test_schedpolicy() { int policy; assert(!pthread_attr_getschedpolicy(&attr, &policy)); assert(policy == SCHED_FIFO); - assert(pthread_attr_setinheritsched(&attr, 2* (SCHED_FIFO + SCHED_RR + - SCHED_OTHER)) == EINVAL); + assert( + pthread_attr_setinheritsched(&attr, 2 * (SCHED_FIFO + SCHED_RR + SCHED_OTHER)) == EINVAL + ); } static void *stackaddr_worker(void *arg) { - void *addr = *(void**)arg; + void *addr = *(void **)arg; void *sp; #if defined(__x86_64__) - asm volatile ("mov %%rsp, %0" : "=r"(sp)); + asm volatile("mov %%rsp, %0" : "=r"(sp)); #elif defined(__i386__) - asm volatile ("mov %%esp, %0" : "=r"(sp)); + asm volatile("mov %%esp, %0" : "=r"(sp)); #elif defined(__aarch64__) - asm volatile ("mov %0, sp" : "=r"(sp)); -#elif defined (__riscv) - asm volatile ("mv %0, sp" : "=r"(sp)); + asm volatile("mov %0, sp" : "=r"(sp)); +#elif defined(__riscv) + asm volatile("mv %0, sp" : "=r"(sp)); #elif defined(__m68k__) - asm volatile ("move.l %%sp, %0" : "=r"(sp)); + asm volatile("move.l %%sp, %0" : "=r"(sp)); #else -# error Unknown architecture +#error Unknown architecture #endif // Check if our stack pointer is in a sane range. @@ -116,8 +123,7 @@ static void test_stackaddr() { assert(!pthread_attr_init(&attr)); size_t size; assert(!pthread_attr_getstacksize(&attr, &size)); - void *addr = mmap(NULL, size, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + void *addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); assert(!pthread_attr_setstack(&attr, addr, size)); assert(!pthread_attr_setguardsize(&attr, 0)); void *new_addr; @@ -135,7 +141,7 @@ static void test_stackaddr() { #if !defined(USE_HOST_LIBC) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 32) static void test_stack() { pthread_attr_t attr; - void *stackaddr = (void*)1; + void *stackaddr = (void *)1; size_t stacksize = PTHREAD_STACK_MIN; assert(!pthread_attr_setstack(&attr, stackaddr, stacksize)); diff --git a/tests/posix/pthread_barrier.c b/tests/posix/pthread_barrier.c index 31cc69610e..33c65b5587 100644 --- a/tests/posix/pthread_barrier.c +++ b/tests/posix/pthread_barrier.c @@ -1,6 +1,6 @@ +#include #include #include -#include pthread_barrier_t barrier; _Atomic int hitBarrierCount, pastBarrierCount; diff --git a/tests/posix/pthread_cancel.c b/tests/posix/pthread_cancel.c index ca4ca346c3..e3a33c2d14 100644 --- a/tests/posix/pthread_cancel.c +++ b/tests/posix/pthread_cancel.c @@ -12,18 +12,20 @@ static void *worker1(void *arg) { worker_ready = 1; - while (1) sleep(1); + while (1) + sleep(1); return NULL; } static void *worker2(void *arg) { - (void) arg; + (void)arg; assert(!pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)); worker_ready = 1; - while(!main_ready); + while (!main_ready) + ; // Cancellation point - we should cancel right now sleep(1); @@ -33,12 +35,13 @@ static void *worker2(void *arg) { } static void *worker3(void *arg) { - (void) arg; + (void)arg; assert(!pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)); worker_ready = 1; - while(!main_ready); + while (!main_ready) + ; // Cancellation point - we should cancel right now pthread_testcancel(); @@ -48,7 +51,7 @@ static void *worker3(void *arg) { } static void *worker4(void *arg) { - (void) arg; + (void)arg; assert(!pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)); worker_ready = 1; @@ -65,12 +68,13 @@ static void *worker5(void *arg) { worker_ready = 1; - while(!main_ready); + while (!main_ready) + ; // Cancellation point - we should NOT cancel right now pthread_testcancel(); - int *arg_int = (int*)arg; + int *arg_int = (int *)arg; *arg_int = 1; return NULL; @@ -89,7 +93,8 @@ int main() { int ret = pthread_create(&thread, NULL, &worker1, NULL); assert(!ret); - while (!worker_ready); + while (!worker_ready) + ; ret = pthread_cancel(thread); assert(!ret); check_result(thread); @@ -100,7 +105,8 @@ int main() { ret = pthread_create(&thread, NULL, &worker2, NULL); assert(!ret); - while(!worker_ready); + while (!worker_ready) + ; ret = pthread_cancel(thread); assert(!ret); main_ready = 1; @@ -112,7 +118,8 @@ int main() { ret = pthread_create(&thread, NULL, &worker3, NULL); assert(!ret); - while(!worker_ready); + while (!worker_ready) + ; ret = pthread_cancel(thread); assert(!ret); main_ready = 1; @@ -123,7 +130,8 @@ int main() { ret = pthread_create(&thread, NULL, &worker4, NULL); assert(!ret); - while(!worker_ready); + while (!worker_ready) + ; ret = pthread_cancel(thread); assert(!ret); main_ready = 1; @@ -137,7 +145,8 @@ int main() { ret = pthread_create(&thread, NULL, &worker5, &pthread_arg); assert(!ret); - while(!worker_ready); + while (!worker_ready) + ; main_ready = 1; void *ret_val = NULL; diff --git a/tests/posix/pthread_cleanup.c b/tests/posix/pthread_cleanup.c index b6136aaa93..779d4353a4 100644 --- a/tests/posix/pthread_cleanup.c +++ b/tests/posix/pthread_cleanup.c @@ -1,12 +1,10 @@ -#include #include #include +#include _Atomic uintptr_t cleanup_val = 0; -static void cleanup(void *arg) { - cleanup_val = (uintptr_t)arg; -} +static void cleanup(void *arg) { cleanup_val = (uintptr_t)arg; } static void *worker(void *arg) { (void)arg; @@ -39,4 +37,3 @@ int main() { return 0; } - diff --git a/tests/posix/pthread_create.c b/tests/posix/pthread_create.c index b78674fad8..72de0c410a 100644 --- a/tests/posix/pthread_create.c +++ b/tests/posix/pthread_create.c @@ -1,11 +1,11 @@ #include -#include #include +#include int variable = 0; static void *worker(void *arg) { - (void) arg; + (void)arg; variable = 1; return NULL; } diff --git a/tests/posix/pthread_key.c b/tests/posix/pthread_key.c index 40bd8825ac..59b46fbbeb 100644 --- a/tests/posix/pthread_key.c +++ b/tests/posix/pthread_key.c @@ -1,7 +1,7 @@ #include -#include #include #include +#include _Atomic int dtors_entered = 0; pthread_key_t key3; diff --git a/tests/posix/pthread_mutex.c b/tests/posix/pthread_mutex.c index 6ee202e47d..16e2fc198f 100644 --- a/tests/posix/pthread_mutex.c +++ b/tests/posix/pthread_mutex.c @@ -1,12 +1,13 @@ -#include #include #include +#include -#define TEST_ATTR(attr, field, value) ({ \ - int x; \ - assert(!pthread_mutexattr_set ## field (&(attr), (value))); \ - assert(!pthread_mutexattr_get ## field (&(attr), &x)); \ - assert(x == (value)); \ +#define TEST_ATTR(attr, field, value) \ + ({ \ + int x; \ + assert(!pthread_mutexattr_set##field(&(attr), (value))); \ + assert(!pthread_mutexattr_get##field(&(attr), &x)); \ + assert(x == (value)); \ }) int variable; diff --git a/tests/posix/pthread_schedparam.c b/tests/posix/pthread_schedparam.c index 6a3a886111..a64f3cbe03 100644 --- a/tests/posix/pthread_schedparam.c +++ b/tests/posix/pthread_schedparam.c @@ -5,7 +5,7 @@ int main() { struct sched_param param = { - .sched_priority = 100, + .sched_priority = 100, }; int policy = 0xDEADBEEF; @@ -19,7 +19,7 @@ int main() { ret = pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m); assert(!ret || ret == EPERM); - if(ret == EPERM) { + if (ret == EPERM) { exit(0); } diff --git a/tests/posix/pthread_thread_local.c b/tests/posix/pthread_thread_local.c index 38651b1704..7228877f5c 100644 --- a/tests/posix/pthread_thread_local.c +++ b/tests/posix/pthread_thread_local.c @@ -1,18 +1,19 @@ -#include -#include #include - -_Thread_local unsigned int counter = 9999; +#include +#include + +_Thread_local unsigned int counter = 9999; _Thread_local unsigned int uninitialized; - -void *check_counter(void *arg) -{ + +void *check_counter(void *arg) { (void)arg; fprintf(stderr, "counter for worker thread: %d, at %p\n", counter, &counter); fflush(stderr); assert(counter == 9999); - fprintf(stderr, "uninitialized data for worker thread: %d, at %p\n", uninitialized, &uninitialized); + fprintf( + stderr, "uninitialized data for worker thread: %d, at %p\n", uninitialized, &uninitialized + ); fflush(stderr); assert(uninitialized == 0); @@ -24,14 +25,15 @@ void *check_counter(void *arg) assert(uninitialized == 1); return NULL; } - -int main() -{ + +int main() { fprintf(stderr, "counter for main thread: %d, at %p\n", counter, &counter); fflush(stderr); assert(counter == 9999); - fprintf(stderr, "uninitialized data for main thread: %d, at %p\n", uninitialized, &uninitialized); + fprintf( + stderr, "uninitialized data for main thread: %d, at %p\n", uninitialized, &uninitialized + ); fflush(stderr); assert(uninitialized == 0); diff --git a/tests/posix/pwd.c b/tests/posix/pwd.c index 9645646096..283f2bad64 100644 --- a/tests/posix/pwd.c +++ b/tests/posix/pwd.c @@ -1,13 +1,12 @@ -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include -int main() -{ +int main() { struct passwd pwd, *result = NULL; char *buf; size_t bufsize; @@ -113,7 +112,8 @@ int main() assert(putpwent(&pwd, tmp) == 0); rewind(tmp); - char *expected = "managarm:passwordhash:1234:12345:/etc/password test:/home/managarm:/usr/bin/bash\n"; + char *expected = + "managarm:passwordhash:1234:12345:/etc/password test:/home/managarm:/usr/bin/bash\n"; size_t expectedlen = strlen(expected); size_t readsize = fread(buf, 1, bufsize, tmp); diff --git a/tests/posix/readv-writev.c b/tests/posix/readv-writev.c index 899de99577..33569db95c 100644 --- a/tests/posix/readv-writev.c +++ b/tests/posix/readv-writev.c @@ -1,8 +1,8 @@ #include #include #include -#include #include +#include #ifdef USE_HOST_LIBC #define TEST_FILE "readv-writev-host-libc.tmp" @@ -21,14 +21,14 @@ int main() { char str1[] = "world!"; struct iovec bufs[2] = { - { - .iov_base = &str0, - .iov_len = strlen(str0), - }, - { - .iov_base = &str1, - .iov_len = strlen(str1), - }, + { + .iov_base = &str0, + .iov_len = strlen(str0), + }, + { + .iov_base = &str1, + .iov_len = strlen(str1), + }, }; ssize_t written = writev(fd, bufs, 2); diff --git a/tests/posix/realpath.c b/tests/posix/realpath.c index 60eb812b6d..78a747ce00 100644 --- a/tests/posix/realpath.c +++ b/tests/posix/realpath.c @@ -1,10 +1,10 @@ -#include -#include #include -#include -#include -#include #include +#include +#include +#include +#include +#include #ifdef USE_HOST_LIBC #define TEST_BASE "/tmp/mlibc-realpath-host-libc" @@ -59,13 +59,12 @@ void signal_handler(int sig, siginfo_t *info, void *ctx) { abort(); } -#define TEST_PATH(rpath, expected) \ - path = realpath(rpath, NULL); \ - assert(path); \ - assert(!strcmp(path, expected)); \ +#define TEST_PATH(rpath, expected) \ + path = realpath(rpath, NULL); \ + assert(path); \ + assert(!strcmp(path, expected)); \ free(path); - int main() { char *path; @@ -77,22 +76,22 @@ int main() { prepare(); - TEST_PATH(TEST_BASE "/dir1/", TEST_BASE "/dir1"); - TEST_PATH(TEST_BASE "/dir1/../dir2", TEST_BASE "/dir2"); - TEST_PATH(TEST_BASE "/dir1/abs-link/", TEST_BASE "/dir2"); - TEST_PATH(TEST_BASE "/dir1/rel-link/", TEST_BASE "/dir2"); - TEST_PATH(TEST_BASE "/dir1/abs-link/../", TEST_BASE ""); - TEST_PATH(TEST_BASE "/dir1/rel-link/../", TEST_BASE ""); + TEST_PATH(TEST_BASE "/dir1/", TEST_BASE "/dir1"); + TEST_PATH(TEST_BASE "/dir1/../dir2", TEST_BASE "/dir2"); + TEST_PATH(TEST_BASE "/dir1/abs-link/", TEST_BASE "/dir2"); + TEST_PATH(TEST_BASE "/dir1/rel-link/", TEST_BASE "/dir2"); + TEST_PATH(TEST_BASE "/dir1/abs-link/../", TEST_BASE ""); + TEST_PATH(TEST_BASE "/dir1/rel-link/../", TEST_BASE ""); TEST_PATH(TEST_BASE "/dir1/abs-link/../dir1/abs-link/", TEST_BASE "/dir2"); TEST_PATH(TEST_BASE "/dir1/rel-link/../dir1/rel-link/", TEST_BASE "/dir2"); TEST_PATH(TEST_BASE "/dir1/abs-link/../dir1/rel-link/", TEST_BASE "/dir2"); TEST_PATH(TEST_BASE "/dir1/rel-link/../dir1/abs-link/", TEST_BASE "/dir2"); - TEST_PATH(TEST_BASE "/dir1/abs-link-no-trail/", TEST_BASE "/dir2"); - TEST_PATH(TEST_BASE "/dir1/abs-link-trail/", TEST_BASE "/dir2"); + TEST_PATH(TEST_BASE "/dir1/abs-link-no-trail/", TEST_BASE "/dir2"); + TEST_PATH(TEST_BASE "/dir1/abs-link-trail/", TEST_BASE "/dir2"); TEST_PATH("/tmp", "/tmp"); - TEST_PATH("/", "/"); - TEST_PATH("//", "/"); + TEST_PATH("/", "/"); + TEST_PATH("//", "/"); cleanup(1); diff --git a/tests/posix/regex.c b/tests/posix/regex.c index 6c2ca3f0dd..87a979c072 100644 --- a/tests/posix/regex.c +++ b/tests/posix/regex.c @@ -1,8 +1,8 @@ +#include #include #include #include -#include - + int main(void) { char *testString = "mlibc is the best best best libc"; char *pattern = "\\(be[a-z]t\\) \\1"; @@ -15,14 +15,22 @@ int main(void) { rc = regexec(®, testString, 2, matches, 0); assert(!rc); - printf("Whole pattern: \"%.*s\" at %zd-%zd.\n", - (int)(matches[0].rm_eo - matches[0].rm_so), &testString[matches[0].rm_so], - (ssize_t)matches[0].rm_so, (ssize_t)(matches[0].rm_eo - 1)); + printf( + "Whole pattern: \"%.*s\" at %zd-%zd.\n", + (int)(matches[0].rm_eo - matches[0].rm_so), + &testString[matches[0].rm_so], + (ssize_t)matches[0].rm_so, + (ssize_t)(matches[0].rm_eo - 1) + ); assert(matches[0].rm_so == 13 && matches[0].rm_eo == 22); - printf("Substring: \"%.*s\" at %zd-%zd.\n", - (int)(matches[1].rm_eo - matches[1].rm_so), &testString[matches[1].rm_so], - (ssize_t)matches[1].rm_so, (ssize_t)matches[1].rm_eo - 1); + printf( + "Substring: \"%.*s\" at %zd-%zd.\n", + (int)(matches[1].rm_eo - matches[1].rm_so), + &testString[matches[1].rm_so], + (ssize_t)matches[1].rm_so, + (ssize_t)matches[1].rm_eo - 1 + ); assert(matches[1].rm_so == 13 && matches[1].rm_eo == 17); regfree(®); diff --git a/tests/posix/rindex.c b/tests/posix/rindex.c index 0eb2f5476c..248d0b2533 100644 --- a/tests/posix/rindex.c +++ b/tests/posix/rindex.c @@ -1,11 +1,11 @@ -#include #include +#include int main() { - char str[] = "This is a sample string"; - char *pch; - pch = rindex(str, 's'); - // The last occurence of 's' is at position 18 - assert(pch - str + 1 == 18); - return 0; + char str[] = "This is a sample string"; + char *pch; + pch = rindex(str, 's'); + // The last occurence of 's' is at position 18 + assert(pch - str + 1 == 18); + return 0; } diff --git a/tests/posix/rlimits.c b/tests/posix/rlimits.c index 3565521494..87f91eaf2f 100644 --- a/tests/posix/rlimits.c +++ b/tests/posix/rlimits.c @@ -1,26 +1,26 @@ -#include -#include -#include #include +#include +#include #include +#include int main() { struct rlimit getlim, setlim; - setlim.rlim_cur = 16; - setlim.rlim_max = 4096; + setlim.rlim_cur = 16; + setlim.rlim_max = 4096; int ret = setrlimit(RLIMIT_NOFILE, &setlim); - if(ret == -1) { - fprintf(stderr, "%s\n", strerror(errno)); + if (ret == -1) { + fprintf(stderr, "%s\n", strerror(errno)); assert(!ret); } - assert(!getrlimit(RLIMIT_NOFILE, &getlim)); + assert(!getrlimit(RLIMIT_NOFILE, &getlim)); assert(setlim.rlim_cur == getlim.rlim_cur); assert(setlim.rlim_max == getlim.rlim_max); - return 0; + return 0; } diff --git a/tests/posix/search.c b/tests/posix/search.c index c75cfc5d4d..7978db2ce3 100644 --- a/tests/posix/search.c +++ b/tests/posix/search.c @@ -1,22 +1,22 @@ -#include #include +#include +#include #include #include -#include static int compare(const void *pa, const void *pb) { - if (*(int*)pa < *(int*) pb) + if (*(int *)pa < *(int *)pb) return -1; - if (*(int*)pa > *(int*) pb) + if (*(int *)pa > *(int *)pb) return 1; return 0; } static void check_key(int key, void *root) { int keyp = key; - void *ret = tfind((void*) &keyp, &root, compare); + void *ret = tfind((void *)&keyp, &root, compare); assert(ret); - assert(**((int **) ret) == key); + assert(**((int **)ret) == key); } static int freed = 0; @@ -33,9 +33,9 @@ int main() { assert(ptr); *ptr = i; - void *ret = tsearch((void*) ptr, &root, compare); + void *ret = tsearch((void *)ptr, &root, compare); assert(ret); - assert(**((int **) ret) == i); + assert(**((int **)ret) == i); } // Test a couple of keys @@ -45,7 +45,7 @@ int main() { // Verify NULL on non-existent key int key = -1; - void *ret = tfind((void*) &key, &root, compare); + void *ret = tfind((void *)&key, &root, compare); assert(ret == NULL); tdestroy(root, free_key); @@ -54,10 +54,7 @@ int main() { assert(hcreate(3)); // Search for a non-existent entry - ENTRY entry = { - .key = (char *)"foo", - .data = (void *)0x12345678 - }; + ENTRY entry = {.key = (char *)"foo", .data = (void *)0x12345678}; ENTRY *result = hsearch(entry, FIND); assert(!result); assert(errno == ESRCH); diff --git a/tests/posix/semaphore.c b/tests/posix/semaphore.c index f250cd02ea..e35a2dda41 100644 --- a/tests/posix/semaphore.c +++ b/tests/posix/semaphore.c @@ -1,6 +1,6 @@ -#include #include #include +#include int main() { sem_t sem; diff --git a/tests/posix/setpriority.c b/tests/posix/setpriority.c index d674e576c8..12c6d1b6fa 100644 --- a/tests/posix/setpriority.c +++ b/tests/posix/setpriority.c @@ -1,7 +1,7 @@ #include #include -#include #include +#include #include #include #include @@ -14,7 +14,7 @@ int main() { int ret = setpriority(PRIO_PROCESS, getpid(), original_priority + 1); - if(ret) { + if (ret) { fprintf(stderr, "%s", strerror(errno)); exit(1); } diff --git a/tests/posix/sigaltstack.c b/tests/posix/sigaltstack.c index 02da78cc16..3afbf58b93 100644 --- a/tests/posix/sigaltstack.c +++ b/tests/posix/sigaltstack.c @@ -38,22 +38,27 @@ int main() { // This is used to trash the stack to ensure sigaltstack actually switched stacks. #if defined(__x86_64__) - asm volatile ("mov $0, %rsp\n" - "\t" "push $0"); + asm volatile("mov $0, %rsp\n" + "\t" + "push $0"); #elif defined(__i386__) - asm volatile ("mov $0, %esp\n" - "\t" "push $0"); + asm volatile("mov $0, %esp\n" + "\t" + "push $0"); #elif defined(__aarch64__) - asm volatile ("mov sp, %0\n" - "\t" "stp x0, x1, [sp, #-16]!" :: "r"((uint64_t)0)); + asm volatile("mov sp, %0\n" + "\t" + "stp x0, x1, [sp, #-16]!" ::"r"((uint64_t)0)); #elif defined(__riscv) && __riscv_xlen == 64 - asm volatile ("li sp, 0\n" - "\t" "sd zero, 0(sp)"); -#elif defined (__m68k__) - asm volatile ("move.l #0, %sp\n" - "\t" "move.l #0, -(%sp)"); + asm volatile("li sp, 0\n" + "\t" + "sd zero, 0(sp)"); +#elif defined(__m68k__) + asm volatile("move.l #0, %sp\n" + "\t" + "move.l #0, -(%sp)"); #else -# error Unknown architecture +#error Unknown architecture #endif return 0; diff --git a/tests/posix/sigsuspend.c b/tests/posix/sigsuspend.c index 09b9a1e83b..812b789aa7 100644 --- a/tests/posix/sigsuspend.c +++ b/tests/posix/sigsuspend.c @@ -1,8 +1,8 @@ #include -#include +#include #include #include -#include +#include _Atomic int handler_ready = 0; _Atomic int thread_signal_ran = 0; diff --git a/tests/posix/sigtimedwait.c b/tests/posix/sigtimedwait.c index 697f63c7c3..969854e404 100644 --- a/tests/posix/sigtimedwait.c +++ b/tests/posix/sigtimedwait.c @@ -1,10 +1,10 @@ #include #include +#include #include -#include #include -#include +#include pid_t parent; pid_t child; diff --git a/tests/posix/string.c b/tests/posix/string.c index 9c6e036b44..73b136ac75 100644 --- a/tests/posix/string.c +++ b/tests/posix/string.c @@ -1,5 +1,5 @@ -#include #include +#include int main() { char buf[4]; @@ -7,10 +7,10 @@ int main() { // stpncpy assert(stpncpy(buf, "", 4) == buf); assert(!strcmp(buf, "")); - + assert(stpncpy(buf, "123", 4) == buf + 3); assert(!strcmp(buf, "123")); - + assert(stpncpy(buf, "12", 4) == buf + 2); assert(buf[0] == '1' && buf[1] == '2' && buf[2] == '\0' && buf[3] == '\0'); @@ -20,10 +20,10 @@ int main() { // stpcpy assert(stpcpy(buf, "") == buf); assert(!strcmp(buf, "")); - + assert(stpcpy(buf, "12") == buf + 2); assert(!strcmp(buf, "12")); - + assert(stpcpy(buf, "123") == buf + 3); assert(!strcmp(buf, "123")); } diff --git a/tests/posix/time.c b/tests/posix/time.c index ae3516d73f..0b740ed7f6 100644 --- a/tests/posix/time.c +++ b/tests/posix/time.c @@ -33,7 +33,7 @@ int main() { assert(a != NULL); assert(*a == '\0'); assert(tm.tm_mday == 19); - assert(tm.tm_mon == 9); + assert(tm.tm_mon == 9); assert(tm.tm_year == 91); assert(tm.tm_wday == 6); assert(tm.tm_yday == 291); @@ -44,7 +44,7 @@ int main() { a = strptime("15:23", "%R", &tm); assert(a != NULL); assert(*a == '\0'); - assert(tm.tm_min == 23); + assert(tm.tm_min == 23); assert(tm.tm_hour == 15); assert(strftime(buf, BUF_SIZE, "%R", &tm) == 5); assert(!strcmp(buf, "15:23")); @@ -53,8 +53,8 @@ int main() { a = strptime("17:12:56", "%T", &tm); assert(a != NULL); assert(*a == '\0'); - assert(tm.tm_sec == 56); - assert(tm.tm_min == 12); + assert(tm.tm_sec == 56); + assert(tm.tm_min == 12); assert(tm.tm_hour == 17); assert(strftime(buf, BUF_SIZE, "%T", &tm) == 8); assert(!strcmp(buf, "17:12:56")); @@ -98,7 +98,7 @@ int main() { assert(a != NULL); assert(*a == '\0'); assert(tm.tm_mday == 23); - assert(tm.tm_mon == 8); + assert(tm.tm_mon == 8); assert(tm.tm_year == -217); assert(tm.tm_wday == 4); assert(tm.tm_yday == 265); @@ -109,7 +109,7 @@ int main() { a = strptime("14 53", "%H%t%S", &tm); assert(a != NULL); assert(*a == '\0'); - assert(tm.tm_sec == 53); + assert(tm.tm_sec == 53); assert(tm.tm_hour == 14); assert(strftime(buf, BUF_SIZE, "%H%t%S", &tm) == 5); assert(!strcmp(buf, "14 53")); @@ -128,7 +128,7 @@ int main() { assert(a != NULL); assert(*a == '\0'); assert(tm.tm_hour == 22); - assert(tm.tm_min == 21); + assert(tm.tm_min == 21); assert(strftime(buf, BUF_SIZE, "%I %M %p", &tm) == 8); assert(!strcmp(buf, "10 21 PM")); memset(&tm, 0, sizeof(tm)); diff --git a/tests/posix/timer.c b/tests/posix/timer.c index f39e92833b..b5ef2e1a1c 100644 --- a/tests/posix/timer.c +++ b/tests/posix/timer.c @@ -1,6 +1,6 @@ +#include #include #include -#include int main() { struct timeval a = {0, 0}; diff --git a/tests/posix/usershell.c b/tests/posix/usershell.c index 94c0b78984..f0f0d53aaf 100644 --- a/tests/posix/usershell.c +++ b/tests/posix/usershell.c @@ -1,7 +1,7 @@ -#include #include -#include #include +#include +#include static void testfor(const char *expected, char *shell, int *count) { if (strcmp(shell, expected) == 0) diff --git a/tests/posix/vfork.c b/tests/posix/vfork.c index 9ec09145f1..bbb2ddec11 100644 --- a/tests/posix/vfork.c +++ b/tests/posix/vfork.c @@ -5,9 +5,7 @@ #include #include -void prevent_atforks(void){ - exit(1); -} +void prevent_atforks(void) { exit(1); } int main() { pid_t pid; @@ -20,7 +18,8 @@ int main() { abort(); case 0: _exit(12); - default: break; + default: + break; } assert(wait(&status) == pid); diff --git a/tests/posix/waitid.c b/tests/posix/waitid.c index 9d53c4005b..60028a2d7c 100644 --- a/tests/posix/waitid.c +++ b/tests/posix/waitid.c @@ -9,7 +9,7 @@ siginfo_t si; int main() { int pid = fork(); - if(!pid) + if (!pid) exit(69); int ret = waitid(P_ALL, 0, &si, WEXITED); diff --git a/tests/posix/wcwidth.c b/tests/posix/wcwidth.c index 2e6fc8cd13..9e7df0bad9 100644 --- a/tests/posix/wcwidth.c +++ b/tests/posix/wcwidth.c @@ -1,8 +1,8 @@ #include #include #include -#include #include +#include #include #include @@ -33,7 +33,14 @@ void assertWidthIs(int expected_width, wchar_t c) { tests_run++; int actual_width = wcwidth(c); if (actual_width != expected_width) { - fprintf(stderr, "ERROR: wcwidth(U+%04" WCHAR_SPEC "x, '%lc') returned %d, expected %d\n", c, (wint_t) c, actual_width, expected_width); + fprintf( + stderr, + "ERROR: wcwidth(U+%04" WCHAR_SPEC "x, '%lc') returned %d, expected %d\n", + c, + (wint_t)c, + actual_width, + expected_width + ); test_failures++; } } @@ -61,7 +68,8 @@ int main() { assertWidthIs(2, 0x1F428); // Koala emoji. assertWidthIs(2, 0x231a); // Watch emoji. - if (test_failures > 0) printf("%d tests FAILED, ", test_failures); + if (test_failures > 0) + printf("%d tests FAILED, ", test_failures); printf("%d tests OK\n", tests_run - test_failures); return (test_failures == 0) ? 0 : 1; } diff --git a/tests/posix/wordexp.c b/tests/posix/wordexp.c index 063a37465e..bec3af0490 100644 --- a/tests/posix/wordexp.c +++ b/tests/posix/wordexp.c @@ -1,10 +1,10 @@ #include #include +#include #include #include #include #include -#include #include #include @@ -17,39 +17,39 @@ struct we_test { const char *wordv[16]; size_t wordc; } test_cases[] = { - /* (unbalanced) pairs */ - {WRDE_SYNTAX, "\\", 0, {NULL}, 0}, - {WRDE_SYNTAX, "\'", 0, {NULL}, 0}, - {0, "\'\'", 0, {""}, 1}, - {0, "\'\"\'", 0, {"\""}, 1}, - {WRDE_SYNTAX, "\"\'", 0, {NULL}, 0}, - - /* numbers & calculations */ - {0, "$((5+5))", 0, {"10"}, 1}, - {0, "$((-5+5))", 0, {"0"}, 1}, - {0, "$((010))", 0, {"8"}, 1}, - {0, "$((0x10))", 0, {"16"}, 1}, - - /* errant symbols */ - {WRDE_BADCHAR, "(string", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "string)", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "{string", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "string}", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "string|", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "string;", WRDE_NOCMD, {NULL}, 0}, - {WRDE_BADCHAR, "string&", WRDE_NOCMD, {NULL}, 0}, - - /* command substitution with WRDE_NOCMD */ - {WRDE_CMDSUB, "$(pwd)", WRDE_NOCMD, {NULL}, 0}, - - /* env vars */ - {WRDE_BADVAL, "$DOES_NOT_EXIST", WRDE_UNDEF, {NULL}, 0}, - - /* normal arguments */ - {0, "arg1 arg2", 0, {"arg1", "arg2"}, 2}, - {-1, NULL, 0, {NULL}, 0}, + /* (unbalanced) pairs */ + {WRDE_SYNTAX, "\\", 0, {NULL}, 0}, + {WRDE_SYNTAX, "\'", 0, {NULL}, 0}, + {0, "\'\'", 0, {""}, 1}, + {0, "\'\"\'", 0, {"\""}, 1}, + {WRDE_SYNTAX, "\"\'", 0, {NULL}, 0}, + + /* numbers & calculations */ + {0, "$((5+5))", 0, {"10"}, 1}, + {0, "$((-5+5))", 0, {"0"}, 1}, + {0, "$((010))", 0, {"8"}, 1}, + {0, "$((0x10))", 0, {"16"}, 1}, + + /* errant symbols */ + {WRDE_BADCHAR, "(string", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "string)", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "{string", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "string}", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "string|", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "string;", WRDE_NOCMD, {NULL}, 0}, + {WRDE_BADCHAR, "string&", WRDE_NOCMD, {NULL}, 0}, + + /* command substitution with WRDE_NOCMD */ + {WRDE_CMDSUB, "$(pwd)", WRDE_NOCMD, {NULL}, 0}, + + /* env vars */ + {WRDE_BADVAL, "$DOES_NOT_EXIST", WRDE_UNDEF, {NULL}, 0}, + + /* normal arguments */ + {0, "arg1 arg2", 0, {"arg1", "arg2"}, 2}, + {-1, NULL, 0, {NULL}, 0}, }; int main() { @@ -80,26 +80,39 @@ int main() { size_t i = 0; - for(struct we_test *test = &test_cases[i]; test->expected_return != -1; test = &test_cases[++i]) { + for (struct we_test *test = &test_cases[i]; test->expected_return != -1; + test = &test_cases[++i]) { wordexp_t test_we; int should_free; const char *expected = wordexp_return_stringify(test->expected_return, &should_free); - fprintf(stderr, "TESTCASE %zu: '%s' with flags %d expected to return %s\n", i, test->words, test->flags, expected); + fprintf( + stderr, + "TESTCASE %zu: '%s' with flags %d expected to return %s\n", + i, + test->words, + test->flags, + expected + ); int test_ret = wordexp(test->words, &test_we, test->flags); - if(test_ret != test->expected_return) { - fprintf(stderr, "\twordexp() returned %s, but we expect %s\n", wordexp_return_stringify(test_ret, &should_free), wordexp_return_stringify(test->expected_return, &should_free)); + if (test_ret != test->expected_return) { + fprintf( + stderr, + "\twordexp() returned %s, but we expect %s\n", + wordexp_return_stringify(test_ret, &should_free), + wordexp_return_stringify(test->expected_return, &should_free) + ); } assert(test_ret == test->expected_return); - if(test_ret != 0) + if (test_ret != 0) continue; assert(test_we.we_wordc == test->wordc); - for(size_t j = 0; j < 16 && j < test->wordc; j++) { + for (size_t j = 0; j < 16 && j < test->wordc; j++) { assert(test->wordv[j] && test_we.we_wordv[j]); assert(!strcmp(test->wordv[j], test_we.we_wordv[j])); } @@ -116,17 +129,17 @@ struct wordexp_return_val { int val; const char *string; } wordexp_return_vals[] = { - {0, "WRDE_SUCCESS"}, - {WRDE_BADCHAR, "WRDE_BADCHAR"}, - {WRDE_BADVAL, "WRDE_BADVAL"}, - {WRDE_CMDSUB, "WRDE_CMDSUB"}, - {WRDE_SYNTAX, "WRDE_SYNTAX"}, - {-1, NULL}, + {0, "WRDE_SUCCESS"}, + {WRDE_BADCHAR, "WRDE_BADCHAR"}, + {WRDE_BADVAL, "WRDE_BADVAL"}, + {WRDE_CMDSUB, "WRDE_CMDSUB"}, + {WRDE_SYNTAX, "WRDE_SYNTAX"}, + {-1, NULL}, }; static const char *wordexp_return_stringify(int val, int *should_free) { - for(size_t i = 0; wordexp_return_vals[i].val != -1 || wordexp_return_vals[i].string; i++) { - if(wordexp_return_vals[i].val == val) { + for (size_t i = 0; wordexp_return_vals[i].val != -1 || wordexp_return_vals[i].string; i++) { + if (wordexp_return_vals[i].val == val) { *should_free = 0; return wordexp_return_vals[i].string; } diff --git a/tests/rtld/destroy1/test.c b/tests/rtld/destroy1/test.c index 62da031cb1..529e136540 100644 --- a/tests/rtld/destroy1/test.c +++ b/tests/rtld/destroy1/test.c @@ -1,9 +1,5 @@ #include -__attribute__((destructor)) void destroy() { - _exit(0); -} +__attribute__((destructor)) void destroy() { _exit(0); } -int main() { - return 1; -} +int main() { return 1; } diff --git a/tests/rtld/destroy2/test.c b/tests/rtld/destroy2/test.c index 53e51781dc..32ff48409b 100644 --- a/tests/rtld/destroy2/test.c +++ b/tests/rtld/destroy2/test.c @@ -1,9 +1,9 @@ +#include #include #include -#include -#include #include #include +#include // Make sure files are flushed on process exit. @@ -40,4 +40,3 @@ int main() { return strcmp(buffer, message) != 0; } - diff --git a/tests/rtld/dl_iterate_phdr/test.c b/tests/rtld/dl_iterate_phdr/test.c index 5d48a41bb0..c3087de593 100644 --- a/tests/rtld/dl_iterate_phdr/test.c +++ b/tests/rtld/dl_iterate_phdr/test.c @@ -1,8 +1,8 @@ #include -#include -#include #include +#include #include +#include #ifdef USE_HOST_LIBC #define LDSO_PATTERN "ld-linux-" @@ -31,13 +31,11 @@ static int ends_with(const char *suffix, const char *s) { } } -static int contains(const char *pattern, const char *s) { - return !!strstr(s, pattern); -} +static int contains(const char *pattern, const char *s) { return !!strstr(s, pattern); } static int callback(struct dl_phdr_info *info, size_t size, void *data) { assert(size == sizeof(struct dl_phdr_info)); - struct result *found = (struct result *) data; + struct result *found = (struct result *)data; printf("%s\n", info->dlpi_name); fflush(stdout); @@ -57,7 +55,7 @@ static int callback(struct dl_phdr_info *info, size_t size, void *data) { } int main() { - struct result found = { 0 }; + struct result found = {0}; assert(!dl_iterate_phdr(callback, &found)); assert(found.found_ldso == 1); assert(found.found_self == 1); diff --git a/tests/rtld/dladdr_local/test.c b/tests/rtld/dladdr_local/test.c index 9952e0929b..fb0bbd46a0 100644 --- a/tests/rtld/dladdr_local/test.c +++ b/tests/rtld/dladdr_local/test.c @@ -1,5 +1,5 @@ -#include #include +#include #ifdef USE_HOST_LIBC #define LIBFOO "libnative-foo.so" @@ -10,13 +10,13 @@ int main() { void *foo_handle = dlopen(LIBFOO, RTLD_LOCAL | RTLD_NOW); assert(foo_handle); - + char *foo_global = (char *)dlsym(foo_handle, "foo_global"); assert(foo_global); - + Dl_info info; assert(dladdr((const void *)foo_global, &info) != 0); - + assert(dlclose(foo_handle) == 0); return 0; diff --git a/tests/rtld/ld_library_path/test.c b/tests/rtld/ld_library_path/test.c index 151eb36f21..a42749f3b5 100644 --- a/tests/rtld/ld_library_path/test.c +++ b/tests/rtld/ld_library_path/test.c @@ -1,6 +1,6 @@ +#include #include #include -#include #include #ifdef USE_HOST_LIBC diff --git a/tests/rtld/noload-promote/test.c b/tests/rtld/noload-promote/test.c index cc9820e133..2051736b39 100644 --- a/tests/rtld/noload-promote/test.c +++ b/tests/rtld/noload-promote/test.c @@ -1,5 +1,5 @@ -#include #include +#include #include #ifdef USE_HOST_LIBC diff --git a/tests/rtld/preinit/libfoo.c b/tests/rtld/preinit/libfoo.c index 9c834eafff..c92e49bfa7 100644 --- a/tests/rtld/preinit/libfoo.c +++ b/tests/rtld/preinit/libfoo.c @@ -1,18 +1,15 @@ -#include #include +#include int fooDone = 0; // DSOs do not support pre-initialization functions. -__attribute__((constructor)) -void fooInit() { +__attribute__((constructor)) void fooInit() { dprintf(1, "initialization function called in foo\n"); assert(fooDone == 0); fooDone++; } -int isFooDone() { - return fooDone; -} +int isFooDone() { return fooDone; } diff --git a/tests/rtld/preinit/test.c b/tests/rtld/preinit/test.c index de2fc516a9..9bd4520a76 100644 --- a/tests/rtld/preinit/test.c +++ b/tests/rtld/preinit/test.c @@ -1,5 +1,5 @@ -#include #include +#include int mainDone = 0; @@ -22,8 +22,7 @@ void preInit2() { mainDone++; } -__attribute__((constructor)) -void mainInit() { +__attribute__((constructor)) void mainInit() { dprintf(1, "initialization function called in main executable\n"); assert(isFooDone() == 1); @@ -32,10 +31,9 @@ void mainInit() { } // Manually register the pre-initialization functions. -__attribute__((used, section(".preinit_array"))) -static void (*preinitFunctions[])(void) = { - &preInit1, - &preInit2, +__attribute__((used, section(".preinit_array"))) static void (*preinitFunctions[])(void) = { + &preInit1, + &preInit2, }; int main() { diff --git a/tests/rtld/relr/test.c b/tests/rtld/relr/test.c index b7a05361ad..a3cfbf7d30 100644 --- a/tests/rtld/relr/test.c +++ b/tests/rtld/relr/test.c @@ -1,22 +1,15 @@ -#include #include +#include -const char* strings[] = { - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", - "", "", "", "", "", "", "", "", +const char *strings[] = { + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", }; int main() { - for(size_t i = 0; i < sizeof(strings) / sizeof(*strings); ++i) { + for (size_t i = 0; i < sizeof(strings) / sizeof(*strings); ++i) { assert(strings[i][0] == 0); } diff --git a/tests/rtld/rtld_next/libbar.c b/tests/rtld/rtld_next/libbar.c index c0950c5879..eb80f1cd68 100644 --- a/tests/rtld/rtld_next/libbar.c +++ b/tests/rtld/rtld_next/libbar.c @@ -2,15 +2,8 @@ typedef char *charFn(void); -__attribute__((weak)) -char *definedInBoth() { - return "bar"; -} +__attribute__((weak)) char *definedInBoth() { return "bar"; } -charFn *barGetDefault() { - return (charFn *)dlsym(RTLD_DEFAULT, "definedInBoth"); -} +charFn *barGetDefault() { return (charFn *)dlsym(RTLD_DEFAULT, "definedInBoth"); } -charFn *barGetNext() { - return (charFn *)dlsym(RTLD_NEXT, "definedInBoth"); -} +charFn *barGetNext() { return (charFn *)dlsym(RTLD_NEXT, "definedInBoth"); } diff --git a/tests/rtld/rtld_next/libfoo.c b/tests/rtld/rtld_next/libfoo.c index 1d46b735f1..108b505397 100644 --- a/tests/rtld/rtld_next/libfoo.c +++ b/tests/rtld/rtld_next/libfoo.c @@ -2,16 +2,8 @@ typedef char *charFn(void); -__attribute__((weak)) -char *definedInBoth() { - return "foo"; -} +__attribute__((weak)) char *definedInBoth() { return "foo"; } -charFn *fooGetDefault() { - return (charFn *)dlsym(RTLD_DEFAULT, "definedInBoth"); -} - -charFn *fooGetNext() { - return (charFn *)dlsym(RTLD_NEXT, "definedInBoth"); -} +charFn *fooGetDefault() { return (charFn *)dlsym(RTLD_DEFAULT, "definedInBoth"); } +charFn *fooGetNext() { return (charFn *)dlsym(RTLD_NEXT, "definedInBoth"); } diff --git a/tests/rtld/rtld_next/test.c b/tests/rtld/rtld_next/test.c index 061f48ec87..02a3395f25 100644 --- a/tests/rtld/rtld_next/test.c +++ b/tests/rtld/rtld_next/test.c @@ -1,5 +1,5 @@ -#include #include +#include typedef char *charFn(void); charFn *fooGetDefault(void); diff --git a/tests/rtld/scope1/libbar.c b/tests/rtld/scope1/libbar.c index bcf336dc71..eb2d19f002 100644 --- a/tests/rtld/scope1/libbar.c +++ b/tests/rtld/scope1/libbar.c @@ -1,14 +1,8 @@ char *foo(void); char *foo_global(void); -char *bar(void) { - return "bar"; -} +char *bar(void) { return "bar"; } -char *bar_calls_foo(void) { - return foo(); -} +char *bar_calls_foo(void) { return foo(); } -char *bar_calls_foo_global(void) { - return foo_global(); -} +char *bar_calls_foo_global(void) { return foo_global(); } diff --git a/tests/rtld/scope1/libfoo.c b/tests/rtld/scope1/libfoo.c index 112342c5c7..9ece1c8ddf 100644 --- a/tests/rtld/scope1/libfoo.c +++ b/tests/rtld/scope1/libfoo.c @@ -1,9 +1,5 @@ -char *foo(void) { - return "foo"; -} +char *foo(void) { return "foo"; } char global[] = "foo global"; -char *foo_global(void) { - return global; -} +char *foo_global(void) { return global; } diff --git a/tests/rtld/scope1/test.c b/tests/rtld/scope1/test.c index 316d90bba2..f8f57ac77d 100644 --- a/tests/rtld/scope1/test.c +++ b/tests/rtld/scope1/test.c @@ -1,8 +1,8 @@ -#include -#include #include -#include +#include +#include #include +#include #ifdef USE_HOST_LIBC #define LIBFOO "libnative-foo.so" @@ -54,17 +54,17 @@ int main() { void *bar_handle = dlopen(LIBBAR, RTLD_GLOBAL | RTLD_NOW); assert(bar_handle); assert(dlopen(LIBBAR, RTLD_NOLOAD | RTLD_NOW)); - + strfn *bar_sym = dlsym(bar_handle, "bar"); assert(bar_sym); assert(bar_sym()); assert(!strcmp(bar_sym(), "bar")); - + strfn *bar_calls_foo_sym = dlsym(bar_handle, "bar_calls_foo"); assert(bar_calls_foo_sym); assert(bar_calls_foo_sym()); assert(!strcmp(bar_calls_foo_sym(), "foo")); - + strfn *bar_calls_foo_global_sym = dlsym(bar_handle, "bar_calls_foo_global"); assert(bar_calls_foo_global_sym); assert(bar_calls_foo_global_sym()); diff --git a/tests/rtld/scope2/libbar.c b/tests/rtld/scope2/libbar.c index 5ae0b85145..d49dc9ceb2 100644 --- a/tests/rtld/scope2/libbar.c +++ b/tests/rtld/scope2/libbar.c @@ -1,5 +1,3 @@ char *foo_baz_conflict(void); -char *bar_calls_foo_baz_conflict(void) { - return foo_baz_conflict(); -} +char *bar_calls_foo_baz_conflict(void) { return foo_baz_conflict(); } diff --git a/tests/rtld/scope2/libbaz.c b/tests/rtld/scope2/libbaz.c index fc73adcdc2..af2316852b 100644 --- a/tests/rtld/scope2/libbaz.c +++ b/tests/rtld/scope2/libbaz.c @@ -1,3 +1 @@ -char *foo_baz_conflict() { - return "resolved to baz"; -} +char *foo_baz_conflict() { return "resolved to baz"; } diff --git a/tests/rtld/scope2/libfoo.c b/tests/rtld/scope2/libfoo.c index 9f7b881f69..00775c0bcb 100644 --- a/tests/rtld/scope2/libfoo.c +++ b/tests/rtld/scope2/libfoo.c @@ -1,3 +1 @@ -char *foo_baz_conflict() { - return "resolved to foo"; -} +char *foo_baz_conflict() { return "resolved to foo"; } diff --git a/tests/rtld/scope2/test.c b/tests/rtld/scope2/test.c index d4763aeea7..781d9b6efd 100644 --- a/tests/rtld/scope2/test.c +++ b/tests/rtld/scope2/test.c @@ -1,8 +1,8 @@ -#include -#include #include -#include +#include +#include #include +#include #ifdef USE_HOST_LIBC #define LIBBAR "libnative-bar.so" diff --git a/tests/rtld/scope3/libbar.c b/tests/rtld/scope3/libbar.c index 28b5b86e7a..d57c49d3a7 100644 --- a/tests/rtld/scope3/libbar.c +++ b/tests/rtld/scope3/libbar.c @@ -2,7 +2,4 @@ int g = 1; int call_foo(void); -int call_bar(void) { - return call_foo(); -} - +int call_bar(void) { return call_foo(); } diff --git a/tests/rtld/scope3/libbaz.c b/tests/rtld/scope3/libbaz.c index d4be90ab3d..e88a0800ea 100644 --- a/tests/rtld/scope3/libbaz.c +++ b/tests/rtld/scope3/libbaz.c @@ -2,6 +2,4 @@ int g = 2; int call_foo(void); -int call_baz(void) { - return call_foo(); -} +int call_baz(void) { return call_foo(); } diff --git a/tests/rtld/scope3/libfoo.c b/tests/rtld/scope3/libfoo.c index 0ec8071cc1..779cbcaa52 100644 --- a/tests/rtld/scope3/libfoo.c +++ b/tests/rtld/scope3/libfoo.c @@ -1,5 +1,3 @@ int g = 0; -int call_foo(void) { - return g; -} +int call_foo(void) { return g; } diff --git a/tests/rtld/scope3/test.c b/tests/rtld/scope3/test.c index 27196ad92d..0514e19909 100644 --- a/tests/rtld/scope3/test.c +++ b/tests/rtld/scope3/test.c @@ -1,6 +1,6 @@ +#include #include #include -#include #ifdef USE_HOST_LIBC #define LIBBAR "libnative-bar.so" @@ -33,7 +33,6 @@ int main() { printf("call_baz: %d\n", call_baz()); assert(call_baz() == 1); - dlclose(libbar); dlclose(libbaz); diff --git a/tests/rtld/scope4/test.c b/tests/rtld/scope4/test.c index 57af05dce1..1e8f6bae3e 100644 --- a/tests/rtld/scope4/test.c +++ b/tests/rtld/scope4/test.c @@ -1,6 +1,6 @@ +#include #include #include -#include #ifdef USE_HOST_LIBC #define LIBFOO "libnative-foo.so" diff --git a/tests/rtld/scope5/test.c b/tests/rtld/scope5/test.c index d2afe09049..e6c7b716cc 100644 --- a/tests/rtld/scope5/test.c +++ b/tests/rtld/scope5/test.c @@ -1,6 +1,6 @@ +#include #include #include -#include #ifdef USE_HOST_LIBC #define LIBFOO "libnative-foo.so" diff --git a/tests/rtld/soname/test.c b/tests/rtld/soname/test.c index 1aba357167..a61aa4959a 100644 --- a/tests/rtld/soname/test.c +++ b/tests/rtld/soname/test.c @@ -1,6 +1,6 @@ +#include #include #include -#include #include #ifdef USE_HOST_LIBC