74 Commits

Author SHA1 Message Date
vasilito d6b223dc28 libredox: revert O_CLOEXEC to literal in protocol module (fixes standalone build)
Commit 65889db changed protocol::O_CLOEXEC to reference syscall::flag::O_CLOEXEC,
but the `protocol` module is built standalone by relibc
(default-features=false, features=["protocol"]), where the optional
redox_syscall/base/libc crates are NOT linked. That produced E0433
'unresolved module or unlinked crate syscall' and failed the relibc/prefix
build. Every other syscall:: use in libredox is #[cfg(feature="redox_syscall")]
-gated; this const was not. 0x0100_0000 is exactly syscall's O_CLOEXEC value, so
the literal is correct (the single-source-of-truth concern is cosmetic here).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 23:08:58 +09:00
vasilito 65889dbd92 libredox: reference syscall::flag::O_CLOEXEC instead of duplicating
O_CLOEXEC was defined in both libredox (0x0100_0000) and syscall
(0x0100_0000). Per the Single Source of Truth principle (and the
Local Fork Supremacy Policy: 'never version-string-duplicate a
Cat 2 fork crate'), a primitive constant should be defined once
in the most-primitive crate that has it (syscall) and re-exported
by higher-level crates (libredox).

Change: libredox::flag::O_CLOEXEC is now
'syscall::flag::O_CLOEXEC' instead of a literal 0x0100_0000. The
F_DUPFD_CLOEXEC constant stays as a literal since syscall does not
define it (it's a Linux-specific fcntl flag that Redox may not need).
2026-07-27 18:17:28 +09:00
vasilito 5bb745ec6f libredox: Fd::ftruncate and Fd::futimens take &self, not self
POSIX ftruncate(2) and futimens(2) do not close the file descriptor.
The previous 'self' (by-value) signature consumed the Fd on call, which
would trigger Fd::drop and close the fd as a side effect. After a
successful ftruncate the user could no longer use the fd, which is
the opposite of the intended semantics.

Change to '&self' to match the surrounding methods (fsync, fdatasync
both already use &self) and to match POSIX behaviour. The drop-on-
failure semantics is preserved by Rust's normal borrow checker: if
ftruncate returns Err, the caller's borrow is still valid and the
fd stays open.
2026-07-27 17:05:08 +09:00
vasilito bfb5f8b2ca libredox: replace demux() .expect() with .unwrap_or(u16::MAX)
CRITICAL F3.1 from NETWORKING-AND-DRIVERS-CODE-ASSESSMENT-2026-07-27.md
§3.4: demux() panicked on edge-case errno via '.expect("2^BITS - res < 4096")'.
Called from every syscall wrapper (~40 call sites). A kernel returning
errno outside the 0..=4095 range would panic the entire process.

Fix: saturate to u16::MAX on overflow rather than panic. The errno
field is u16; values above u16::MAX indicate a kernel ABI violation,
and surfacing u16::MAX is safer than crashing every caller.

Trivial change (one line: .expect -> .unwrap_or(u16::MAX)) with a
comment explaining the saturate-vs-panic tradeoff.
2026-07-27 16:09:41 +09:00
vasilito d787867f8c libredox: add minimal # Safety comments to lib.rs
Adds 45 minimal SAFETY: comments above unsafe blocks in lib.rs:
- demux(): caller guarantees errno fits in u16 (handled with unwrap_or)
- Fd::Drop munmap: caller guarantees fd is still valid at drop time
- SocketCall enum: caller validates discriminator
- from_raw_fd: caller guarantees fd is valid, open, not aliased
- copy_nonoverlapping: caller guarantees non-overlapping regions
- generic catch-all: caller must verify the safety contract

Part of the systematic fix for ZERO # Safety docs across libredox
(NETWORKING-AND-DRIVERS-CODE-ASSESSMENT-2026-07-27.md §3.4,
Finding 9.2).
2026-07-27 15:07:59 +09:00
vasilito b99b204c96 libredox: remove cargo metadata + tighten .gitignore
The .cargo-ok and .cargo_vcs_info.json files were cargo-published
metadata that got committed to the fork. Upstream libredox 0.1.18
does not have these files in source control — they're cargo workspace
artifacts that should be in .gitignore.

This commit:
- Removes .cargo-ok and .cargo_vcs_info.json from tracking
- Adds /Cargo.lock to .gitignore (matches upstream)
- Brings fork structure back in line with upstream conventions

Fixes verify-fork-versions.sh content-check for libredox 0.1.18.
2026-07-12 02:12:57 +03:00
vasilito 6908adc9a4 libredox: apply Red Bear patches on latest upstream
- Use local path dep for redox_syscall
- Protocol constants and fixes
- Version suffix +rb0.3.1
- Author attribution
2026-07-11 11:34:24 +03:00
Jeremy Soller bedf0129b9 Merge branch 'fcntl' into 'master'
feat: Add fcntl

See merge request redox-os/libredox!27
2026-07-01 08:01:38 -06:00
Ibuki Omatsu 0899f212c0 feat: Add fcntl 2026-07-01 08:01:37 -06:00
Jacob Lorentzon 7040cf71b3 Merge branch 'relpathat' into 'master'
feat: Add relpathat

See merge request redox-os/libredox!26
2026-05-27 16:02:55 +02:00
Ibuki Omatsu 5cc70f148f feat: Add relpathat 2026-05-27 16:02:55 +02:00
Jeremy Soller f14358d4d8 Merge branch 'prio-sched-version' into 'master'
Bump version

See merge request redox-os/libredox!25
2026-04-09 15:21:52 -06:00
Akshit Gaur 65aa9e1272 Bump version 2026-04-06 14:46:33 +05:30
Jeremy Soller eb3b30ed33 Merge branch 'priority-sched' into 'master'
{Get/Set}ProcPriority

See merge request redox-os/libredox!24
2026-04-04 07:40:47 -06:00
Jeremy Soller c2f1a4f763 Merge branch 'MSG_FLAGS' into 'master'
Add MSG flags for sockets

See merge request redox-os/libredox!22
2026-03-24 11:02:02 -06:00
Akshit Gaur 33192ebab7 {Get/Set}ProcPriority 2026-03-23 22:50:21 +05:30
Benton60 477f6e6ae9 bump version 2026-03-22 12:13:02 -04:00
Benton60 c7b39521e4 add MSG flags for sockets 2026-03-22 12:13:02 -04:00
Jeremy Soller 0076e6e034 Merge branch 'priority-sched' into 'master'
Add Set and Get Priority

See merge request redox-os/libredox!23
2026-03-22 06:59:27 -06:00
Akshit Gaur 1b859147f5 Add Set and Get Priority 2026-03-22 17:51:09 +05:30
Jeremy Soller 094dc72d36 Merge branch 'base-libc' into 'master'
fix: Fix feature dependencies

See merge request redox-os/libredox!21
2026-02-28 07:10:06 -07:00
Ibuki Omatsu 35d51ab014 fix: Fix feature dependencies 2026-02-28 07:10:05 -07:00
Jeremy Soller 653c5b41b9 Merge branch 'protocol' into 'master'
feat: Move redox-rt::protocol into libredox::protocol. Add getdents and futimens.

See merge request redox-os/libredox!20
2026-02-27 08:37:26 -07:00
Ibuki Omatsu 17f21113a0 feat: Move redox-rt::protocol into libredox::protocol. Add getdents and futimens. 2026-02-27 08:37:26 -07:00
Jeremy Soller 6a75c953a6 Merge branch 'nsmgr' into 'master'
Add Fd::new, setns, getns, and register_scheme_to_ns.

See merge request redox-os/libredox!18
2025-12-27 07:47:25 -07:00
Ibuki Omatsu 6c5a628461 Add Fd::new, setns, getns, and register_scheme_to_ns. 2025-12-27 07:47:25 -07:00
Jeremy Soller cfbb2c3d39 Merge branch 'update-syscall' into 'master'
chore: Bump version and update redox_syscall.

See merge request redox-os/libredox!19
2025-12-16 07:43:30 -07:00
Ibuki Omatsu 9db478544d chore: Bump version and update redox_syscall. 2025-12-16 07:43:30 -07:00
Jeremy Soller 616d2e81f7 Merge branch 'getens' into 'master'
Add getens.

See merge request redox-os/libredox!15
2025-09-09 07:36:12 -06:00
Ibuki Omatsu fd13f1b8dd Add getens. 2025-09-09 07:36:12 -06:00
Jeremy Soller 33c6543c67 Merge branch 'waitpid-flags' into 'master'
Add waitpid flags

See merge request redox-os/libredox!14
2025-08-11 14:12:30 -06:00
Wildan M b4c4fb9fd1 Add waitpid flags 2025-08-09 07:31:24 +07:00
Jeremy Soller f0b019173e Merge branch 'master' into 'master'
Bump version to 0.1.9

See merge request redox-os/libredox!12
2025-07-30 19:48:52 -06:00
Ibuki Omatsu dc9aee240a Bump version to 0.1.9 2025-07-30 19:48:52 -06:00
Jeremy Soller 53fd2f4530 Merge branch 'call_redox_syscall_feature' into 'master'
fix: Add cfg attribute for the redox_syscall feature to all call functions.

See merge request redox-os/libredox!11
2025-07-30 15:34:25 -06:00
Ibuki Omatsu 86444c59a2 fix: Add cfg attribute for the redox_syscall feature to all call functions. 2025-07-30 15:34:25 -06:00
Jeremy Soller c6c2ae6ce6 Merge branch 'call' into 'master'
feat: Add call_ro, call_wo and call_wr to call module.

See merge request redox-os/libredox!10
2025-07-28 09:33:13 -06:00
Ibuki Omatsu c8ad74b402 feat: Add call_ro, call_wo and call_wr to call module. 2025-07-28 09:33:13 -06:00
Jacob Lorentzon c2e45479c9 Merge branch 'fd-call' into 'master'
feat: Add call as a new method of Fd.

See merge request redox-os/libredox!9
2025-07-26 16:21:23 +02:00
Ibuki Omatsu 144500e2c9 feat: Add call as a new method of Fd. 2025-07-26 16:21:22 +02:00
Jeremy Soller 2cacc86d93 Merge branch 'redox_get_socket_token' into 'master'
refactor: Use redox_get_socket_token from relibc

See merge request redox-os/libredox!8
2025-07-19 07:36:33 -06:00
Ibuki Omatsu c21fcb6847 refactor: Use redox_get_socket_token from relibc 2025-07-19 07:36:33 -06:00
Jeremy Soller 927f8f0578 Merge branch 'get_proc_creds_cap' into 'master'
feat: Change get_proc_credentials to use capability fd and add get_socket_token.

See merge request redox-os/libredox!6
2025-07-18 18:27:36 -06:00
Ibuki Omatsu 690884e0a6 feat: Change get_proc_credentials to use capability fd and add get_socket_token. 2025-07-18 18:27:36 -06:00
Jeremy Soller 69d53bef29 Merge branch 'openat-update' into 'master'
Add fcntl_flags to openat

See merge request redox-os/libredox!7
2025-07-07 15:18:41 -06:00
Darley Barreto 6e05857046 Add fcntl_flags to openat 2025-07-05 12:55:13 -03:00
Jeremy Soller 540f302456 Merge branch 'redox_get_proc_credentials' into 'master'
feat: Add get_proc_credentials functions.

See merge request redox-os/libredox!3
2025-06-25 08:48:33 -06:00
Ibuki Omatsu 7bb0cff932 feat: Add get_proc_credentials functions. 2025-06-25 08:48:33 -06:00
Jacob Lorentzon 4273b8ac67 Merge branch 'openat' into 'master'
Add openat

See merge request redox-os/libredox!1
2025-04-05 18:00:33 +00:00
Darley Barreto 2a04c02f36 Add openat 2025-04-05 12:35:10 -03:00
4lDO2 70bf561aef 0.1.3 2024-03-18 17:08:27 +01:00
4lDO2 fa1739a954 Add mkns API. 2024-03-18 17:08:14 +01:00
4lDO2 0cd9eec99e Libredox 0.1.2 2024-03-12 17:04:55 +01:00
4lDO2 8596a93069 Bump redox_syscall optional dependency. 2024-03-12 17:04:41 +01:00
4lDO2 23b4a07f1a Libredox 0.1.1 2024-02-23 10:36:02 +01:00
4lDO2 0ef1244bd7 Impl From<libredox Error> for syscall Error. 2024-02-23 10:34:48 +01:00
4lDO2 9faaf9d156 Libredox 0.1.0 2024-01-14 20:56:26 +01:00
4lDO2 7341724f55 Make the redox_syscall dependency optional. 2024-01-11 15:03:09 +01:00
4lDO2 9872ee3ef5 Bump crate version. 2023-12-26 12:21:28 +01:00
4lDO2 4de57e2c98 Allow disabling redox_syscall public APIs. 2023-12-26 12:20:13 +01:00
4lDO2 dcb73fea4b Move scheme API to redox-scheme. 2023-12-26 11:21:01 +01:00
4lDO2 8009c0457a Libredox 0.0.3 2023-11-05 13:04:36 +01:00
4lDO2 8201e827c8 Add fstat, fstatvfs, and futimens. 2023-11-05 13:03:57 +01:00
4lDO2 5376b5aaae Libredox 0.0.2 2023-11-04 16:48:53 +01:00
4lDO2 4b4b0432dd Only use the call feature by default. 2023-11-04 16:47:23 +01:00
4lDO2 3a0e50ef3f Implement mmap and munmap 2023-11-04 16:42:12 +01:00
4lDO2 eea551978d Add LICENSE. 2023-10-12 20:17:57 +02:00
4lDO2 cc96253e78 Add exclude = ["target"] 2023-10-12 20:16:44 +02:00
4lDO2 721a564726 Update Cargo.toml metadata. 2023-10-12 20:15:12 +02:00
4lDO2 a15ce02753 Compile on non-Redox platforms. 2023-10-12 20:13:05 +02:00
4lDO2 619de8a521 Add more ABI functions and some scheme APIs. 2023-10-12 20:08:07 +02:00
4lDO2 eaf682b6b4 Ensure ABI uses unsigned arguments
This is important because compilers may not correctly sign-extend args
otherwise, if e.g. flags are extended.
2023-10-02 17:08:07 +02:00
4lDO2 9904ebe0c1 Add clock_gettime. 2023-10-02 17:06:25 +02:00
4lDO2 7016837f1f Initial Commit 2023-09-28 16:32:39 +02:00
1132 changed files with 1262 additions and 102484 deletions
-7
View File
@@ -1,7 +0,0 @@
[**.c]
indent_size = 4
indent_style = space
[**.yml]
indent_size = 4
indent_style = space
+2 -11
View File
@@ -1,11 +1,2 @@
.idea/ /target
prefix/ /Cargo.lock
sysroot/
**/target/
.gdb_history
*.patch
*.swp
*.swo
/.vim
.vscode/
-87
View File
@@ -1,87 +0,0 @@
image: "redoxos/redoxer:latest"
variables:
GIT_SUBMODULE_STRATEGY: recursive
workflow:
rules:
- if: '$CI_COMMIT_BRANCH == "master" && $CI_PROJECT_NAMESPACE == "redox-os"'
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'
stages:
- build
- cross-build
- test
before_script:
cargo install cbindgen
fmt:
stage: build
needs: []
script:
- rustup component add rustfmt-preview
- ./fmt.sh -- --check
clippy:
stage: build
needs: []
# TODO: remove when passed
allow_failure: true
script:
- ./check.sh --clippy
linux:
stage: build
script:
- rustup component add clippy
- ./check.sh --host
# - ./check.sh --host --clippy
x86_64:
stage: build
script:
- ./check.sh --arch=x86_64
i586:
stage: cross-build
script:
- ./check.sh --arch=i586
# - ./check.sh --arch=i586 --clippy
aarch64:
stage: cross-build
image: "redoxos/redoxer:aarch64"
script:
- ./check.sh --arch=aarch64
# - ./check.sh --arch=aarch64 --clippy
riscv64gc:
stage: cross-build
script:
- ./check.sh --arch=riscv64gc
# - ./check.sh --arch=riscv64gc --clippy
test:linux:
stage: test
needs: [linux]
script:
- ./check.sh --host --test
test:x86_64:
stage: test
needs: [x86_64]
script:
# timeout: https://gitlab.redox-os.org/redox-os/relibc/-/issues/238
- timeout -s KILL 9m ./check.sh --arch=x86_64 --test
test:aarch64:
stage: test
needs: [aarch64]
image: "redoxos/redoxer:aarch64"
# many issues that not exist in x86_64, and lack of interest to fix so far
allow_failure: true
when: manual
script:
- timeout -s KILL 9m ./check.sh --arch=aarch64 --test
#TODO: Enable more arch once dynamic linker working
-7
View File
@@ -1,7 +0,0 @@
[submodule "openlibm"]
path = openlibm
url = https://gitlab.redox-os.org/redox-os/openlibm.git
branch = master
[submodule "src/dlmalloc-rs"]
path = dlmalloc-rs
url = https://gitlab.redox-os.org/redox-os/dlmalloc-rs.git
-123
View File
@@ -1,123 +0,0 @@
# Contributing
## Table of contents
1. [What to do](#what-to-do)
2. [Code style](#code-style)
3. [Sending merge requests](#sending-merge-requests)
4. [Writing tests](#writing-tests)
5. [Running tests](#running-tests)
Maintaining a libc is tough work, and we'd love some help!
## What to do
For now, we are still trying to get full libc compatibility before we move on to
any optimisation.
- We currently have a number of unimplemented functions. Search for
`unimplemented!()` and hop right in!
- If you notice any missing functionality, feel free to add it in
## Code style
We have a `rustfmt.toml` in the root directory of relibc. Please run `./fmt.sh`
before sending in any merge requests as it will automatically format your code.
With regards to general style:
### Where applicable, prefer using references to raw pointers
This is most obvious when looking at `stdio` functions. If raw pointers were
used instead of references, then the resulting code would be significantly
uglier. Instead try to check for pointer being valid with `pointer::as_ref()`
and `pointer::as_mut()` and then immediately use those references instead.
Internal functions should always take references.
### Use the c types exposed in our platform module instead of Rust's inbuilt integer types
This is so we can guarantee that everything works across platforms. While it is
generally accepted these days that an `int` has 32 bits (which matches against
an `i32`), some platforms have `int` as having 16 bits, and others have long as
being 32 bits instead of 64. If you use the types in platform, then we can
guarantee that your code will "just work" should we port relibc to a different
architecture.
### Use our internal functions
If you need to use a C string, don't reinvent the wheel. We have functions in
the platform module that convert C strings to Rust slices.
We also have structures that wrap files, wrap writable strings, and wrap various
other commonly used things that you should use instead of rolling your own.
## Sending merge requests
If you have sent us a merge request, first of all, thanks for taking your time
to help us!
The first thing to note is that we do most of our development on our
[GitLab server](https://gitlab.redox-os.org/redox-os/relibc), and as such it is
possible that none of the maintainers will see your merge request if it is
opened on GitHub.
In your merge request, please put in the description:
- What functions (if any) have been implemented or changed
- The rationale behind your merge request (e.g. why you thought this change was
required. If you are just implementing some functions, you can ignore this)
- Any issues that are related to the merge request
We have CI attached to our GitLab instance, so all merge requests are checked to
make sure that they are tested before they are merged. Please write tests for
the functions that you add/change and test locally on your own machine
***before*** submitting a merge request.
## Writing tests
Every function that gets written needs to have a test in C in order to make sure
it works as intended. Here are a few guidelines for writing good tests.
### Ensure that any literals you have are mapped to variables instead of being directly passed to a function.
Sometimes compilers take literals put into libc functions and run them
internally during compilation, which can cause some false positives. All tests
are compiled with `-fno-builtin`, which theoretically solves this issue, but
just in case, it'd be a good idea to map inputs to variables.
```c
#include "string.h"
#include "stdio.h"
int main(void) {
// Don't do this
printf("%d\n", strcspn("Hello", "Hi"));
// Do this
char *first = "Hello";
char *second = "Hi";
printf("%d\n", strcspn(first, second));
}
```
### Ensure your tests cover every section of code.
What happens if a string in `strcmp()` is shorter than the other string? What
happens if the first argument to `strcspn()` is longer than the second string?
In order to make sure that all functions work as expected, we ask that any tests
cover as much of the code that you have written as possible.
## Running tests
Running tests is an important part in trying to find bugs. Before opening a
merge request, we ask that you test on your own machine to make sure there are
no regressions.
You can run tests with `make test` in the root directory of relibc to compile
relibc, compile the tests and run them. This *will* print a lot of output to
stdout, so be warned!
You can test against verified correct output with `make verify` in the tests
directory. You will need to manually create the correct output and put it in the
tests/expected directory. Running any `make` commands in the tests directory
will ***not*** rebuild relibc, so you'll need to go back to the root directory
if you need to rebuild relibc.
Generated
-732
View File
@@ -1,732 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "argon2"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"password-hash",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bcrypt-pbkdf"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6aeac2e1fe888769f34f05ac343bbef98b14d1ffb292ab69d4608b3abc86f2a2"
dependencies = [
"blowfish",
"pbkdf2",
"sha2",
]
[[package]]
name = "bitflags"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "blowfish"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"
dependencies = [
"byteorder",
"cipher",
]
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cbitset"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29b6ad25ae296159fb0da12b970b2fe179b234584d7cd294c891e2bbb284466b"
dependencies = [
"num-traits",
]
[[package]]
name = "cc"
version = "1.1.22"
source = "git+https://github.com/tea/cc-rs?branch=riscv-abi-arch-fix#588ceacb084af41415690c57688e338a32a1f1b4"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"num-traits",
]
[[package]]
name = "chrono-tz"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
dependencies = [
"chrono",
"phf",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crt0"
version = "0.1.0"
[[package]]
name = "crti"
version = "0.1.0"
[[package]]
name = "crtn"
version = "0.1.0"
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
name = "dlmalloc"
version = "0.2.8"
dependencies = [
"cfg-if",
"windows-sys",
]
[[package]]
name = "drm-sys"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8"
dependencies = [
"libc",
"linux-raw-sys",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "generic-rt"
version = "0.1.0"
[[package]]
name = "goblin"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17582616a7718cca54cec18e534a76c7c4aec11a8b9a85695712f262fd15a4c8"
dependencies = [
"log",
"plain",
"scroll",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "ioslice"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e571352c8a3b89074d12e3ee5173ffe162159105352aaaf1fc5764da747e31b"
[[package]]
name = "ld_so"
version = "0.1.0"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "libredox"
version = "0.1.18+rb0.3.1"
dependencies = [
"bitflags",
"libc",
"plain",
]
[[package]]
name = "linux-raw-sys"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "object"
version = "0.36.7"
source = "git+https://gitlab.redox-os.org/andypython/object?branch=new#da781336d847df0deb897ed1162785f6c2057c56"
dependencies = [
"memchr",
]
[[package]]
name = "password-hash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core 0.6.4",
"subtle",
]
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest",
"hmac",
"sha2",
]
[[package]]
name = "phf"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
dependencies = [
"phf_shared",
]
[[package]]
name = "phf_shared"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
dependencies = [
"siphasher",
]
[[package]]
name = "plain"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "posix-regex"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66df580334caab2f744839ab1be85493d7ec731a92d6cf928008ab0b212bf3bc"
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_jitter"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdcd80e68f0a8f9ca5ec7cfd02fd5fbb8fbe6ef4e9b90ea2f48bb929b74f88e"
dependencies = [
"libc",
"rand_core 0.10.1",
"windows-sys",
]
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "redox-ioctl"
version = "0.1.0"
dependencies = [
"drm-sys",
"redox_syscall",
]
[[package]]
name = "redox-path"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54ec1b67c01c63545205ea6d218b336751399f0d8974c1a635c28604bedb81bc"
[[package]]
name = "redox-rt"
version = "0.1.0"
dependencies = [
"bitflags",
"generic-rt",
"goblin",
"ioslice",
"libredox",
"plain",
"redox-path",
"redox_syscall",
]
[[package]]
name = "redox_event"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5018d583d6d2f5499352aea8d177e9067d1eb03ab17c78169d5ba7a30001b15"
dependencies = [
"bitflags",
"libredox",
"redox_syscall",
]
[[package]]
name = "redox_syscall"
version = "0.9.0+rb0.3.1"
dependencies = [
"bitflags",
]
[[package]]
name = "relibc"
version = "0.2.5+rb0.3.1"
dependencies = [
"argon2",
"arrayvec",
"base64ct",
"bcrypt-pbkdf",
"bitflags",
"cbitset",
"cc",
"chrono",
"chrono-tz",
"dlmalloc",
"generic-rt",
"ioslice",
"libc",
"libm",
"libredox",
"log",
"md-5",
"memchr",
"object",
"pbkdf2",
"plain",
"posix-regex",
"rand",
"rand_jitter",
"rand_xorshift",
"redox-ioctl",
"redox-path",
"redox-rt",
"redox_event",
"redox_syscall",
"sc",
"scrypt",
"sha-crypt",
"sha2",
"spin",
"unicode-width",
]
[[package]]
name = "salsa20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
dependencies = [
"cipher",
]
[[package]]
name = "sc"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010e18bd3bfd1d45a7e666b236c78720df0d9a7698ebaa9c1c559961eb60a38b"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scroll"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1257cd4248b4132760d6524d6dda4e053bc648c9070b960929bf50cfb1e7add"
dependencies = [
"scroll_derive",
]
[[package]]
name = "scroll_derive"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed76efe62313ab6610570951494bdaa81568026e0318eaa55f167de70eeea67d"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "scrypt"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"
dependencies = [
"password-hash",
"pbkdf2",
"salsa20",
"sha2",
]
[[package]]
name = "sha-crypt"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88e79009728d8311d42d754f2f319a975f9e38f156fd5e422d2451486c78b286"
dependencies = [
"base64ct",
"sha2",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "siphasher"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
[[package]]
name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
dependencies = [
"lock_api",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+31 -147
View File
@@ -1,154 +1,38 @@
[package] [package]
name = "relibc" name = "libredox"
version = "0.2.5+rb0.3.1" authors = ["4lDO2 <4lDO2@protonmail.com>", "vasilito <adminpupkin@gmail.com>"]
authors = ["Jeremy Soller <jackpot51@gmail.com>", "vasilito <adminpupkin@gmail.com>"] version = "0.1.18+rb0.3.1"
edition = "2024" edition = "2021"
license = "MIT"
[lib] description = "Redox stable ABI"
name = "relibc" repository = "https://gitea.redbearos.org/vasilito/RedBear-OS"
crate-type = ["staticlib"] exclude = ["target"]
[workspace]
members = [
"src/crt0",
"src/crti",
"src/crtn",
"redox-rt",
"ld_so",
"generic-rt",
]
exclude = ["tests", "dlmalloc-rs"]
[workspace.lints.clippy]
borrow_as_ptr = "deny"
cast_lossless = "warn" # TODO review occurrences
cast_possible_truncation = "allow" # TODO review occurrences
cast_possible_wrap = "allow" # TODO review occurrences
cast_precision_loss = "allow" # TODO review occurrences
cast_ptr_alignment = "allow" # TODO review occurrences
cast_sign_loss = "allow" # TODO review occurrences
ignored_unit_patterns = "deny"
implicit_clone = "deny"
manual_let_else = "deny"
missing_errors_doc = "allow" # TODO review occurrences
missing_panics_doc = "allow" # TODO review occurrences
missing_safety_doc = "allow" # TODO review occurrences
mut_from_ref = "deny"
precedence = "deny"
ptr_as_ptr = "warn" # TODO review occurrences
ptr_cast_constness = "warn" # TODO review occurrences
ptr_offset_by_literal = "deny"
ref_as_ptr = "warn" # TODO review occurrences
type_complexity = "allow" # TODO review occurrences
upper_case_acronyms = "allow" # TODO review occurrences
zero_ptr = "deny" # must allow on public constants due to cbindgen issue
[workspace.lints.rust]
dangling_pointers_from_temporaries = "deny"
dead_code = "allow" # TODO review occuurences
deprecated = "deny"
improper_ctypes_definitions = "deny"
internal_features = "allow" # core_intrinsics and lang_items
irrefutable_let_patterns = "deny"
mismatched_lifetime_syntaxes = "deny"
non_camel_case_types = "allow" # needed for most POSIX type names
non_snake_case = "allow" # TODO review occuurences
non_upper_case_globals = "allow" # TODO review occuurences
unexpected_cfgs = "deny"
unpredictable_function_pointer_comparisons = "deny"
unreachable_code = "allow" # TODO review occuurences
unsafe_op_in_unsafe_fn = "deny"
unused_imports = "deny"
unused_must_use = "deny"
unused_mut = "deny"
unused_unsafe = "deny"
unused_variables = "allow" # TODO review occurrences (too many for now)
[lints]
workspace = true
[workspace.dependencies]
bitflags = "2"
ioslice = { version = "0.6", default-features = false }
plain = "0.2"
redox-path = "0.4.0"
redox_protocols = { package = "libredox", path = "../libredox", default-features = false, features = ["protocol"] }
redox_syscall = { path = "../syscall" }
[build-dependencies]
cc = "1"
[dependencies]
bitflags.workspace = true
arrayvec = { version = "0.7.6", default-features = false }
cbitset = "0.2"
posix-regex = { version = "0.1.4", features = ["no_std"] }
rand = { version = "0.10", default-features = false }
rand_xorshift = "0.5"
rand_jitter = "0.6"
memchr = { version = "2.2.0", default-features = false }
plain.workspace = true
unicode-width = "0.1"
__libc_only_for_layout_checks = { package = "libc", version = "0.2.149", optional = true }
md5-crypto = { package = "md-5", version = "0.10.6", default-features = false }
sha-crypt = { version = "0.5", default-features = false }
base64ct = { version = "1.6", default-features = false, features = ["alloc"] }
bcrypt-pbkdf = { version = "0.10", default-features = false, features = [
"alloc",
] }
scrypt = { version = "0.11", default-features = false, features = ["simple"] }
pbkdf2 = { version = "0.12", features = ["sha2"] }
sha2 = { version = "0.10", default-features = false }
generic-rt = { path = "generic-rt" }
chrono-tz = { version = "0.10", default-features = false }
chrono = { version = "0.4", default-features = false, features = ["alloc"] }
libm = "0.2"
log = "0.4"
spin = "0.9.8"
argon2 = "0.5.3"
[dependencies.dlmalloc]
path = "dlmalloc-rs"
default-features = false
features = ["c_api"]
[dependencies.object]
version = "0.36.7"
git = "https://gitlab.redox-os.org/andypython/object"
branch = "new"
default-features = false
features = ["elf", "read_core"]
[target.'cfg(target_os = "linux")'.dependencies]
sc = "0.2.7"
[target.'cfg(target_os = "redox")'.dependencies]
redox_syscall.workspace = true
redox-rt = { path = "redox-rt" }
redox-path.workspace = true
redox_event = { version = "0.4.8", default-features = false, features = ["redox_syscall"] }
ioslice.workspace = true
redox-ioctl = { path = "redox-ioctl" }
redox_protocols.workspace = true
[features] [features]
# to enable trace level, take out this `no_trace` default = ["base", "call", "std", "protocol", "redox_syscall"]
default = ["check_against_libc_crate", "no_trace"] base = ["libc"]
check_against_libc_crate = ["__libc_only_for_layout_checks"] call = ["base"]
math_libm = [] std = ["base"]
no_trace = ["log/release_max_level_debug"] protocol = ["plain", "bitflags"]
# for very verbose activity beyond trace level mkns = ["ioslice"]
trace_tls = [] # The `redox_syscall` feature activates the optional `redox_syscall`
# dep below. The `#[cfg(feature = "redox_syscall")]` attributes in
# src/lib.rs gate the `From` impls between `libredox::error::Error`
# and `syscall::Error`; without the feature, those impls are absent
# and `?` propagation between the two types fails. Mirroring
# upstream `libredox 0.1.18`'s feature structure.
redox_syscall = ["dep:redox_syscall"]
[profile.dev] [dependencies]
panic = "abort" bitflags = { version = "2", optional = true }
libc = { version = "0.2", optional = true }
[profile.release] # The redox_syscall package has [lib] name = "syscall", so
panic = "abort" # in Rust code it is imported as `syscall`, NOT `redox_syscall`.
# This dep is optional and gated by the `redox_syscall` feature
# above. Matching upstream `libredox 0.1.18` structure.
redox_syscall = { path = "../syscall", optional = true }
ioslice = { version = "0.6", optional = true }
plain = { version = "0.2", optional = true }
[patch.crates-io] [patch.crates-io]
cc-11 = { git = "https://github.com/tea/cc-rs", branch = "riscv-abi-arch-fix", package = "cc" }
redox_syscall = { path = "../syscall" } redox_syscall = { path = "../syscall" }
libredox = { path = "../libredox" }
+44
View File
@@ -0,0 +1,44 @@
[package]
name = "libredox"
authors = ["4lDO2 <4lDO2@protonmail.com>"]
# Red Bear OS Phase J: version is 0.1.18 upstream. The
# redox_syscall dep is now required (not optional) because
# the local fork's acpi module (added in this commit) re-
# exports AcPiVerb from redox_syscall, and downstream recipes
# that don't enable the redox_syscall feature get an
# "unresolved import" error. Making the dep non-optional
# also matches the upstream 0.1.18 Cargo.toml pattern where
# the redox_syscall dep is unconditional.
version = "0.1.18"
edition = "2021"
license = "MIT"
description = "Redox stable ABI"
# Red Bear OS fork lives at the canonical outer repo
# (gitea.redbearos.org/vasilito/RedBear-OS).
repository = "https://gitea.redbearos.org/vasilito/RedBear-OS"
exclude = ["target"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
default = ["base", "call", "std", "protocol"]
base = ["libc"]
call = ["base"]
std = ["base"]
protocol = ["plain", "bitflags", "redox_syscall"]
mkns = ["ioslice"]
[dependencies]
bitflags = { version = "2", optional = true }
libc = { version = "0.2", optional = true }
# Phase J: path override to the local fork (../syscall
# relative to the libredox fork's local/sources/libredox/
# path). This gives libredox access to the EnterS2Idle /
# ExitS2Idle AcpiVerb variants. Cargo's [patch.crates-io]
# in the workspace's outer Cargo.toml (in base/ and kernel/)
# is what wires this path through to the actual
# redox_syscall crate; this path entry is the libredox-
# side patch override for the same crate.
redox_syscall = { path = "../syscall", version = "0.8" }
ioslice = { version = "0.6", optional = true }
plain = { version = "0.2", optional = true }
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2018 Redox OS Copyright (c) 2023 4lDO2
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
-230
View File
@@ -1,230 +0,0 @@
include config.mk
CARGO?=cargo
CARGO_TEST?=$(CARGO)
CARGO_COMMON_FLAGS=-Z build-std=core,alloc,compiler_builtins
CARGOFLAGS?=$(CARGO_COMMON_FLAGS)
CC_WRAPPER?=
RUSTCFLAGS?=
LINKFLAGS?=-lgcc
USE_RUST_LIBM?=
TESTBIN?=
export OBJCOPY?=objcopy
export CARGO_TARGET_DIR?=$(shell pwd)/target
BUILD?=$(CARGO_TARGET_DIR)/$(TARGET)
CARGOFLAGS+=--target=$(TARGET)
EXCEPT_MATH=-not -name "math"
FEATURE_MATH=
ifneq ($(USE_RUST_LIBM),)
FEATURE_MATH=--features math_libm
EXCEPT_MATH=
endif
TARGET_HEADERS?=$(BUILD)/include
export CFLAGS=-I$(TARGET_HEADERS)
PROFILE?=release
HEADERS_UNPARSED=$(shell find src/header -mindepth 1 -maxdepth 1 -type d -not -name "_*" $(EXCEPT_MATH) -printf "%f\n")
HEADERS_DEPS=$(shell find src/header -type f \( -name "cbindgen.toml" -o -name "*.rs" \))
#HEADERS=$(patsubst %,%.h,$(subst _,/,$(HEADERS_UNPARSED)))
SRC=\
Cargo.* \
$(shell find src/ redox-rt/src/ ld_so/src/ redox-ioctl/src/ include/ -type f)
BUILTINS_VERSION=0.1.70
.PHONY: all clean fmt install install-libs install-headers install-tests libs headers submodules test
all: | headers libs
headers: $(BUILD)/$(PROFILE)/librelibc.a $(HEADERS_DEPS)
rm -rf $(TARGET_HEADERS)
mkdir -p $(TARGET_HEADERS)
cp -r include/* $(TARGET_HEADERS)
ifeq ($(USE_RUST_LIBM),)
cp "openlibm/include"/*.h $(TARGET_HEADERS)
cp "openlibm/src"/*.h $(TARGET_HEADERS)
endif
@set -e ; \
for header in $(HEADERS_UNPARSED); do \
if test -f "src/header/$$header/cbindgen.toml"; then \
printf "\033[0;36;49mWriting Header $$header\033[0m\n"; \
out=`echo "$$header" | sed 's/_/\//g'`; \
out="$(TARGET_HEADERS)/$$out.h"; \
cat "src/header/$$header/cbindgen.toml" cbindgen.globdefs.toml \
| cbindgen "src/header/$$header/mod.rs" --config=/dev/stdin --output "$$out"; \
fi \
done; printf "\033[0;36;49mAll headers written\033[0m\n";
clean:
$(CARGO) clean
$(MAKE) -C tests clean
rm -rf sysroot
check:
$(CARGO) check
fmt:
./fmt.sh
install-headers: headers libs
mkdir -pv "$(DESTDIR)/include"
cp -rv "$(TARGET_HEADERS)"/* "$(DESTDIR)/include"
libs: \
$(BUILD)/$(PROFILE)/libc.a \
$(BUILD)/$(PROFILE)/libc.so \
$(BUILD)/$(PROFILE)/crt0.o \
$(BUILD)/$(PROFILE)/crti.o \
$(BUILD)/$(PROFILE)/crtn.o
install-libs: headers libs
mkdir -pv "$(DESTDIR)/lib"
cp -v "$(BUILD)/$(PROFILE)/libc.a" "$(DESTDIR)/lib"
cp -v "$(BUILD)/$(PROFILE)/libc.so" "$(DESTDIR)/lib"
ln -vnfs libc.so "$(DESTDIR)/lib/libc.so.6"
ln -vnfs libc.so "$(DESTDIR)/lib/$(LD_SONAME)"
cp -v "$(BUILD)/$(PROFILE)/crt0.o" "$(DESTDIR)/lib"
ln -vnfs crt0.o "$(DESTDIR)/lib/crt1.o"
ln -vnfs crt0.o "$(DESTDIR)/lib/Scrt1.o"
cp -v "$(BUILD)/$(PROFILE)/crti.o" "$(DESTDIR)/lib"
cp -v "$(BUILD)/$(PROFILE)/crtn.o" "$(DESTDIR)/lib"
ifeq ($(USE_RUST_LIBM),)
cp -v "$(BUILD)/openlibm/libopenlibm.a" "$(DESTDIR)/lib/libm.a"
else
$(AR) -rcs "$(DESTDIR)/lib/libm.a"
endif
# Empty libraries for dl, pthread, and rt
$(AR) -rcs "$(DESTDIR)/lib/libdl.a"
$(AR) -rcs "$(DESTDIR)/lib/libpthread.a"
$(AR) -rcs "$(DESTDIR)/lib/librt.a"
install-tests: tests
$(MAKE) -C tests
mkdir -p "$(DESTDIR)/relibc-tests"
cp -vr tests/build_$(TARGET)/* "$(DESTDIR)/relibc-tests/"
install: install-headers install-libs
submodules:
git submodule sync
git submodule update --init --recursive
sysroot:
@mkdir -p $@
.PHONY: sysroot/$(TARGET)
sysroot/$(TARGET): | sysroot
rm -rf $@
rm -rf $@.partial
mkdir -p $@.partial
$(MAKE) install DESTDIR=$(shell pwd)/$@.partial
mv $@.partial $@
touch $@
test: sysroot/$(TARGET)
# TODO: Fix SIGILL when running cargo test
# $(CARGO_TEST) test
$(MAKE) -C tests run
test-once: sysroot/$(TARGET)
$(MAKE) -C tests run-once TESTBIN=$(TESTBIN)
$(BUILD)/$(PROFILE)/libc.so: $(BUILD)/$(PROFILE)/ld_so.o $(BUILD)/$(PROFILE)/libc.a
# Specifying a dynamic list makes all non-local `STV_DEFAULT`
# definitions non-preemptible, except for the symbols listed in
# `dynlst.txt`. So, the symbols defined in `dynlst.txt` may be
# interposed by other definitions at runtime (either from the
# executable or some shared library).
$(CC) -nostdlib \
-shared \
-Wl,--gc-sections \
-Wl,--dynamic-list=dynlst.txt \
-Wl,-z,pack-relative-relocs \
-Wl,--sort-common \
-Wl,--whole-archive $^ -Wl,--no-whole-archive \
-Wl,-soname,libc.so.6 \
$(LINKFLAGS) \
-o $@
$(BUILD)/$(PROFILE)/libc.a: $(BUILD)/$(PROFILE)/librelibc.a $(BUILD)/openlibm/libopenlibm.a
echo "create $@" > "$@.mri"
for lib in $^; do\
echo "addlib $$lib" >> "$@.mri"; \
done
echo "save" >> "$@.mri"
echo "end" >> "$@.mri"
$(AR) -M < "$@.mri"
# Debug targets
$(BUILD)/debug/librelibc.a: $(SRC)
$(CARGO) rustc $(CARGOFLAGS) $(FEATURE_MATH) -- --emit link=$@ -g -C debug-assertions=no $(RUSTCFLAGS)
./renamesyms.sh "$@" "$(BUILD)/debug/deps/"
./stripcore.sh "$@"
touch $@
$(BUILD)/debug/crt0.o: $(SRC)
$(CARGO) rustc --manifest-path src/crt0/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
$(BUILD)/debug/crti.o: $(SRC)
$(CARGO) rustc --manifest-path src/crti/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
$(BUILD)/debug/crtn.o: $(SRC)
$(CARGO) rustc --manifest-path src/crtn/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
$(BUILD)/debug/ld_so.o: $(SRC)
$(CARGO) rustc --manifest-path ld_so/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort -g -C debug-assertions=no $(RUSTCFLAGS)
touch $@
# Release targets
$(BUILD)/release/librelibc.a: $(SRC)
$(CARGO) rustc --release $(CARGOFLAGS) $(FEATURE_MATH) -- --emit link=$@ $(RUSTCFLAGS)
@# TODO: Better to only allow a certain whitelisted set of symbols? Perhaps
@# use some cbindgen hook, specify them manually, or grep for #[unsafe(no_mangle)].
./renamesyms.sh "$@" "$(BUILD)/release/deps/"
./stripcore.sh "$@"
touch $@
$(BUILD)/release/crt0.o: $(SRC)
$(CARGO) rustc --release --manifest-path src/crt0/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
$(BUILD)/release/crti.o: $(SRC)
$(CARGO) rustc --release --manifest-path src/crti/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
$(BUILD)/release/crtn.o: $(SRC)
$(CARGO) rustc --release --manifest-path src/crtn/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
$(BUILD)/release/ld_so.o: $(SRC)
$(CARGO) rustc --release --manifest-path ld_so/Cargo.toml $(CARGOFLAGS) -- --emit obj=$@ -C panic=abort $(RUSTCFLAGS)
touch $@
# Other targets
$(BUILD)/openlibm: openlibm
rm -rf $@ $@.partial
mkdir -p $(BUILD)
cp -r $< $@.partial
mv $@.partial $@
touch $@
ifeq ($(USE_RUST_LIBM),)
$(BUILD)/openlibm/libopenlibm.a: $(BUILD)/openlibm headers $(BUILD)/$(PROFILE)/librelibc.a
$(MAKE) -s AR=$(AR) CC="$(CC_WRAPPER) $(CC)" LD=$(LD) CPPFLAGS="$(CPPFLAGS) -fno-stack-protector -I$(shell pwd)/include -I$(TARGET_HEADERS)" -C $< libopenlibm.a
./renamesyms.sh "$@" "$(BUILD)/$(PROFILE)/deps/"
else
$(BUILD)/openlibm/libopenlibm.a:
mkdir -p "$(BUILD)/openlibm"
$(AR) -rcs "$(BUILD)/openlibm/libopenlibm.a"
endif
-173
View File
@@ -1,173 +0,0 @@
# Redox C Library (relibc)
relibc is a portable C standard library written in Rust and is under heavy development, this library contains the following items:
- C, Linux, BSD functions and extensions
- POSIX compatibility layer
- Interfaces for system components
The motivation for this project is twofold: Reduce issues that the Redox developers were having with [newlib](https://sourceware.org/newlib/), and create a more stable and safe alternative to C standard libraries written in C. It is mainly designed to be used under Redox, as an alternative to newlib, but it also supports Linux via the [sc](https://crates.io/crates/sc) crate.
Currently Redox and Linux are supported.
## `redox-rt`
`redox-rt` is a runtime library that provides much of the code that enables POSIX on Redox, like `fork`, `exec`, signal handling, etc.
Relibc uses it as backend in `src/platform/redox`, and it's intended to eventually be usable independently, without relibc.
## Repository Layout
- `include` - Header files (mostly macros and variadic functions `cbindgen` can't generate)
- `src` - Source files
- `src/c` - C code
- `src/crt0` - Runtime code
- `src/crti` - Runtime code
- `src/crtn` - Runtime code
- `src/header` - Header files implementation
- `src/header/*` - Each folder has a `cbindgen.toml` file, it generates a C-to-Rust interface and header files
- `src/ld_so` - Dynamic loader code
- `src/platform` - Platform-specific and common code
- `src/platform/redox` - Redox-specific code
- `src/platform/linux` - Linux-specific code
- `src/pthread` - pthread implementation
- `src/sync` - Synchronization primitives
- `tests` - C tests (each MR needs to give success in all of them)
## Download the sources
To download the relibc sources run the following command:
```sh
git clone --recursive https://gitlab.redox-os.org/redox-os/relibc
```
## Build Instructions
To build relibc out of the Redox build system, do the following steps:
### Dependencies
- Install `cbindgen`
```sh
cargo install cbindgen
```
#### Install the `expect` tool
- Debian, Ubuntu and PopOS:
```sh
sudo apt install expect
```
- Fedora:
```sh
sudo dnf install expect
```
- Arch Linux:
```sh
sudo pacman -S expect
```
### Build Relibc
To build the relibc library objects, run the following command:
```sh
make all
```
- Clean old library objects and tests
```sh
make clean
```
## Build relibc inside the Redox build system
Inside of your Redox build system, run:
```sh
make prefix
```
If you need to rebuild `relibc` for testing a Cookbook recipe, run:
```sh
touch relibc
make prefix r.recipe-name
```
Touching (changing the "last modified time" of) the `relibc` folder is needed to trigger recompilation for `make prefix`. Replace `recipe-name` with your desired recipe name.
Note: Do not edit `relibc` inside `prefix` folder! Do your work on `relibc` folder directly inside your Redox build system instead.
## Tests
Relibc has a test suite that also runs every time a new commit get pushed. You can see `.gitlab-ci.yml` to see how it's being executed. That being said, `./check.sh` is the recommended way to run tests. Here's few examples:
+ `./check.sh` - Run build, without running the test
+ `./check.sh --test` - Run all tests in x86_64 Redox using Redoxer
+ `./check.sh --test --host` - Run all tests in host (Linux)
+ `./check.sh --test --arch=aarch64` - Run all tests in specified arch
- Arch can be `x86_64`, `aarch64`, `i586`, or `riscv64gc`
+ `./check.sh --test=stdio/printf` - Run a single test
- Can be combined with `--host` or `--arch`
- Will run statically linked test in Linux, dynamically linked in Redox
Couple of notes:
- Relibc and its tests will rebuild if files are changed, however switching between arch or host requires you to run `make clean`
- Redoxer is needed to run tests for Redox without `--host`. You can install it using `cargo install redoxer`
- Tests can hang, the test runner can anticipate this, assuming the kernel doesn't hang too.
## Issues
#### I'm building for my own platform which I run, and am getting `x86_64-linux-gnu-ar: command not found` (or similar)
The Makefile expects GNU compiler tools prefixed with the platform specifier, as would be present when you installed a cross compiler. Since you are building for your own platform, some Linux distributions (like Manjaro) don't install/symlink the prefixed executables.
An easy fix would be to replace the corresponding lines in `config.mk`, e.g.
```diff
ifeq ($(TARGET),x86_64-unknown-linux-gnu)
- export CC=x86_64-linux-gnu-gcc
- export LD=x86_64-linux-gnu-ld
- export AR=x86_64-linux-gnu-ar
- export NM=x86_64-linux-gnu-nm
+ export CC=gcc
+ export LD=ld
+ export AR=ar
+ export NM=nm
export OBJCOPY=objcopy
export CPPFLAGS=
LD_SO_PATH=lib/ld64.so.1
endif
```
## Contributing
Before starting to contribute, read [this](CONTRIBUTING.md) document.
## Supported OSes
- Redox OS
- Linux
## Supported architectures
- i586 (Intel/AMD)
- x86_64 (Intel/AMD)
- aarch64 (ARM64)
- riscv64gc (RISC-V)
## Funding - _Unix-style Signals and Process Management_
This project is funded through [NGI Zero Core](https://nlnet.nl/core), a fund established by [NLnet](https://nlnet.nl) with financial support from the European Commission's [Next Generation Internet](https://ngi.eu) program. Learn more at the [NLnet project page](https://nlnet.nl/project/RedoxOS-Signals).
[<img src="https://nlnet.nl/logo/banner.png" alt="NLnet foundation logo" width="20%" />](https://nlnet.nl)
[<img src="https://nlnet.nl/image/logos/NGI0_tag.svg" alt="NGI Zero Logo" width="20%" />](https://nlnet.nl/core)
-30
View File
@@ -1,30 +0,0 @@
extern crate cc;
use std::{env, fs};
fn main() {
let _crate_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
let target = env::var("TARGET").unwrap();
println!("cargo:rerun-if-changed=src/c");
let mut cc_builder = &mut cc::Build::new();
cc_builder = cc_builder.flag("-nostdinc").flag("-nostdlib");
if target.starts_with("aarch64") {
cc_builder = cc_builder.flag("-mno-outline-atomics")
}
cc_builder
.flag("-fno-stack-protector")
.flag("-Wno-expansion-to-defined")
.files(
fs::read_dir("src/c")
.expect("src/c directory missing")
.map(|res| res.expect("read_dir error").path()),
)
.compile("relibc_c");
println!("cargo:rustc-link-lib=static=relibc_c");
}
-25
View File
@@ -1,25 +0,0 @@
# needs a leading newline
[defines]
"target_os=redox" = "__redox__"
"target_os=linux" = "__linux__"
"target_pointer_width=64" = "__LP64__"
"target_pointer_width=32" = "__ILP32__"
"target_arch=x86" = "__i386__"
"target_arch=x86_64" = "__x86_64__"
"target_arch=aarch64" = "__aarch64__"
# This is not exact. It should be `defined(__riscv) && defined(__LP64__)`, or `defined(__riscv) && __riscv_xlen==64`
# This will do however, as long as we only support riscv64 and not riscv32
"target_arch=riscv64" = "__riscv"
# XXX: silences a warning
"feature = no_std" = "__relibc__"
"feature = ip6" = "__ip6__"
# Ensure attributes are passed down from Rust
# <features.h> must be included where attributes are used in relibc
[fn]
must_use = "__nodiscard"
deprecated = "__deprecated"
deprecated_with_note = "__deprecatedNote({})"
no_return = "__noreturn"
-170
View File
@@ -1,170 +0,0 @@
#!/bin/bash
RED='\033[1;38;5;196m'
GREEN='\033[1;38;5;46m'
NC='\033[0m'
show_help() {
echo "Usage: $(basename "$0") [OPTIONS]"
echo ""
echo "Description:"
echo " Wrapper for Makefile / Cargo to run checks or tests on Redox OS targets."
echo ""
echo "Options:"
echo " --test Run 'make test' instead of 'make all'"
echo " --test= Run single 'make test'"
echo " --cargo Run 'cargo check' / 'cargo test' instead"
echo " (note: cargo test is currently not maintained for relibc)"
echo " --host Run the command on host (linux) target"
echo " --all-target Run the command on all supported Redox architectures"
echo " --target=<target> Override the target architecture (e.g., i586-unknown-redox)"
echo " --arch=<arch> Override the target architecture using arch (e.g., i586)"
echo " --help Show this help message"
echo ""
echo "Supported Targets:"
for t in "${SUPPORTED_TARGETS[@]}"; do
echo " - $t"
done
echo " - $(uname -m)-unknown-linux-gnu"
echo ""
echo "Environment:"
echo " TARGET Sets the default target (overridden by --target)"
}
if ! command -v cbindgen &> /dev/null; then
echo "Error: 'cbindgen' CLI not found."
echo "Please install it: cargo install cbindgen"
exit 1
fi
SUPPORTED_TARGETS=(
"x86_64-unknown-redox"
"i586-unknown-redox"
"aarch64-unknown-redox"
"riscv64gc-unknown-redox"
)
CURRENT_TARGET="${TARGET:-x86_64-unknown-redox}"
CHECK_ALL=false
CMD_ACTION="make"
CARGO_ACTION="check"
MAKE_ACTION="all"
TEST_BIN=""
IS_HOST=0
while [[ $# -gt 0 ]]; do
case "$1" in
--all-target)
CHECK_ALL=true
;;
--test)
MAKE_ACTION="test"
CARGO_ACTION="test"
;;
--test=*)
TEST_BIN="${1#*=}"
MAKE_ACTION="test-once"
;;
--cargo)
CMD_ACTION="cargo"
;;
--clippy)
CMD_ACTION="cargo"
CARGO_ACTION="clippy"
;;
--host)
CURRENT_TARGET="$(uname -m)-unknown-linux-gnu"
IS_HOST=1
;;
--target=*)
CURRENT_TARGET="${1#*=}"
;;
--arch=*)
CURRENT_TARGET="${1#*=}-unknown-redox"
;;
--help)
show_help
exit 0
;;
*)
echo -e "${RED}Error: Unknown option '$1'${NC}"
show_help
exit 1
;;
esac
shift
done
if [ "$IS_HOST" -eq 0 ]; then
if ! command -v redoxer &> /dev/null; then
echo "Error: 'redoxer' CLI not found."
echo "Please install it: cargo install redoxer"
exit 1
fi
fi
run_redoxer() {
export TARGET=$1
REDOXER_ENV="redoxer env"
if [ "$IS_HOST" -eq 0 ]; then
redoxer toolchain || { echo -e "${RED}Fail: redoxer toolchain for: $target.${NC}" && exit 1; }
export CARGO_TEST="redoxer"
export TEST_RUNNER="redoxer exec --folder ../../sysroot/$TARGET/:/usr --folder . --"
MAKE_ACTION="$MAKE_ACTION IS_REDOX=1"
else
REDOXER_ENV=""
fi
if [ "$TEST_BIN" != "" ]; then
if [ "$IS_HOST" -eq 0 ]; then
MAKE_ACTION="$MAKE_ACTION TESTBIN=bins_dynamic/$TEST_BIN"
else
MAKE_ACTION="$MAKE_ACTION TESTBIN=bins_static/$TEST_BIN"
fi
fi
if [ "$CMD_ACTION" == "make" ]; then
CMD_OPT="-j $(nproc) $MAKE_ACTION"
else
CMD_OPT="$CARGO_ACTION --target=$TARGET"
fi
echo "----------------------------------------"
echo "Running $REDOXER_ENV $CMD_ACTION $CMD_OPT for: $TARGET"
if $REDOXER_ENV $CMD_ACTION $CMD_OPT; then
return 0
else
echo -e "${RED}Fail: $CMD_ACTION $CMD_OPT for $TARGET failed.${NC}"
return 1
fi
}
if [ "$CHECK_ALL" = true ]; then
echo "Running $CMD_ACTION for all supported Redox targets..."
has_error=false
for target in "${SUPPORTED_TARGETS[@]}"; do
if ! run_redoxer "$target"; then
has_error=true
fi
done
echo "----------------------------------------"
if [ "$has_error" = true ]; then
echo -e "${RED}Summary: One or more targets failed.${NC}"
exit 1
else
echo -e "${GREEN}Summary: All targets passed!${NC}"
exit 0
fi
else
if run_redoxer "$CURRENT_TARGET"; then
echo -e "${GREEN}Success: $CARGO_ACTION for $CURRENT_TARGET passed.${NC}"
exit 0
else
exit 1
fi
fi
-94
View File
@@ -1,94 +0,0 @@
ifndef TARGET
export TARGET:=$(shell rustc -Z unstable-options --print target-spec-json | grep llvm-target | cut -d '"' -f4)
endif
ifeq ($(TARGET),aarch64-unknown-linux-gnu)
export CC=aarch64-linux-gnu-gcc
export LD=aarch64-linux-gnu-ld
export AR=aarch64-linux-gnu-ar
export NM=aarch64-linux-gnu-nm
export OBJCOPY=aarch64-linux-gnu-objcopy
export CPPFLAGS=
LD_SONAME=ld.so.1
endif
ifeq ($(TARGET),aarch64-unknown-linux-relibc)
export CC=aarch64-linux-relibc-gcc
export LD=aarch64-linux-relibc-ld
export AR=aarch64-linux-relibc-ar
export NM=aarch64-linux-relibc-nm
export OBJCOPY=aarch64-linux-relibc-objcopy
export CPPFLAGS=
LD_SONAME=ld.so.1
endif
ifeq ($(TARGET),aarch64-unknown-redox)
export CC=aarch64-unknown-redox-gcc
export LD=aarch64-unknown-redox-ld
export AR=aarch64-unknown-redox-ar
export NM=aarch64-unknown-redox-nm
export OBJCOPY=aarch64-unknown-redox-objcopy
export CPPFLAGS=
LD_SONAME=ld.so.1
endif
ifeq ($(TARGET),i586-unknown-redox)
export CC=i586-unknown-redox-gcc
export LD=i586-unknown-redox-ld
export AR=i586-unknown-redox-ar
export NM=i586-unknown-redox-nm
export OBJCOPY=i586-unknown-redox-objcopy
export CPPFLAGS=
LD_SONAME=ld.so.1
endif
ifeq ($(TARGET),i686-unknown-redox)
export CC=i686-unknown-redox-gcc
export LD=i686-unknown-redox-ld
export AR=i686-unknown-redox-ar
export NM=i686-unknown-redox-nm
export OBJCOPY=i686-unknown-redox-objcopy
export CPPFLAGS=
LD_SONAME=ld.so.1
endif
ifeq ($(TARGET),x86_64-unknown-linux-gnu)
export CC=x86_64-linux-gnu-gcc
export LD=x86_64-linux-gnu-ld
export AR=x86_64-linux-gnu-ar
export NM=x86_64-linux-gnu-nm
export OBJCOPY=objcopy
export CPPFLAGS=
LD_SONAME=ld64.so.1
endif
ifeq ($(TARGET),x86_64-unknown-linux-relibc)
export CC=x86_64-linux-relibc-gcc
export LD=x86_64-linux-relibc-ld
export AR=x86_64-linux-relibc-ar
export NM=x86_64-linux-relibc-nm
export OBJCOPY=x86_64-linux-relibc-objcopy
export CPPFLAGS=
LD_SONAME=ld64.so.1
endif
ifeq ($(TARGET),x86_64-unknown-redox)
export CC=x86_64-unknown-redox-gcc
export LD=x86_64-unknown-redox-ld
export AR=x86_64-unknown-redox-ar
export NM=x86_64-unknown-redox-nm
export OBJCOPY=x86_64-unknown-redox-objcopy
export CPPFLAGS=
LD_SONAME=ld64.so.1
endif
ifeq ($(TARGET),riscv64gc-unknown-redox)
export CC=riscv64-unknown-redox-gcc
export LD=riscv64-unknown-redox-ld
export AR=riscv64-unknown-redox-ar
export NM=riscv64-unknown-redox-nm
export OBJCOPY=riscv64-unknown-redox-objcopy
export CPPFLAGS=-march=rv64gc -mabi=lp64d
LD_SONAME=ld.so.1
endif
Submodule dlmalloc-rs deleted from 3b0ee3b467
-27
View File
@@ -1,27 +0,0 @@
{
environ;
stdin;
stdout;
stderr;
timezone;
daylight;
tzname;
__timezone;
__daylight;
__tzname;
signgam;
__signgam;
optarg;
optind;
opterr;
optreset;
__optreset;
getdate_err;
__stack_chk_guard;
};
-3
View File
@@ -1,3 +0,0 @@
#!/usr/bin/env bash
cargo fmt --package relibc --package crt0 --package redox-rt "$@"
-7
View File
@@ -1,7 +0,0 @@
[package]
name = "generic-rt"
version = "0.1.0"
edition = "2024"
[lints]
workspace = true
-99
View File
@@ -1,99 +0,0 @@
#![no_std]
#![allow(internal_features)]
#![deny(unsafe_op_in_unsafe_fn)]
use core::{
arch::asm,
mem::{self, offset_of},
};
#[derive(Debug)]
#[repr(C)]
pub struct GenericTcb<Os> {
/// Pointer to the end of static TLS. Must be the first member
pub tls_end: *mut u8,
/// Size of the memory allocated for the static TLS in bytes (multiple of page size)
pub tls_len: usize,
/// Pointer to this structure
pub tcb_ptr: *mut Self,
/// Size of the memory allocated for this structure in bytes (should be same as page size)
pub tcb_len: usize,
pub os_specific: Os,
}
impl<Os> GenericTcb<Os> {
/// Architecture specific code to read a usize from the TCB - aarch64
#[allow(unsafe_op_in_unsafe_fn)]
#[inline(always)]
#[cfg(target_arch = "aarch64")]
pub unsafe fn arch_read(offset: usize) -> usize {
let abi_ptr: usize;
asm!(
"mrs {}, tpidr_el0",
out(reg) abi_ptr,
);
let tcb_ptr = *(abi_ptr as *const usize);
*((tcb_ptr + offset) as *const usize)
}
/// Architecture specific code to read a usize from the TCB - x86
#[allow(unsafe_op_in_unsafe_fn)]
#[inline(always)]
#[cfg(target_arch = "x86")]
pub unsafe fn arch_read(offset: usize) -> usize {
let value;
asm!(
"
mov {}, gs:[{}]
",
out(reg) value,
in(reg) offset,
);
value
}
/// Architecture specific code to read a usize from the TCB - x86_64
#[allow(unsafe_op_in_unsafe_fn)]
#[inline(always)]
#[cfg(target_arch = "x86_64")]
pub unsafe fn arch_read(offset: usize) -> usize {
let value;
asm!(
"
mov {}, fs:[{}]
",
out(reg) value,
in(reg) offset,
);
value
}
/// Architecture specific code to read a usize from the TCB - riscv64
#[allow(unsafe_op_in_unsafe_fn)]
#[inline(always)]
#[cfg(target_arch = "riscv64")]
unsafe fn arch_read(offset: usize) -> usize {
let value;
asm!(
"ld {value}, -8(tp)", // TCB
"add {value}, {value}, {offset}",
"ld {value}, 0({value})",
value = out(reg) value,
offset = in(reg) offset,
);
value
}
pub unsafe fn current_ptr() -> Option<*mut Self> {
let tcb_ptr = unsafe { Self::arch_read(offset_of!(Self, tcb_ptr)) as *mut Self };
let tcb_len = unsafe { Self::arch_read(offset_of!(Self, tcb_len)) };
if tcb_ptr.is_null() || tcb_len < mem::size_of::<Self>() {
None
} else {
Some(tcb_ptr)
}
}
pub unsafe fn current() -> Option<&'static mut Self> {
unsafe { Some(&mut *Self::current_ptr()?) }
}
}
-6
View File
@@ -1,6 +0,0 @@
#ifndef _ALLOCA_H
#define _ALLOCA_H
#define alloca(size) __builtin_alloca (size)
#endif /* _ALLOCA_H */
-1
View File
@@ -1 +0,0 @@
#include <openlibm_complex.h>
-112
View File
@@ -1,112 +0,0 @@
/*
* MIT License
* Copyright (c) 2020 Rich Felker musl-libc
*/
#ifndef _FEATURES_H__RELIBC
#define _FEATURES_H__RELIBC
// Version metadata for feature gating
// This is useful for divergent implementation specific behavior
// glibc, ulibc, and likely others define a similar macro
// musl does not define an equivalent macro
#define __RELIBC__ 1
#define __RELIBC__MAJOR 0
#define __RELIBC__MINOR 2
/*
* Sources:
* https://en.cppreference.com/w/c/language/attributes
* https://clang.llvm.org/docs/LanguageExtensions.html
* https://gcc.gnu.org/onlinedocs/cpp/_005f_005fhas_005fc_005fattribute.html
* https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
*/
// Clang doesn't define __has_cpp_attribute if compiling C code
#if !defined(__has_cpp_attribute)
#define __has_cpp_attribute(x) 0
#endif
// Clang doesn't define __has_c_attribute if compiling C++ code
#if !defined(__has_c_attribute)
#define __has_c_attribute(x) 0
#endif
// Check if C23+ attributes are available
#if defined(__cplusplus)
// HACK: GCC backports C++ attributes to C++98 but doesn't accept attributes
// placed before the function like cbindgen emits.
// Let's just disable attributes for C++98 by checking if a random C++11
// feature is available.
#define __HAS_ATTRIBUTE(x) __cpp_variable_templates &&__has_cpp_attribute(x)
#else
#define __HAS_ATTRIBUTE(x) \
(__has_c_attribute(x) || __STDC_VERSION__ >= 202311L || \
__has_cpp_attribute(x))
#endif
// From musl, license MIT {
#if defined(_ALL_SOURCE) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE 1
#endif
#if defined(_DEFAULT_SOURCE) && !defined(_BSD_SOURCE)
#define _BSD_SOURCE 1
#endif
#if !defined(_POSIX_SOURCE) && !defined(_POSIX_C_SOURCE) \
&& !defined(_XOPEN_SOURCE) && !defined(_GNU_SOURCE) \
&& !defined(_BSD_SOURCE) && !defined(__STRICT_ANSI__)
#define _BSD_SOURCE 1
#define _XOPEN_SOURCE 700
#endif
// } from musl
// TODO: Not emitted with cbindgen
#if __STDC_VERSION__ >= 199901L
#define __restrict restrict
#elif !defined(__GNUC__)
#define __restrict
#endif
// TODO: Not emitted with cbindgen
#if __STDC_VERSION__ >= 199901L || defined(__cplusplus)
#define __inline inline
#elif !defined(__GNUC__)
#define __inline
#endif
// Analogous to Rust's Never type
//TODO: clang fails to compile C with [[noreturn]]
#if defined(__cplusplus) && __HAS_ATTRIBUTE(noreturn) && !(__clang__)
#define __noreturn [[noreturn]]
// #elif __STDC_VERSION__ >= 201112L
// FIXME: cbindgen incorrectly places _Noreturn
// #define __noreturn _Noreturn
#elif defined(__GNUC__)
#define __noreturn __attribute__((__noreturn__))
#else
#define __noreturn
#endif
// Analogous to Rust's #[must_use]
// C23 only
#if __HAS_ATTRIBUTE(nodiscard)
#define __nodiscard [[nodiscard]]
#define __nodiscardNote(x) [[nodiscard(x)]]
#else
#define __nodiscard
#define __nodiscardNote(x)
#endif
// Analogous to Rust's #[deprecated]
// C23 only
#if __HAS_ATTRIBUTE(deprecated)
#define __deprecated [[deprecated]]
#define __deprecatedNote(x) [[deprecated(x)]]
#else
#define __deprecated
#define __deprecatedNote(x)
#endif
#endif
-3
View File
@@ -1,3 +0,0 @@
#include <openlibm_fenv.h>
#undef complex
#undef I
-22
View File
@@ -1,22 +0,0 @@
// Copied from musl
#ifndef _ISO646_H
#define _ISO646_H
#ifndef __cplusplus
#define and &&
#define and_eq &=
#define bitand &
#define bitor |
#define compl ~
#define not !
#define not_eq !=
#define or ||
#define or_eq |=
#define xor ^
#define xor_eq ^=
#endif
#endif
-17
View File
@@ -1,17 +0,0 @@
#ifndef __MACHINE_ENDIAN_H__
/* TODO: Forcing little endian, if you need a big endian system, fix this { */
#ifndef BIG_ENDIAN
#define BIG_ENDIAN 4321
#endif
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN 1234
#endif
#ifndef BYTE_ORDER
#define BYTE_ORDER LITTLE_ENDIAN
#endif
/* } */
#endif /* __MACHINE_ENDIAN_H__ */
-113
View File
@@ -1,113 +0,0 @@
#include <openlibm_math.h>
// Missing typedefs
typedef float float_t;
typedef double double_t;
/* double */
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923 /* pi/2 */
#endif
#ifndef M_PI_4
#define M_PI_4 0.78539816339744830962 /* pi/4 */
#endif
#ifndef M_2_PI
#define M_2_PI 0.63661977236758134308 /* 2/pi */
#endif
#ifndef M_E
#define M_E 2.7182818284590452354 /* e */
#endif
#ifndef M_LOG2E
#define M_LOG2E 1.4426950408889634074 /* log_2 e */
#endif
#ifndef M_LOG10E
#define M_LOG10E 0.43429448190325182765 /* log_10 e */
#endif
#ifndef M_LN2
#define M_LN2 0.69314718055994530942 /* log_e 2 */
#endif
#ifndef M_LN10
#define M_LN10 2.30258509299404568402 /* log_e 10 */
#endif
#ifndef M_1_PI
#define M_1_PI 0.31830988618379067154 /* 1/pi */
#endif
#ifndef M_2_SQRTPI
#define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */
#endif
#ifndef M_SQRT2
#define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
#endif
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */
#endif
/* long double */
#ifndef M_El
#define M_El 2.718281828459045235360287471352662498L /* e */
#endif
#ifndef M_LOG2El
#define M_LOG2El 1.442695040888963407359924681001892137L /* log_2 e */
#endif
#ifndef M_LOG10El
#define M_LOG10El 0.434294481903251827651128918916605082L /* log_10 e */
#endif
#ifndef M_LN2l
#define M_LN2l 0.693147180559945309417232121458176568L /* log_e 2 */
#endif
#ifndef M_LN10l
#define M_LN10l 2.302585092994045684017991454684364208L /* log_e 10 */
#endif
#ifndef M_PIl
#define M_PIl 3.141592653589793238462643383279502884L /* pi */
#endif
#ifndef M_PI_2l
#define M_PI_2l 1.570796326794896619231321691639751442L /* pi/2 */
#endif
#ifndef M_PI_4l
#define M_PI_4l 0.785398163397448309615660845819875721L /* pi/4 */
#endif
#ifndef M_1_PIl
#define M_1_PIl 0.318309886183790671537767526745028724L /* 1/pi */
#endif
#ifndef M_2_PIl
#define M_2_PIl 0.636619772367581343075535053490057448L /* 2/pi */
#endif
#ifndef M_2_SQRTPIl
#define M_2_SQRTPIl 1.128379167095512573896158903121545172L /* 2/sqrt(pi) */
#endif
#ifndef M_SQRT2l
#define M_SQRT2l 1.414213562373095048801688724209698079L /* sqrt(2) */
#endif
#ifndef M_SQRT1_2l
#define M_SQRT1_2l 0.707106781186547524400844362104849039L /* 1/sqrt(2) */
#endif
-1
View File
@@ -1 +0,0 @@
#include <string.h>
-10
View File
@@ -1,10 +0,0 @@
#ifndef _NETINET_IN_SYSTM_H
#define _NETINET_IN_SYSTM_H
#include <stdint.h>
typedef uint16_t n_short;
typedef uint32_t n_long;
typedef uint32_t n_time;
#endif
-6
View File
@@ -1,6 +0,0 @@
#ifndef _RELIBC_PATHS_H
#define _RELIBC_PATHS_H
#define _PATH_BSHELL "/bin/sh"
#endif
-35
View File
@@ -1,35 +0,0 @@
#ifndef _SETJMP_H
#define _SETJMP_H
#ifdef __aarch64__
typedef unsigned long long jmp_buf[22];
#endif
#ifdef __i386__
typedef unsigned long long jmp_buf[6];
#endif
#ifdef __x86_64__
typedef unsigned long long jmp_buf[16];
#endif
#ifdef __riscv
typedef unsigned long long jmp_buf[26];
#endif
typedef jmp_buf sigjmp_buf;
#ifdef __cplusplus
extern "C" {
#endif
int setjmp(jmp_buf buf);
void longjmp(jmp_buf buf, int value);
int sigsetjmp(jmp_buf buf, int savemask);
int siglongjmp(jmp_buf buf, int savemask);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* _SETJMP_H */
-243
View File
@@ -1,243 +0,0 @@
/* Copyright (C) 2013-2022 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* ISO C11 Standard: 7.17 Atomics <stdatomic.h>. */
#ifndef _STDATOMIC_H
#define _STDATOMIC_H
typedef enum
{
memory_order_relaxed = __ATOMIC_RELAXED,
memory_order_consume = __ATOMIC_CONSUME,
memory_order_acquire = __ATOMIC_ACQUIRE,
memory_order_release = __ATOMIC_RELEASE,
memory_order_acq_rel = __ATOMIC_ACQ_REL,
memory_order_seq_cst = __ATOMIC_SEQ_CST
} memory_order;
typedef _Atomic _Bool atomic_bool;
typedef _Atomic char atomic_char;
typedef _Atomic signed char atomic_schar;
typedef _Atomic unsigned char atomic_uchar;
typedef _Atomic short atomic_short;
typedef _Atomic unsigned short atomic_ushort;
typedef _Atomic int atomic_int;
typedef _Atomic unsigned int atomic_uint;
typedef _Atomic long atomic_long;
typedef _Atomic unsigned long atomic_ulong;
typedef _Atomic long long atomic_llong;
typedef _Atomic unsigned long long atomic_ullong;
typedef _Atomic __CHAR16_TYPE__ atomic_char16_t;
typedef _Atomic __CHAR32_TYPE__ atomic_char32_t;
typedef _Atomic __WCHAR_TYPE__ atomic_wchar_t;
typedef _Atomic __INT_LEAST8_TYPE__ atomic_int_least8_t;
typedef _Atomic __UINT_LEAST8_TYPE__ atomic_uint_least8_t;
typedef _Atomic __INT_LEAST16_TYPE__ atomic_int_least16_t;
typedef _Atomic __UINT_LEAST16_TYPE__ atomic_uint_least16_t;
typedef _Atomic __INT_LEAST32_TYPE__ atomic_int_least32_t;
typedef _Atomic __UINT_LEAST32_TYPE__ atomic_uint_least32_t;
typedef _Atomic __INT_LEAST64_TYPE__ atomic_int_least64_t;
typedef _Atomic __UINT_LEAST64_TYPE__ atomic_uint_least64_t;
typedef _Atomic __INT_FAST8_TYPE__ atomic_int_fast8_t;
typedef _Atomic __UINT_FAST8_TYPE__ atomic_uint_fast8_t;
typedef _Atomic __INT_FAST16_TYPE__ atomic_int_fast16_t;
typedef _Atomic __UINT_FAST16_TYPE__ atomic_uint_fast16_t;
typedef _Atomic __INT_FAST32_TYPE__ atomic_int_fast32_t;
typedef _Atomic __UINT_FAST32_TYPE__ atomic_uint_fast32_t;
typedef _Atomic __INT_FAST64_TYPE__ atomic_int_fast64_t;
typedef _Atomic __UINT_FAST64_TYPE__ atomic_uint_fast64_t;
typedef _Atomic __INTPTR_TYPE__ atomic_intptr_t;
typedef _Atomic __UINTPTR_TYPE__ atomic_uintptr_t;
typedef _Atomic __SIZE_TYPE__ atomic_size_t;
typedef _Atomic __PTRDIFF_TYPE__ atomic_ptrdiff_t;
typedef _Atomic __INTMAX_TYPE__ atomic_intmax_t;
typedef _Atomic __UINTMAX_TYPE__ atomic_uintmax_t;
#define ATOMIC_VAR_INIT(VALUE) (VALUE)
/* Initialize an atomic object pointed to by PTR with VAL. */
#define atomic_init(PTR, VAL) \
atomic_store_explicit (PTR, VAL, __ATOMIC_RELAXED)
#define kill_dependency(Y) \
__extension__ \
({ \
__auto_type __kill_dependency_tmp = (Y); \
__kill_dependency_tmp; \
})
extern void atomic_thread_fence (memory_order);
#define atomic_thread_fence(MO) __atomic_thread_fence (MO)
extern void atomic_signal_fence (memory_order);
#define atomic_signal_fence(MO) __atomic_signal_fence (MO)
#define atomic_is_lock_free(OBJ) __atomic_is_lock_free (sizeof (*(OBJ)), (OBJ))
#define ATOMIC_BOOL_LOCK_FREE __GCC_ATOMIC_BOOL_LOCK_FREE
#define ATOMIC_CHAR_LOCK_FREE __GCC_ATOMIC_CHAR_LOCK_FREE
#define ATOMIC_CHAR16_T_LOCK_FREE __GCC_ATOMIC_CHAR16_T_LOCK_FREE
#define ATOMIC_CHAR32_T_LOCK_FREE __GCC_ATOMIC_CHAR32_T_LOCK_FREE
#define ATOMIC_WCHAR_T_LOCK_FREE __GCC_ATOMIC_WCHAR_T_LOCK_FREE
#define ATOMIC_SHORT_LOCK_FREE __GCC_ATOMIC_SHORT_LOCK_FREE
#define ATOMIC_INT_LOCK_FREE __GCC_ATOMIC_INT_LOCK_FREE
#define ATOMIC_LONG_LOCK_FREE __GCC_ATOMIC_LONG_LOCK_FREE
#define ATOMIC_LLONG_LOCK_FREE __GCC_ATOMIC_LLONG_LOCK_FREE
#define ATOMIC_POINTER_LOCK_FREE __GCC_ATOMIC_POINTER_LOCK_FREE
/* Note that these macros require __auto_type to remove
_Atomic qualifiers (and const qualifiers, if those are valid on
macro operands).
Also note that the header file uses the generic form of __atomic
builtins, which requires the address to be taken of the value
parameter, and then we pass that value on. This allows the macros
to work for any type, and the compiler is smart enough to convert
these to lock-free _N variants if possible, and throw away the
temps. */
#define atomic_store_explicit(PTR, VAL, MO) \
__extension__ \
({ \
__auto_type __atomic_store_ptr = (PTR); \
__typeof__ ((void)0, *__atomic_store_ptr) __atomic_store_tmp = (VAL); \
__atomic_store (__atomic_store_ptr, &__atomic_store_tmp, (MO)); \
})
#define atomic_store(PTR, VAL) \
atomic_store_explicit (PTR, VAL, __ATOMIC_SEQ_CST)
#define atomic_load_explicit(PTR, MO) \
__extension__ \
({ \
__auto_type __atomic_load_ptr = (PTR); \
__typeof__ ((void)0, *__atomic_load_ptr) __atomic_load_tmp; \
__atomic_load (__atomic_load_ptr, &__atomic_load_tmp, (MO)); \
__atomic_load_tmp; \
})
#define atomic_load(PTR) atomic_load_explicit (PTR, __ATOMIC_SEQ_CST)
#define atomic_exchange_explicit(PTR, VAL, MO) \
__extension__ \
({ \
__auto_type __atomic_exchange_ptr = (PTR); \
__typeof__ ((void)0, *__atomic_exchange_ptr) __atomic_exchange_val = (VAL); \
__typeof__ ((void)0, *__atomic_exchange_ptr) __atomic_exchange_tmp; \
__atomic_exchange (__atomic_exchange_ptr, &__atomic_exchange_val, \
&__atomic_exchange_tmp, (MO)); \
__atomic_exchange_tmp; \
})
#define atomic_exchange(PTR, VAL) \
atomic_exchange_explicit (PTR, VAL, __ATOMIC_SEQ_CST)
#define atomic_compare_exchange_strong_explicit(PTR, VAL, DES, SUC, FAIL) \
__extension__ \
({ \
__auto_type __atomic_compare_exchange_ptr = (PTR); \
__typeof__ ((void)0, *__atomic_compare_exchange_ptr) __atomic_compare_exchange_tmp \
= (DES); \
__atomic_compare_exchange (__atomic_compare_exchange_ptr, (VAL), \
&__atomic_compare_exchange_tmp, 0, \
(SUC), (FAIL)); \
})
#define atomic_compare_exchange_strong(PTR, VAL, DES) \
atomic_compare_exchange_strong_explicit (PTR, VAL, DES, __ATOMIC_SEQ_CST, \
__ATOMIC_SEQ_CST)
#define atomic_compare_exchange_weak_explicit(PTR, VAL, DES, SUC, FAIL) \
__extension__ \
({ \
__auto_type __atomic_compare_exchange_ptr = (PTR); \
__typeof__ ((void)0, *__atomic_compare_exchange_ptr) __atomic_compare_exchange_tmp \
= (DES); \
__atomic_compare_exchange (__atomic_compare_exchange_ptr, (VAL), \
&__atomic_compare_exchange_tmp, 1, \
(SUC), (FAIL)); \
})
#define atomic_compare_exchange_weak(PTR, VAL, DES) \
atomic_compare_exchange_weak_explicit (PTR, VAL, DES, __ATOMIC_SEQ_CST, \
__ATOMIC_SEQ_CST)
#define atomic_fetch_add(PTR, VAL) __atomic_fetch_add ((PTR), (VAL), \
__ATOMIC_SEQ_CST)
#define atomic_fetch_add_explicit(PTR, VAL, MO) \
__atomic_fetch_add ((PTR), (VAL), (MO))
#define atomic_fetch_sub(PTR, VAL) __atomic_fetch_sub ((PTR), (VAL), \
__ATOMIC_SEQ_CST)
#define atomic_fetch_sub_explicit(PTR, VAL, MO) \
__atomic_fetch_sub ((PTR), (VAL), (MO))
#define atomic_fetch_or(PTR, VAL) __atomic_fetch_or ((PTR), (VAL), \
__ATOMIC_SEQ_CST)
#define atomic_fetch_or_explicit(PTR, VAL, MO) \
__atomic_fetch_or ((PTR), (VAL), (MO))
#define atomic_fetch_xor(PTR, VAL) __atomic_fetch_xor ((PTR), (VAL), \
__ATOMIC_SEQ_CST)
#define atomic_fetch_xor_explicit(PTR, VAL, MO) \
__atomic_fetch_xor ((PTR), (VAL), (MO))
#define atomic_fetch_and(PTR, VAL) __atomic_fetch_and ((PTR), (VAL), \
__ATOMIC_SEQ_CST)
#define atomic_fetch_and_explicit(PTR, VAL, MO) \
__atomic_fetch_and ((PTR), (VAL), (MO))
typedef _Atomic struct
{
#if __GCC_ATOMIC_TEST_AND_SET_TRUEVAL == 1
_Bool __val;
#else
unsigned char __val;
#endif
} atomic_flag;
#define ATOMIC_FLAG_INIT { 0 }
extern _Bool atomic_flag_test_and_set (volatile atomic_flag *);
#define atomic_flag_test_and_set(PTR) \
__atomic_test_and_set ((PTR), __ATOMIC_SEQ_CST)
extern _Bool atomic_flag_test_and_set_explicit (volatile atomic_flag *,
memory_order);
#define atomic_flag_test_and_set_explicit(PTR, MO) \
__atomic_test_and_set ((PTR), (MO))
extern void atomic_flag_clear (volatile atomic_flag *);
#define atomic_flag_clear(PTR) __atomic_clear ((PTR), __ATOMIC_SEQ_CST)
extern void atomic_flag_clear_explicit (volatile atomic_flag *, memory_order);
#define atomic_flag_clear_explicit(PTR, MO) __atomic_clear ((PTR), (MO))
#endif /* _STDATOMIC_H */
-18
View File
@@ -1,18 +0,0 @@
#ifndef _STDBOOL_H
#define _STDBOOL_H
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#else /* __cplusplus */
#if __cplusplus < 201103L
#define bool bool
#define false false
#define true true
#endif /*__cplusplus < 201103L*/
#endif /* __cplusplus */
#define __bool_true_false_are_defined 1
#endif /* _STDBOOL_H */
-370
View File
@@ -1,370 +0,0 @@
/* Copyright (C) 2008-2018 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C Standard: 7.18 Integer types <stdint.h>
*/
#ifndef _STDINT_H
#define _STDINT_H
/* 7.8.1.1 Exact-width integer types */
#ifdef __INT8_TYPE__
typedef __INT8_TYPE__ int8_t;
#endif
#ifdef __INT16_TYPE__
typedef __INT16_TYPE__ int16_t;
#endif
#ifdef __INT32_TYPE__
typedef __INT32_TYPE__ int32_t;
#endif
#ifdef __INT64_TYPE__
typedef __INT64_TYPE__ int64_t;
#endif
#ifdef __UINT8_TYPE__
typedef __UINT8_TYPE__ uint8_t;
typedef __UINT8_TYPE__ u_int8_t;
#endif
#ifdef __UINT16_TYPE__
typedef __UINT16_TYPE__ uint16_t;
typedef __UINT16_TYPE__ u_int16_t;
#endif
#include <bits/uint32-t.h> // for uint32_t
#ifdef __UINT64_TYPE__
typedef __UINT64_TYPE__ uint64_t;
typedef __UINT64_TYPE__ u_int64_t;
// Required by openlibm
typedef __UINT64_TYPE__ __uint64_t;
#endif
/* 7.8.1.2 Minimum-width integer types */
typedef __INT_LEAST8_TYPE__ int_least8_t;
typedef __INT_LEAST16_TYPE__ int_least16_t;
typedef __INT_LEAST32_TYPE__ int_least32_t;
typedef __INT_LEAST64_TYPE__ int_least64_t;
typedef __UINT_LEAST8_TYPE__ uint_least8_t;
typedef __UINT_LEAST16_TYPE__ uint_least16_t;
typedef __UINT_LEAST32_TYPE__ uint_least32_t;
typedef __UINT_LEAST64_TYPE__ uint_least64_t;
/* 7.8.1.3 Fastest minimum-width integer types */
typedef __INT_FAST8_TYPE__ int_fast8_t;
typedef __INT_FAST16_TYPE__ int_fast16_t;
typedef __INT_FAST32_TYPE__ int_fast32_t;
typedef __INT_FAST64_TYPE__ int_fast64_t;
typedef __UINT_FAST8_TYPE__ uint_fast8_t;
typedef __UINT_FAST16_TYPE__ uint_fast16_t;
typedef __UINT_FAST32_TYPE__ uint_fast32_t;
typedef __UINT_FAST64_TYPE__ uint_fast64_t;
/* 7.8.1.4 Integer types capable of holding object pointers */
#include <bits/intptr-t.h> // for intptr_t
#ifdef __UINTPTR_TYPE__
typedef __UINTPTR_TYPE__ uintptr_t;
#endif
/* 7.8.1.5 Greatest-width integer types */
typedef __INTMAX_TYPE__ intmax_t;
typedef __UINTMAX_TYPE__ uintmax_t;
#if (!defined __cplusplus || __cplusplus >= 201103L \
|| defined __STDC_LIMIT_MACROS)
/* 7.18.2 Limits of specified-width integer types */
#ifdef __INT8_MAX__
# undef INT8_MAX
# define INT8_MAX __INT8_MAX__
# undef INT8_MIN
# define INT8_MIN (-INT8_MAX - 1)
#endif
#ifdef __UINT8_MAX__
# undef UINT8_MAX
# define UINT8_MAX __UINT8_MAX__
#endif
#ifdef __INT16_MAX__
# undef INT16_MAX
# define INT16_MAX __INT16_MAX__
# undef INT16_MIN
# define INT16_MIN (-INT16_MAX - 1)
#endif
#ifdef __UINT16_MAX__
# undef UINT16_MAX
# define UINT16_MAX __UINT16_MAX__
#endif
#ifdef __INT32_MAX__
# undef INT32_MAX
# define INT32_MAX __INT32_MAX__
# undef INT32_MIN
# define INT32_MIN (-INT32_MAX - 1)
#endif
#ifdef __UINT32_MAX__
# undef UINT32_MAX
# define UINT32_MAX __UINT32_MAX__
#endif
#ifdef __INT64_MAX__
# undef INT64_MAX
# define INT64_MAX __INT64_MAX__
# undef INT64_MIN
# define INT64_MIN (-INT64_MAX - 1)
#endif
#ifdef __UINT64_MAX__
# undef UINT64_MAX
# define UINT64_MAX __UINT64_MAX__
#endif
#undef INT_LEAST8_MAX
#define INT_LEAST8_MAX __INT_LEAST8_MAX__
#undef INT_LEAST8_MIN
#define INT_LEAST8_MIN (-INT_LEAST8_MAX - 1)
#undef UINT_LEAST8_MAX
#define UINT_LEAST8_MAX __UINT_LEAST8_MAX__
#undef INT_LEAST16_MAX
#define INT_LEAST16_MAX __INT_LEAST16_MAX__
#undef INT_LEAST16_MIN
#define INT_LEAST16_MIN (-INT_LEAST16_MAX - 1)
#undef UINT_LEAST16_MAX
#define UINT_LEAST16_MAX __UINT_LEAST16_MAX__
#undef INT_LEAST32_MAX
#define INT_LEAST32_MAX __INT_LEAST32_MAX__
#undef INT_LEAST32_MIN
#define INT_LEAST32_MIN (-INT_LEAST32_MAX - 1)
#undef UINT_LEAST32_MAX
#define UINT_LEAST32_MAX __UINT_LEAST32_MAX__
#undef INT_LEAST64_MAX
#define INT_LEAST64_MAX __INT_LEAST64_MAX__
#undef INT_LEAST64_MIN
#define INT_LEAST64_MIN (-INT_LEAST64_MAX - 1)
#undef UINT_LEAST64_MAX
#define UINT_LEAST64_MAX __UINT_LEAST64_MAX__
#undef INT_FAST8_MAX
#define INT_FAST8_MAX __INT_FAST8_MAX__
#undef INT_FAST8_MIN
#define INT_FAST8_MIN (-INT_FAST8_MAX - 1)
#undef UINT_FAST8_MAX
#define UINT_FAST8_MAX __UINT_FAST8_MAX__
#undef INT_FAST16_MAX
#define INT_FAST16_MAX __INT_FAST16_MAX__
#undef INT_FAST16_MIN
#define INT_FAST16_MIN (-INT_FAST16_MAX - 1)
#undef UINT_FAST16_MAX
#define UINT_FAST16_MAX __UINT_FAST16_MAX__
#undef INT_FAST32_MAX
#define INT_FAST32_MAX __INT_FAST32_MAX__
#undef INT_FAST32_MIN
#define INT_FAST32_MIN (-INT_FAST32_MAX - 1)
#undef UINT_FAST32_MAX
#define UINT_FAST32_MAX __UINT_FAST32_MAX__
#undef INT_FAST64_MAX
#define INT_FAST64_MAX __INT_FAST64_MAX__
#undef INT_FAST64_MIN
#define INT_FAST64_MIN (-INT_FAST64_MAX - 1)
#undef UINT_FAST64_MAX
#define UINT_FAST64_MAX __UINT_FAST64_MAX__
#ifdef __INTPTR_MAX__
# undef INTPTR_MAX
# define INTPTR_MAX __INTPTR_MAX__
# undef INTPTR_MIN
# define INTPTR_MIN (-INTPTR_MAX - 1)
#endif
#ifdef __UINTPTR_MAX__
# undef UINTPTR_MAX
# define UINTPTR_MAX __UINTPTR_MAX__
#endif
#undef INTMAX_MAX
#define INTMAX_MAX __INTMAX_MAX__
#undef INTMAX_MIN
#define INTMAX_MIN (-INTMAX_MAX - 1)
#undef UINTMAX_MAX
#define UINTMAX_MAX __UINTMAX_MAX__
/* 7.18.3 Limits of other integer types */
#undef PTRDIFF_MAX
#define PTRDIFF_MAX __PTRDIFF_MAX__
#undef PTRDIFF_MIN
#define PTRDIFF_MIN (-PTRDIFF_MAX - 1)
#undef SIG_ATOMIC_MAX
#define SIG_ATOMIC_MAX __SIG_ATOMIC_MAX__
#undef SIG_ATOMIC_MIN
#define SIG_ATOMIC_MIN __SIG_ATOMIC_MIN__
#undef SIZE_MAX
#define SIZE_MAX __SIZE_MAX__
#undef WCHAR_MAX
#define WCHAR_MAX __WCHAR_MAX__
#undef WCHAR_MIN
#define WCHAR_MIN __WCHAR_MIN__
#undef WINT_MAX
#define WINT_MAX __WINT_MAX__
#undef WINT_MIN
#define WINT_MIN __WINT_MIN__
#endif /* (!defined __cplusplus || __cplusplus >= 201103L
|| defined __STDC_LIMIT_MACROS) */
#if (!defined __cplusplus || __cplusplus >= 201103L \
|| defined __STDC_CONSTANT_MACROS)
#undef INT8_C
#define INT8_C(c) __INT8_C(c)
#undef INT16_C
#define INT16_C(c) __INT16_C(c)
#undef INT32_C
#define INT32_C(c) __INT32_C(c)
#undef INT64_C
#define INT64_C(c) __INT64_C(c)
#undef UINT8_C
#define UINT8_C(c) __UINT8_C(c)
#undef UINT16_C
#define UINT16_C(c) __UINT16_C(c)
#undef UINT32_C
#define UINT32_C(c) __UINT32_C(c)
#undef UINT64_C
#define UINT64_C(c) __UINT64_C(c)
#undef INTMAX_C
#define INTMAX_C(c) __INTMAX_C(c)
#undef UINTMAX_C
#define UINTMAX_C(c) __UINTMAX_C(c)
#endif /* (!defined __cplusplus || __cplusplus >= 201103L
|| defined __STDC_CONSTANT_MACROS) */
#ifdef __STDC_WANT_IEC_60559_BFP_EXT__
/* TS 18661-1 widths of integer types. */
#ifdef __INT8_TYPE__
# undef INT8_WIDTH
# define INT8_WIDTH 8
#endif
#ifdef __UINT8_TYPE__
# undef UINT8_WIDTH
# define UINT8_WIDTH 8
#endif
#ifdef __INT16_TYPE__
# undef INT16_WIDTH
# define INT16_WIDTH 16
#endif
#ifdef __UINT16_TYPE__
# undef UINT16_WIDTH
# define UINT16_WIDTH 16
#endif
#ifdef __INT32_TYPE__
# undef INT32_WIDTH
# define INT32_WIDTH 32
#endif
#ifdef __UINT32_TYPE__
# undef UINT32_WIDTH
# define UINT32_WIDTH 32
#endif
#ifdef __INT64_TYPE__
# undef INT64_WIDTH
# define INT64_WIDTH 64
#endif
#ifdef __UINT64_TYPE__
# undef UINT64_WIDTH
# define UINT64_WIDTH 64
#endif
#undef INT_LEAST8_WIDTH
#define INT_LEAST8_WIDTH __INT_LEAST8_WIDTH__
#undef UINT_LEAST8_WIDTH
#define UINT_LEAST8_WIDTH __INT_LEAST8_WIDTH__
#undef INT_LEAST16_WIDTH
#define INT_LEAST16_WIDTH __INT_LEAST16_WIDTH__
#undef UINT_LEAST16_WIDTH
#define UINT_LEAST16_WIDTH __INT_LEAST16_WIDTH__
#undef INT_LEAST32_WIDTH
#define INT_LEAST32_WIDTH __INT_LEAST32_WIDTH__
#undef UINT_LEAST32_WIDTH
#define UINT_LEAST32_WIDTH __INT_LEAST32_WIDTH__
#undef INT_LEAST64_WIDTH
#define INT_LEAST64_WIDTH __INT_LEAST64_WIDTH__
#undef UINT_LEAST64_WIDTH
#define UINT_LEAST64_WIDTH __INT_LEAST64_WIDTH__
#undef INT_FAST8_WIDTH
#define INT_FAST8_WIDTH __INT_FAST8_WIDTH__
#undef UINT_FAST8_WIDTH
#define UINT_FAST8_WIDTH __INT_FAST8_WIDTH__
#undef INT_FAST16_WIDTH
#define INT_FAST16_WIDTH __INT_FAST16_WIDTH__
#undef UINT_FAST16_WIDTH
#define UINT_FAST16_WIDTH __INT_FAST16_WIDTH__
#undef INT_FAST32_WIDTH
#define INT_FAST32_WIDTH __INT_FAST32_WIDTH__
#undef UINT_FAST32_WIDTH
#define UINT_FAST32_WIDTH __INT_FAST32_WIDTH__
#undef INT_FAST64_WIDTH
#define INT_FAST64_WIDTH __INT_FAST64_WIDTH__
#undef UINT_FAST64_WIDTH
#define UINT_FAST64_WIDTH __INT_FAST64_WIDTH__
#ifdef __INTPTR_TYPE__
# undef INTPTR_WIDTH
# define INTPTR_WIDTH __INTPTR_WIDTH__
#endif
#ifdef __UINTPTR_TYPE__
# undef UINTPTR_WIDTH
# define UINTPTR_WIDTH __INTPTR_WIDTH__
#endif
#undef INTMAX_WIDTH
#define INTMAX_WIDTH __INTMAX_WIDTH__
#undef UINTMAX_WIDTH
#define UINTMAX_WIDTH __INTMAX_WIDTH__
#undef PTRDIFF_WIDTH
#define PTRDIFF_WIDTH __PTRDIFF_WIDTH__
#undef SIG_ATOMIC_WIDTH
#define SIG_ATOMIC_WIDTH __SIG_ATOMIC_WIDTH__
#undef SIZE_WIDTH
#define SIZE_WIDTH __SIZE_WIDTH__
#undef WCHAR_WIDTH
#define WCHAR_WIDTH __WCHAR_WIDTH__
#undef WINT_WIDTH
#define WINT_WIDTH __WINT_WIDTH__
#ifdef __ILP32__
#define SIZE_MAX UINT32_MAX
#else
#define SIZE_MAX UINT64_MAX
#endif
#endif
#endif /* _GCC_STDINT_H */
-22
View File
@@ -1,22 +0,0 @@
#ifndef _STDIO_EXT_H
#define _STDIO_EXT_H
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
size_t __freadahead(FILE *stream);
size_t __fpending(FILE *stream);
int __freadable(FILE *stream);
int __freading(FILE *stream);
void __fseterr(FILE *stream);
int __fwritable(FILE *stream);
int __fwriting(FILE *stream);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* _STDIO_EXT_H */
-19
View File
@@ -1,19 +0,0 @@
/* Spec:
* The <stdnoreturn.h> header shall define the macro noreturn which shall
* expand to _Noreturn */
#ifndef _STDNORETURN_H
#define _STDNORETURN_H
#ifndef __cplusplus
/* Borrowed from musl */
#if __STDC_VERSION__ >= 201112L
#elif defined(__GNUC__)
#define _Noreturn __attribute__((__noreturn__))
#else
#define _Noreturn
#endif
#define noreturn _Noreturn
#endif
#endif
-97
View File
@@ -1,97 +0,0 @@
#ifndef _SYS_IOCCOM_H
#define _SYS_IOCCOM_H
// Linux-compatible ioctl command encoding constants — supplements the
// base _IOC / _IO / _IOR / _IOW / _IOWR macros from <sys/ioctl.h> with
// the bitfield widths, masks, shifts, decoders, and IOC direction
// macros that Linux UAPI headers (DRM, V4L2, etc.) expect.
//
// DRM headers include <sys/ioccom.h> as the BSD-naming path for ioctl
// command encoding; relibc's <sys/ioctl.h> provides the basic macros
// but not these constants. This header unifies them so DRM and other
// Linux UAPI consumers build without a Mesa-side stub.
#include <sys/ioctl.h>
#ifndef _IOC_NRBITS
#define _IOC_NRBITS 8
#endif
#ifndef _IOC_TYPEBITS
#define _IOC_TYPEBITS 8
#endif
#ifndef _IOC_SIZEBITS
#define _IOC_SIZEBITS 14
#endif
#ifndef _IOC_DIRBITS
#define _IOC_DIRBITS 2
#endif
#ifndef _IOC_NRMASK
#define _IOC_NRMASK ((1 << _IOC_NRBITS) - 1)
#endif
#ifndef _IOC_TYPEMASK
#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS) - 1)
#endif
#ifndef _IOC_SIZEMASK
#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS) - 1)
#endif
#ifndef _IOC_DIRMASK
#define _IOC_DIRMASK ((1 << _IOC_DIRBITS) - 1)
#endif
#ifndef _IOC_NRSHIFT
#define _IOC_NRSHIFT 0
#endif
#ifndef _IOC_TYPESHIFT
#define _IOC_TYPESHIFT (_IOC_NRSHIFT + _IOC_NRBITS)
#endif
#ifndef _IOC_SIZESHIFT
#define _IOC_SIZESHIFT (_IOC_TYPESHIFT + _IOC_TYPEBITS)
#endif
#ifndef _IOC_DIRSHIFT
#define _IOC_DIRSHIFT (_IOC_SIZESHIFT + _IOC_SIZEBITS)
#endif
// _IOC_TYPECHECK wraps the ioctl size argument in a sizeof() for type
// safety. The musl/relibc _IOW / _IOR / _IOWR macros already call
// sizeof internally on the third argument; this macro is provided for
// callers that compose ioctl numbers directly (e.g. DRM).
#ifndef _IOC_TYPECHECK
#define _IOC_TYPECHECK(t) (sizeof(t))
#endif
// _IOC_DIR / _IOC_TYPE / _IOC_NR / _IOC_SIZE decode the fields of an
// ioctl number. Linux UAPI callers use these to inspect ioctls.
#ifndef _IOC_DIR
#define _IOC_DIR(nr) (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK)
#endif
#ifndef _IOC_TYPE
#define _IOC_TYPE(nr) (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK)
#endif
#ifndef _IOC_NR
#define _IOC_NR(nr) (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK)
#endif
#ifndef _IOC_SIZE
#define _IOC_SIZE(nr) (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK)
#endif
// IOC_IN / IOC_OUT / IOC_INOUT are the values stored in the direction
// field of an ioctl number when constructing one without _IO / _IOR /
// _IOW / _IOWR.
#ifndef IOC_IN
#define IOC_IN (_IOC_WRITE << _IOC_DIRSHIFT)
#endif
#ifndef IOC_OUT
#define IOC_OUT (_IOC_READ << _IOC_DIRSHIFT)
#endif
#ifndef IOC_INOUT
#define IOC_INOUT ((_IOC_WRITE | _IOC_READ) << _IOC_DIRSHIFT)
#endif
#ifndef IOCSIZE_MASK
#define IOCSIZE_MASK (_IOC_SIZEMASK << _IOC_SIZESHIFT)
#endif
#ifndef IOCSIZE_SHIFT
#define IOCSIZE_SHIFT (_IOC_SIZESHIFT)
#endif
#endif /* _SYS_IOCCOM_H */
-36
View File
@@ -1,36 +0,0 @@
#ifndef _SYS_PARAM_H
#define _SYS_PARAM_H
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#define __bitop(array, index, op) ((array)[(index) / 8] op (1 << (index) % 8))
#define setbit(array, index) __bitop(array, index, |=)
#define clrbit(array, index) __bitop(array, index, &= ~)
#define isset(array, index) __bitop(array, index, &)
#define isclr(array, index) !isset(array, index)
#define howmany(bits, size) (((bits) + (size) - 1) / (size))
#define roundup(bits, size) (howmany(bits, size) * (size))
#define powerof2(n) !(((n) - 1) & (n))
// Shamelessly copied from musl.
// Tweak as needed.
#define MAXSYMLINKS 20
#define MAXHOSTNAMELEN 64
#define MAXNAMLEN 255
#define MAXPATHLEN 4096
#define NBBY 8
#define NGROUPS 32
#define CANBSIZ 255
#define NOFILE 256
#define NCARGS 131072
#define DEV_BSIZE 512
#define NOGROUP (-1)
#include <sys/resource.h>
#include <limits.h>
#include <machine/endian.h>
#endif
-1
View File
@@ -1 +0,0 @@
#include <poll.h>
-846
View File
@@ -1,846 +0,0 @@
/* $NetBSD: queue.h,v 1.70 2015/11/02 15:21:23 christos Exp $ */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
*/
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
/*
* This file defines five types of data structures: singly-linked lists,
* lists, simple queues, tail queues, and circular queues.
*
* A singly-linked list is headed by a single forward pointer. The
* elements are singly linked for minimum space and pointer manipulation
* overhead at the expense of O(n) removal for arbitrary elements. New
* elements can be added to the list after an existing element or at the
* head of the list. Elements being removed from the head of the list
* should use the explicit macro for this purpose for optimum
* efficiency. A singly-linked list may only be traversed in the forward
* direction. Singly-linked lists are ideal for applications with large
* datasets and few or no removals or for implementing a LIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* A simple queue is headed by a pair of pointers, one the head of the
* list and the other to the tail of the list. The elements are singly
* linked to save space, so elements can only be removed from the
* head of the list. New elements can be added to the list after
* an existing element, at the head of the list, or at the end of the
* list. A simple queue may only be traversed in the forward direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* A circle queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the list.
* A circle queue may be traversed in either direction, but has a more
* complex end of list detection.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
/*
* Include the definition of NULL only on NetBSD because sys/null.h
* is not available elsewhere. This conditional makes the header
* portable and it can simply be dropped verbatim into any system.
* The caveat is that on other systems some other header
* must provide NULL before the macros can be used.
*/
#ifdef __NetBSD__
#include <sys/null.h>
#endif
#if defined(QUEUEDEBUG)
# if defined(_KERNEL)
# define QUEUEDEBUG_ABORT(...) panic(__VA_ARGS__)
# else
# include <err.h>
# define QUEUEDEBUG_ABORT(...) err(1, __VA_ARGS__)
# endif
#endif
/*
* Singly-linked List definitions.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define SLIST_HEAD_INITIALIZER(head) \
{ NULL }
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
/*
* Singly-linked List access methods.
*/
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_END(head) NULL
#define SLIST_EMPTY(head) ((head)->slh_first == NULL)
#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
#define SLIST_FOREACH(var, head, field) \
for((var) = (head)->slh_first; \
(var) != SLIST_END(head); \
(var) = (var)->field.sle_next)
#define SLIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = SLIST_FIRST((head)); \
(var) != SLIST_END(head) && \
((tvar) = SLIST_NEXT((var), field), 1); \
(var) = (tvar))
/*
* Singly-linked List functions.
*/
#define SLIST_INIT(head) do { \
(head)->slh_first = SLIST_END(head); \
} while (/*CONSTCOND*/0)
#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
(elm)->field.sle_next = (slistelm)->field.sle_next; \
(slistelm)->field.sle_next = (elm); \
} while (/*CONSTCOND*/0)
#define SLIST_INSERT_HEAD(head, elm, field) do { \
(elm)->field.sle_next = (head)->slh_first; \
(head)->slh_first = (elm); \
} while (/*CONSTCOND*/0)
#define SLIST_REMOVE_AFTER(slistelm, field) do { \
(slistelm)->field.sle_next = \
SLIST_NEXT(SLIST_NEXT((slistelm), field), field); \
} while (/*CONSTCOND*/0)
#define SLIST_REMOVE_HEAD(head, field) do { \
(head)->slh_first = (head)->slh_first->field.sle_next; \
} while (/*CONSTCOND*/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 (/*CONSTCOND*/0)
/*
* List definitions.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#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 */ \
}
/*
* List access methods.
*/
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_END(head) NULL
#define LIST_EMPTY(head) ((head)->lh_first == LIST_END(head))
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_FOREACH(var, head, field) \
for ((var) = ((head)->lh_first); \
(var) != LIST_END(head); \
(var) = ((var)->field.le_next))
#define LIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = LIST_FIRST((head)); \
(var) != LIST_END(head) && \
((tvar) = LIST_NEXT((var), field), 1); \
(var) = (tvar))
#define LIST_MOVE(head1, head2) do { \
LIST_INIT((head2)); \
if (!LIST_EMPTY((head1))) { \
(head2)->lh_first = (head1)->lh_first; \
LIST_INIT((head1)); \
} \
} while (/*CONSTCOND*/0)
/*
* List functions.
*/
#if defined(QUEUEDEBUG)
#define QUEUEDEBUG_LIST_INSERT_HEAD(head, elm, field) \
if ((head)->lh_first && \
(head)->lh_first->field.le_prev != &(head)->lh_first) \
QUEUEDEBUG_ABORT("LIST_INSERT_HEAD %p %s:%d", (head), \
__FILE__, __LINE__);
#define QUEUEDEBUG_LIST_OP(elm, field) \
if ((elm)->field.le_next && \
(elm)->field.le_next->field.le_prev != \
&(elm)->field.le_next) \
QUEUEDEBUG_ABORT("LIST_* forw %p %s:%d", (elm), \
__FILE__, __LINE__); \
if (*(elm)->field.le_prev != (elm)) \
QUEUEDEBUG_ABORT("LIST_* back %p %s:%d", (elm), \
__FILE__, __LINE__);
#define QUEUEDEBUG_LIST_POSTREMOVE(elm, field) \
(elm)->field.le_next = (void *)1L; \
(elm)->field.le_prev = (void *)1L;
#else
#define QUEUEDEBUG_LIST_INSERT_HEAD(head, elm, field)
#define QUEUEDEBUG_LIST_OP(elm, field)
#define QUEUEDEBUG_LIST_POSTREMOVE(elm, field)
#endif
#define LIST_INIT(head) do { \
(head)->lh_first = LIST_END(head); \
} while (/*CONSTCOND*/0)
#define LIST_INSERT_AFTER(listelm, elm, field) do { \
QUEUEDEBUG_LIST_OP((listelm), field) \
if (((elm)->field.le_next = (listelm)->field.le_next) != \
LIST_END(head)) \
(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 (/*CONSTCOND*/0)
#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
QUEUEDEBUG_LIST_OP((listelm), field) \
(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 (/*CONSTCOND*/0)
#define LIST_INSERT_HEAD(head, elm, field) do { \
QUEUEDEBUG_LIST_INSERT_HEAD((head), (elm), field) \
if (((elm)->field.le_next = (head)->lh_first) != LIST_END(head))\
(head)->lh_first->field.le_prev = &(elm)->field.le_next;\
(head)->lh_first = (elm); \
(elm)->field.le_prev = &(head)->lh_first; \
} while (/*CONSTCOND*/0)
#define LIST_REMOVE(elm, field) do { \
QUEUEDEBUG_LIST_OP((elm), field) \
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; \
QUEUEDEBUG_LIST_POSTREMOVE((elm), field) \
} while (/*CONSTCOND*/0)
#define LIST_REPLACE(elm, elm2, field) do { \
if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \
(elm2)->field.le_next->field.le_prev = \
&(elm2)->field.le_next; \
(elm2)->field.le_prev = (elm)->field.le_prev; \
*(elm2)->field.le_prev = (elm2); \
QUEUEDEBUG_LIST_POSTREMOVE((elm), field) \
} while (/*CONSTCOND*/0)
/*
* 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_INITIALIZER(head) \
{ NULL, &(head).sqh_first }
#define SIMPLEQ_ENTRY(type) \
struct { \
struct type *sqe_next; /* next element */ \
}
/*
* Simple queue access methods.
*/
#define SIMPLEQ_FIRST(head) ((head)->sqh_first)
#define SIMPLEQ_END(head) NULL
#define SIMPLEQ_EMPTY(head) ((head)->sqh_first == SIMPLEQ_END(head))
#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next)
#define SIMPLEQ_FOREACH(var, head, field) \
for ((var) = ((head)->sqh_first); \
(var) != SIMPLEQ_END(head); \
(var) = ((var)->field.sqe_next))
#define SIMPLEQ_FOREACH_SAFE(var, head, field, next) \
for ((var) = ((head)->sqh_first); \
(var) != SIMPLEQ_END(head) && \
((next = ((var)->field.sqe_next)), 1); \
(var) = (next))
/*
* Simple queue functions.
*/
#define SIMPLEQ_INIT(head) do { \
(head)->sqh_first = NULL; \
(head)->sqh_last = &(head)->sqh_first; \
} while (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/0)
#define SIMPLEQ_REMOVE_AFTER(head, elm, field) do { \
if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \
== NULL) \
(head)->sqh_last = &(elm)->field.sqe_next; \
} while (/*CONSTCOND*/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 (/*CONSTCOND*/0)
#define SIMPLEQ_CONCAT(head1, head2) do { \
if (!SIMPLEQ_EMPTY((head2))) { \
*(head1)->sqh_last = (head2)->sqh_first; \
(head1)->sqh_last = (head2)->sqh_last; \
SIMPLEQ_INIT((head2)); \
} \
} while (/*CONSTCOND*/0)
#define SIMPLEQ_LAST(head, type, field) \
(SIMPLEQ_EMPTY((head)) ? \
NULL : \
((struct type *)(void *) \
((char *)((head)->sqh_last) - offsetof(struct type, field))))
/*
* 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) \
{ TAILQ_END(head), &(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 access methods.
*/
#define TAILQ_FIRST(head) ((head)->tqh_first)
#define TAILQ_END(head) (NULL)
#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define TAILQ_LAST(head, headname) \
(*(((struct headname *)(void *)((head)->tqh_last))->tqh_last))
#define TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)(void *)((elm)->field.tqe_prev))->tqh_last))
#define TAILQ_EMPTY(head) (TAILQ_FIRST(head) == TAILQ_END(head))
#define TAILQ_FOREACH(var, head, field) \
for ((var) = ((head)->tqh_first); \
(var) != TAILQ_END(head); \
(var) = ((var)->field.tqe_next))
#define TAILQ_FOREACH_SAFE(var, head, field, next) \
for ((var) = ((head)->tqh_first); \
(var) != TAILQ_END(head) && \
((next) = TAILQ_NEXT(var, field), 1); (var) = (next))
#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \
for ((var) = TAILQ_LAST((head), headname); \
(var) != TAILQ_END(head); \
(var) = TAILQ_PREV((var), headname, field))
#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, prev) \
for ((var) = TAILQ_LAST((head), headname); \
(var) != TAILQ_END(head) && \
((prev) = TAILQ_PREV((var), headname, field), 1); (var) = (prev))
/*
* Tail queue functions.
*/
#if defined(QUEUEDEBUG)
#define QUEUEDEBUG_TAILQ_INSERT_HEAD(head, elm, field) \
if ((head)->tqh_first && \
(head)->tqh_first->field.tqe_prev != &(head)->tqh_first) \
QUEUEDEBUG_ABORT("TAILQ_INSERT_HEAD %p %s:%d", (head), \
__FILE__, __LINE__);
#define QUEUEDEBUG_TAILQ_INSERT_TAIL(head, elm, field) \
if (*(head)->tqh_last != NULL) \
QUEUEDEBUG_ABORT("TAILQ_INSERT_TAIL %p %s:%d", (head), \
__FILE__, __LINE__);
#define QUEUEDEBUG_TAILQ_OP(elm, field) \
if ((elm)->field.tqe_next && \
(elm)->field.tqe_next->field.tqe_prev != \
&(elm)->field.tqe_next) \
QUEUEDEBUG_ABORT("TAILQ_* forw %p %s:%d", (elm), \
__FILE__, __LINE__); \
if (*(elm)->field.tqe_prev != (elm)) \
QUEUEDEBUG_ABORT("TAILQ_* back %p %s:%d", (elm), \
__FILE__, __LINE__);
#define QUEUEDEBUG_TAILQ_PREREMOVE(head, elm, field) \
if ((elm)->field.tqe_next == NULL && \
(head)->tqh_last != &(elm)->field.tqe_next) \
QUEUEDEBUG_ABORT("TAILQ_PREREMOVE head %p elm %p %s:%d",\
(head), (elm), __FILE__, __LINE__);
#define QUEUEDEBUG_TAILQ_POSTREMOVE(elm, field) \
(elm)->field.tqe_next = (void *)1L; \
(elm)->field.tqe_prev = (void *)1L;
#else
#define QUEUEDEBUG_TAILQ_INSERT_HEAD(head, elm, field)
#define QUEUEDEBUG_TAILQ_INSERT_TAIL(head, elm, field)
#define QUEUEDEBUG_TAILQ_OP(elm, field)
#define QUEUEDEBUG_TAILQ_PREREMOVE(head, elm, field)
#define QUEUEDEBUG_TAILQ_POSTREMOVE(elm, field)
#endif
#define TAILQ_INIT(head) do { \
(head)->tqh_first = TAILQ_END(head); \
(head)->tqh_last = &(head)->tqh_first; \
} while (/*CONSTCOND*/0)
#define TAILQ_INSERT_HEAD(head, elm, field) do { \
QUEUEDEBUG_TAILQ_INSERT_HEAD((head), (elm), field) \
if (((elm)->field.tqe_next = (head)->tqh_first) != TAILQ_END(head))\
(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 (/*CONSTCOND*/0)
#define TAILQ_INSERT_TAIL(head, elm, field) do { \
QUEUEDEBUG_TAILQ_INSERT_TAIL((head), (elm), field) \
(elm)->field.tqe_next = TAILQ_END(head); \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &(elm)->field.tqe_next; \
} while (/*CONSTCOND*/0)
#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
QUEUEDEBUG_TAILQ_OP((listelm), field) \
if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != \
TAILQ_END(head)) \
(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 (/*CONSTCOND*/0)
#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
QUEUEDEBUG_TAILQ_OP((listelm), field) \
(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 (/*CONSTCOND*/0)
#define TAILQ_REMOVE(head, elm, field) do { \
QUEUEDEBUG_TAILQ_PREREMOVE((head), (elm), field) \
QUEUEDEBUG_TAILQ_OP((elm), field) \
if (((elm)->field.tqe_next) != TAILQ_END(head)) \
(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; \
QUEUEDEBUG_TAILQ_POSTREMOVE((elm), field); \
} while (/*CONSTCOND*/0)
#define TAILQ_REPLACE(head, elm, elm2, field) do { \
if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != \
TAILQ_END(head)) \
(elm2)->field.tqe_next->field.tqe_prev = \
&(elm2)->field.tqe_next; \
else \
(head)->tqh_last = &(elm2)->field.tqe_next; \
(elm2)->field.tqe_prev = (elm)->field.tqe_prev; \
*(elm2)->field.tqe_prev = (elm2); \
QUEUEDEBUG_TAILQ_POSTREMOVE((elm), field); \
} while (/*CONSTCOND*/0)
#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 (/*CONSTCOND*/0)
/*
* 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_INITIALIZER(head) \
{ NULL, &(head).stqh_first }
#define STAILQ_ENTRY(type) \
struct { \
struct type *stqe_next; /* next element */ \
}
/*
* Singly-linked Tail queue access methods.
*/
#define STAILQ_FIRST(head) ((head)->stqh_first)
#define STAILQ_END(head) NULL
#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next)
#define STAILQ_EMPTY(head) (STAILQ_FIRST(head) == STAILQ_END(head))
/*
* Singly-linked Tail queue functions.
*/
#define STAILQ_INIT(head) do { \
(head)->stqh_first = NULL; \
(head)->stqh_last = &(head)->stqh_first; \
} while (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/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 (/*CONSTCOND*/0)
#define STAILQ_FOREACH(var, head, field) \
for ((var) = ((head)->stqh_first); \
(var); \
(var) = ((var)->field.stqe_next))
#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = STAILQ_FIRST((head)); \
(var) && ((tvar) = STAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#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 (/*CONSTCOND*/0)
#define STAILQ_LAST(head, type, field) \
(STAILQ_EMPTY((head)) ? \
NULL : \
((struct type *)(void *) \
((char *)((head)->stqh_last) - offsetof(struct type, field))))
#ifndef _KERNEL
/*
* Circular queue definitions. Do not use. We still keep the macros
* for compatibility but because of pointer aliasing issues their use
* is discouraged!
*/
/*
* __launder_type(): We use this ugly hack to work around the the compiler
* noticing that two types may not alias each other and elide tests in code.
* We hit this in the CIRCLEQ macros when comparing 'struct name *' and
* 'struct type *' (see CIRCLEQ_HEAD()). Modern compilers (such as GCC
* 4.8) declare these comparisons as always false, causing the code to
* not run as designed.
*
* This hack is only to be used for comparisons and thus can be fully const.
* Do not use for assignment.
*
* If we ever choose to change the ABI of the CIRCLEQ macros, we could fix
* this by changing the head/tail sentinal values, but see the note above
* this one.
*/
static __inline const void * __launder_type(const void *);
static __inline const void *
__launder_type(const void *__x)
{
__asm __volatile("" : "+r" (__x));
return __x;
}
#if defined(QUEUEDEBUG)
#define QUEUEDEBUG_CIRCLEQ_HEAD(head, field) \
if ((head)->cqh_first != CIRCLEQ_ENDC(head) && \
(head)->cqh_first->field.cqe_prev != CIRCLEQ_ENDC(head)) \
QUEUEDEBUG_ABORT("CIRCLEQ head forw %p %s:%d", (head), \
__FILE__, __LINE__); \
if ((head)->cqh_last != CIRCLEQ_ENDC(head) && \
(head)->cqh_last->field.cqe_next != CIRCLEQ_ENDC(head)) \
QUEUEDEBUG_ABORT("CIRCLEQ head back %p %s:%d", (head), \
__FILE__, __LINE__);
#define QUEUEDEBUG_CIRCLEQ_ELM(head, elm, field) \
if ((elm)->field.cqe_next == CIRCLEQ_ENDC(head)) { \
if ((head)->cqh_last != (elm)) \
QUEUEDEBUG_ABORT("CIRCLEQ elm last %p %s:%d", \
(elm), __FILE__, __LINE__); \
} else { \
if ((elm)->field.cqe_next->field.cqe_prev != (elm)) \
QUEUEDEBUG_ABORT("CIRCLEQ elm forw %p %s:%d", \
(elm), __FILE__, __LINE__); \
} \
if ((elm)->field.cqe_prev == CIRCLEQ_ENDC(head)) { \
if ((head)->cqh_first != (elm)) \
QUEUEDEBUG_ABORT("CIRCLEQ elm first %p %s:%d", \
(elm), __FILE__, __LINE__); \
} else { \
if ((elm)->field.cqe_prev->field.cqe_next != (elm)) \
QUEUEDEBUG_ABORT("CIRCLEQ elm prev %p %s:%d", \
(elm), __FILE__, __LINE__); \
}
#define QUEUEDEBUG_CIRCLEQ_POSTREMOVE(elm, field) \
(elm)->field.cqe_next = (void *)1L; \
(elm)->field.cqe_prev = (void *)1L;
#else
#define QUEUEDEBUG_CIRCLEQ_HEAD(head, field)
#define QUEUEDEBUG_CIRCLEQ_ELM(head, elm, field)
#define QUEUEDEBUG_CIRCLEQ_POSTREMOVE(elm, field)
#endif
#define CIRCLEQ_HEAD(name, type) \
struct name { \
struct type *cqh_first; /* first element */ \
struct type *cqh_last; /* last element */ \
}
#define CIRCLEQ_HEAD_INITIALIZER(head) \
{ CIRCLEQ_END(&head), CIRCLEQ_END(&head) }
#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 = CIRCLEQ_END(head); \
(head)->cqh_last = CIRCLEQ_END(head); \
} while (/*CONSTCOND*/0)
#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
QUEUEDEBUG_CIRCLEQ_HEAD((head), field) \
QUEUEDEBUG_CIRCLEQ_ELM((head), (listelm), field) \
(elm)->field.cqe_next = (listelm)->field.cqe_next; \
(elm)->field.cqe_prev = (listelm); \
if ((listelm)->field.cqe_next == CIRCLEQ_ENDC(head)) \
(head)->cqh_last = (elm); \
else \
(listelm)->field.cqe_next->field.cqe_prev = (elm); \
(listelm)->field.cqe_next = (elm); \
} while (/*CONSTCOND*/0)
#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \
QUEUEDEBUG_CIRCLEQ_HEAD((head), field) \
QUEUEDEBUG_CIRCLEQ_ELM((head), (listelm), field) \
(elm)->field.cqe_next = (listelm); \
(elm)->field.cqe_prev = (listelm)->field.cqe_prev; \
if ((listelm)->field.cqe_prev == CIRCLEQ_ENDC(head)) \
(head)->cqh_first = (elm); \
else \
(listelm)->field.cqe_prev->field.cqe_next = (elm); \
(listelm)->field.cqe_prev = (elm); \
} while (/*CONSTCOND*/0)
#define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \
QUEUEDEBUG_CIRCLEQ_HEAD((head), field) \
(elm)->field.cqe_next = (head)->cqh_first; \
(elm)->field.cqe_prev = CIRCLEQ_END(head); \
if ((head)->cqh_last == CIRCLEQ_ENDC(head)) \
(head)->cqh_last = (elm); \
else \
(head)->cqh_first->field.cqe_prev = (elm); \
(head)->cqh_first = (elm); \
} while (/*CONSTCOND*/0)
#define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \
QUEUEDEBUG_CIRCLEQ_HEAD((head), field) \
(elm)->field.cqe_next = CIRCLEQ_END(head); \
(elm)->field.cqe_prev = (head)->cqh_last; \
if ((head)->cqh_first == CIRCLEQ_ENDC(head)) \
(head)->cqh_first = (elm); \
else \
(head)->cqh_last->field.cqe_next = (elm); \
(head)->cqh_last = (elm); \
} while (/*CONSTCOND*/0)
#define CIRCLEQ_REMOVE(head, elm, field) do { \
QUEUEDEBUG_CIRCLEQ_HEAD((head), field) \
QUEUEDEBUG_CIRCLEQ_ELM((head), (elm), field) \
if ((elm)->field.cqe_next == CIRCLEQ_ENDC(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 == CIRCLEQ_ENDC(head)) \
(head)->cqh_first = (elm)->field.cqe_next; \
else \
(elm)->field.cqe_prev->field.cqe_next = \
(elm)->field.cqe_next; \
QUEUEDEBUG_CIRCLEQ_POSTREMOVE((elm), field) \
} while (/*CONSTCOND*/0)
#define CIRCLEQ_FOREACH(var, head, field) \
for ((var) = ((head)->cqh_first); \
(var) != CIRCLEQ_ENDC(head); \
(var) = ((var)->field.cqe_next))
#define CIRCLEQ_FOREACH_REVERSE(var, head, field) \
for ((var) = ((head)->cqh_last); \
(var) != CIRCLEQ_ENDC(head); \
(var) = ((var)->field.cqe_prev))
/*
* Circular queue access methods.
*/
#define CIRCLEQ_FIRST(head) ((head)->cqh_first)
#define CIRCLEQ_LAST(head) ((head)->cqh_last)
/* For comparisons */
#define CIRCLEQ_ENDC(head) (__launder_type(head))
/* For assignments */
#define CIRCLEQ_END(head) ((void *)(head))
#define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next)
#define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev)
#define CIRCLEQ_EMPTY(head) \
(CIRCLEQ_FIRST(head) == CIRCLEQ_ENDC(head))
#define CIRCLEQ_LOOP_NEXT(head, elm, field) \
(((elm)->field.cqe_next == CIRCLEQ_ENDC(head)) \
? ((head)->cqh_first) \
: (elm->field.cqe_next))
#define CIRCLEQ_LOOP_PREV(head, elm, field) \
(((elm)->field.cqe_prev == CIRCLEQ_ENDC(head)) \
? ((head)->cqh_last) \
: (elm->field.cqe_prev))
#endif /* !_KERNEL */
#endif /* !_SYS_QUEUE_H_ */
-22
View File
@@ -1,22 +0,0 @@
#ifndef _SYS_REDOX_H
#define _SYS_REDOX_H
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __redox__
ssize_t redox_fpath(int fd, void * buf, size_t count);
void * redox_physalloc(size_t size);
int redox_physfree(void * physical_address, size_t size);
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#endif
-16
View File
@@ -1,16 +0,0 @@
// From musl, license MIT
#ifndef _SYS_SYSMACROS_H
#define _SYS_SYSMACROS_H
#define major(x) \
((unsigned)( (((x)>>31>>1) & 0xfffff000) | (((x)>>8) & 0x00000fff) ))
#define minor(x) \
((unsigned)( (((x)>>12) & 0xffffff00) | ((x) & 0x000000ff) ))
#define makedev(x,y) ( \
(((x)&0xfffff000ULL) << 32) | \
(((x)&0x00000fffULL) << 8) | \
(((y)&0xffffff00ULL) << 12) | \
(((y)&0x000000ffULL)) )
#endif
-13
View File
@@ -1,13 +0,0 @@
#ifndef _SYS_USER_H
#define _SYS_USER_H
#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_AMD64)
#include <arch/x64/user.h>
#elif defined(__aarch64__)
#include <arch/aarch64/user.h>
#elif defined(__riscv) && __riscv_xlen==64
#include <arch/riscv64/user.h>
#else
#error "Unknown architecture"
#endif
#endif
-1
View File
@@ -1 +0,0 @@
#include <sys/syslog.h>
-12
View File
@@ -1,12 +0,0 @@
[package]
name = "ld_so"
version = "0.1.0"
authors = ["Jeremy Soller <jackpot51@gmail.com>"]
edition = "2024"
[lib]
name = "ld_so"
crate-type = ["staticlib"]
[lints]
workspace = true
-136
View File
@@ -1,136 +0,0 @@
#![no_std]
#![feature(linkage)]
#![deny(unsafe_op_in_unsafe_fn)]
use core::arch::global_asm;
#[cfg(target_arch = "aarch64")]
global_asm!(
"
.weak _DYNAMIC
.hidden _DYNAMIC
.global _start
_start:
mov x28, sp
// align stack to 16 bytes
and sp, x28, #0xfffffffffffffff0
adr x1, _start
mov x0, x28
adrp x2, _DYNAMIC
add x2, x2, #:lo12:_DYNAMIC
// ld_so_start(stack=x0, ld_entry=x1, dynamic=x2)
bl relibc_ld_so_start
// restore original stack, clear registers, and jump to the new start function
mov sp, x28
mov x1, xzr
mov x2, xzr
mov x3, xzr
mov x4, xzr
mov x5, xzr
mov x6, xzr
mov x7, xzr
mov x8, xzr
mov x9, xzr
mov x10, xzr
mov x11, xzr
mov x12, xzr
mov x13, xzr
mov x14, xzr
mov x15, xzr
mov x16, xzr
mov x17, xzr
mov x18, xzr
mov x19, xzr
mov x20, xzr
mov x21, xzr
mov x22, xzr
mov x23, xzr
mov x24, xzr
mov x25, xzr
mov x26, xzr
mov x27, xzr
mov x28, xzr
mov x29, xzr
mov x30, xzr
br x0
udf #0
"
);
#[cfg(target_arch = "x86")]
global_asm!(
"
.globl _start
_start:
push esp
call relibc_ld_so_start
pop esp
# TODO: x86
ud2
"
);
#[cfg(target_arch = "x86_64")]
global_asm!(
"
.weak _DYNAMIC
.hidden _DYNAMIC
.globl _start
_start:
lea rsi, [rip + _start]
# Save original stack and align stack to 16 bytes
mov rbp, rsp
and rsp, 0xfffffffffffffff0
# Call ld_so_start(stack=rdi, ld_entry=rsi, dynamic=rdx)
mov rdi, rbp
lea rdx, [rip + _DYNAMIC]
call relibc_ld_so_start
# Restore original stack, clear registers, and jump to new start function
mov rsp, rbp
xor rcx, rcx
xor rdx, rdx
xor rdi, rdi
xor rsi, rsi
xor r8, r8
xor r9, r9
xor r10, r10
xor r11, r11
fninit
jmp rax
ud2
"
);
#[cfg(target_arch = "riscv64")]
global_asm!(
"
.globl _start
_start:
mv a0, sp
call relibc_ld_so_start
unimp
"
);
#[unsafe(no_mangle)]
pub unsafe extern "C" fn main(_argc: isize, _argv: *const *const i8) -> usize {
// LD
0x1D
}
#[linkage = "weak"]
#[unsafe(no_mangle)]
extern "C" fn relibc_panic(_pi: &::core::panic::PanicInfo) -> ! {
loop {}
}
#[panic_handler]
#[linkage = "weak"]
pub unsafe fn rust_begin_unwind(pi: &::core::panic::PanicInfo) -> ! {
relibc_panic(pi)
}
Submodule openlibm deleted from f5ed774593
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "redox-ioctl"
authors = ["bjorn3 <bjorn3_gh@protonmail.com>"]
version = "0.1.0"
edition = "2024"
license = "MIT"
description = "Ioctl definitions and (de)serialization for Redox"
[dependencies]
drm-sys = "0.8.0"
redox_syscall = "0.9.0"
[features]
[lints]
workspace = true
-347
View File
@@ -1,347 +0,0 @@
use alloc::vec::Vec;
use core::{
cmp,
ffi::{c_char, c_int, c_uint},
iter, mem, slice,
};
pub use drm_sys::{
__kernel_size_t, DRM_PROP_NAME_LEN, drm_clip_rect, drm_get_cap, drm_mode_card_res,
drm_mode_closefb, drm_mode_connector_set_property, drm_mode_create_dumb, drm_mode_crtc,
drm_mode_crtc_page_flip_target, drm_mode_cursor, drm_mode_cursor2, drm_mode_destroy_dumb,
drm_mode_fb_cmd, drm_mode_fb_cmd2, drm_mode_fb_dirty_cmd, drm_mode_get_blob,
drm_mode_get_connector, drm_mode_get_encoder, drm_mode_get_plane, drm_mode_get_plane_res,
drm_mode_get_property, drm_mode_map_dumb, drm_mode_modeinfo, drm_mode_obj_get_properties,
drm_mode_property_enum, drm_mode_set_plane, drm_set_client_cap, drm_set_version, drm_unique,
drm_version,
};
pub const VERSION: u64 = 0;
define_ioctl_data! {
struct drm_version, DrmVersion {
version_major: c_int,
version_minor: c_int,
version_patchlevel: c_int,
name_len: __kernel_size_t,
name: *mut c_char [array<c_char, name_len>],
date_len: __kernel_size_t,
date: *mut c_char [array<c_char, date_len>],
desc_len: __kernel_size_t,
desc: *mut c_char [array<c_char, desc_len>],
}
}
pub const GET_UNIQUE: u64 = 0x01;
define_ioctl_data! {
struct drm_unique, DrmUnique {
unique_len: __kernel_size_t,
unique: *mut c_char [array<c_char, unique_len>],
}
}
pub const SET_VERSION: u64 = 0x07;
define_ioctl_data! {
struct drm_set_version, DrmSetVersion {
drm_di_major: c_int,
drm_di_minor: c_int,
drm_dd_major: c_int,
drm_dd_minor: c_int,
}
}
pub const GET_CAP: u64 = 0x0C;
pub use drm_sys::DRM_CAP_DUMB_BUFFER;
define_ioctl_data! {
struct drm_get_cap, DrmGetCap {
capability: u64,
value: u64,
}
}
pub const SET_CLIENT_CAP: u64 = 0x0D;
pub use drm_sys::DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT;
define_ioctl_data! {
struct drm_set_client_cap, DrmSetClientCap {
capability: u64,
value: u64,
}
}
pub const MODE_CARD_RES: u64 = 0xA0;
define_ioctl_data! {
struct drm_mode_card_res, DrmModeCardRes {
fb_id_ptr: u64 [array<u32, count_fbs>],
crtc_id_ptr: u64 [array<u32, count_crtcs>],
connector_id_ptr: u64 [array<u32, count_connectors>],
encoder_id_ptr: u64 [array<u32, count_encoders>],
count_fbs: u32,
count_crtcs: u32,
count_connectors: u32,
count_encoders: u32,
min_width: u32,
max_width: u32,
min_height: u32,
max_height: u32,
}
}
pub const MODE_GET_CRTC: u64 = 0xA1;
pub const MODE_SET_CRTC: u64 = 0xA2;
define_ioctl_data! {
struct drm_mode_crtc, DrmModeCrtc {
set_connectors_ptr: u64 [array<u32, count_connectors>],
count_connectors: u32,
crtc_id: u32,
fb_id: u32,
x: u32,
y: u32,
gamma_size: u32,
mode_valid: u32,
mode: drm_mode_modeinfo,
}
}
pub const MODE_CURSOR: u64 = 0xA3;
define_ioctl_data! {
struct drm_mode_cursor, DrmModeCursor {
flags: u32,
crtc_id: u32,
x: i32,
y:i32,
width:u32,
height:u32,
handle:u32,
}
}
pub const MODE_GET_ENCODER: u64 = 0xA6;
define_ioctl_data! {
struct drm_mode_get_encoder, DrmModeGetEncoder {
encoder_id: u32,
encoder_type: u32,
crtc_id: u32,
possible_crtcs: u32,
possible_clones: u32,
}
}
pub const MODE_GET_CONNECTOR: u64 = 0xA7;
define_ioctl_data! {
struct drm_mode_get_connector, DrmModeGetConnector {
encoders_ptr: u64 [array<u32, count_encoders>],
modes_ptr: u64 [array<drm_mode_modeinfo, count_modes>],
props_ptr: u64 [array<u32, count_props>],
prop_values_ptr: u64 [array<u64, count_props>],
count_modes: u32,
count_props: u32,
count_encoders: u32,
encoder_id: u32,
connector_id: u32,
connector_type: u32,
connector_type_id: u32,
connection: u32,
mm_width: u32,
mm_height: u32,
subpixel: u32,
pad: u32,
}
}
pub const MODE_GET_PROPERTY: u64 = 0xAA;
define_ioctl_data! {
struct drm_mode_get_property, DrmModeGetProperty {
values_ptr: u64 [array<u64, count_values>],
enum_blob_ptr: u64 [array<drm_mode_property_enum, count_enum_blobs>],
prop_id: u32,
flags: u32,
name: [c_char; DRM_PROP_NAME_LEN as usize],
count_values: u32,
count_enum_blobs: u32,
}
}
pub const MODE_SET_PROPERTY: u64 = 0xAB;
define_ioctl_data! {
struct drm_mode_connector_set_property, DrmModeConnectorSetProperty {
value: u64,
prop_id: u32,
connector_id: u32,
}
}
pub const MODE_GET_PROP_BLOB: u64 = 0xAC;
define_ioctl_data! {
struct drm_mode_get_blob, DrmModeGetBlob {
blob_id: u32,
length: u32,
data: u64 [array<u8, length>],
}
}
pub const MODE_GET_FB: u64 = 0xAD;
pub const MODE_ADD_FB: u64 = 0xAE;
define_ioctl_data! {
struct drm_mode_fb_cmd, DrmModeFbCmd {
fb_id: u32,
width: u32,
height: u32,
pitch: u32,
bpp: u32,
depth: u32,
handle: u32,
}
}
pub const MODE_RM_FB: u64 = 0xAF;
define_ioctl_data! {
struct standin_for_uint, StandinForUint {
inner: c_uint,
}
}
#[repr(transparent)]
#[allow(non_camel_case_types)]
pub struct standin_for_uint {
pub inner: c_uint,
}
pub const MODE_PAGE_FLIP: u64 = 0xB0;
define_ioctl_data! {
struct drm_mode_crtc_page_flip_target, DrmModeCrtcPageFlipTarget {
crtc_id: u32,
fb_id: u32,
flags: u32,
sequence: u32,
user_data: u64,
}
}
pub const MODE_DIRTYFB: u64 = 0xB1;
define_ioctl_data! {
struct drm_mode_fb_dirty_cmd, DrmModeFbDirtyCmd {
fb_id: u32,
flags: u32,
color: u32,
num_clips: u32,
clips_ptr: u64 [array<drm_clip_rect, num_clips>],
}
}
pub const MODE_CREATE_DUMB: u64 = 0xB2;
define_ioctl_data! {
struct drm_mode_create_dumb, DrmModeCreateDumb {
height: u32,
width: u32,
bpp: u32,
flags: u32,
handle: u32,
pitch: u32,
size: u64,
}
}
pub const MODE_MAP_DUMB: u64 = 0xB3;
define_ioctl_data! {
struct drm_mode_map_dumb, DrmModeMapDumb {
handle: u32,
pad: u32,
offset: u64,
}
}
pub const MODE_DESTROY_DUMB: u64 = 0xB4;
define_ioctl_data! {
struct drm_mode_destroy_dumb, DrmModeDestroyDumb {
handle: u32,
}
}
pub const MODE_GET_PLANE_RES: u64 = 0xB5;
define_ioctl_data! {
struct drm_mode_get_plane_res, DrmModeGetPlaneRes {
plane_id_ptr: u64 [array<u32, count_planes>],
count_planes: u32,
}
}
pub const MODE_GET_PLANE: u64 = 0xB6;
define_ioctl_data! {
struct drm_mode_get_plane, DrmModeGetPlane {
plane_id: u32,
crtc_id: u32,
fb_id: u32,
possible_crtcs: u32,
gamma_size: u32,
count_format_types: u32,
format_type_ptr: u64 [array<u32, count_format_types>],
}
}
pub const MODE_SET_PLANE: u64 = 0xB7;
define_ioctl_data! {
struct drm_mode_set_plane, DrmModeSetPlane {
plane_id: u32,
crtc_id: u32,
fb_id: u32,
flags: u32,
crtc_x: i32,
crtc_y: i32,
crtc_w: u32,
crtc_h: u32,
src_x: u32,
src_y: u32,
src_h: u32,
src_w: u32,
}
}
pub const MODE_ADD_FB2: u64 = 0xB8;
pub const MODE_OBJ_GET_PROPERTIES: u64 = 0xB9;
define_ioctl_data! {
struct drm_mode_obj_get_properties, DrmModeObjGetProperties {
props_ptr: u64 [array<u32, count_props>],
prop_values_ptr: u64 [array<u64, count_props>],
count_props: u32,
obj_id: u32,
obj_type: u32,
}
}
pub const MODE_CURSOR2: u64 = 0xBB;
define_ioctl_data! {
struct drm_mode_cursor2, DrmModeCursor2 {
flags: u32,
crtc_id: u32,
x: i32,
y: i32,
width: u32,
height: u32,
handle: u32,
hot_x: i32,
hot_y: i32,
}
}
pub const MODE_GET_FB2: u64 = 0xCE;
define_ioctl_data! {
struct drm_mode_fb_cmd2, DrmModeFbCmd2 {
fb_id: u32,
width: u32,
height: u32,
pixel_format: u32,
flags: u32,
handles: [u32; 4],
pitches: [u32; 4],
offsets: [u32; 4],
modifier: [u64; 4],
}
}
pub const MODE_CLOSE_FB: u64 = 0xD0;
define_ioctl_data! {
struct drm_mode_closefb, DrmModeClosefb {
fb_id: u32,
pad: u32,
}
}
-168
View File
@@ -1,168 +0,0 @@
use alloc::vec::Vec;
pub trait IoctlData {
unsafe fn write(&self) -> Vec<u8>;
unsafe fn read_from(&mut self, buf: &[u8]);
}
macro_rules! define_ioctl_data {
(struct $ioctl_ty:ident, $mem_ty:ident {
$($rest:tt)*
}) => {
define_ioctl_data!(
struct $ioctl_ty, $mem_ty { $($rest)* } => (), (), ()
);
};
(struct $ioctl_ty:ident, $mem_ty:ident {
$field:ident: $ty:ty,
$($rest:tt)*
} =>
($($ioctl_fields:tt)*),
($($counted_fields:tt)*),
($($noncounted_fields:tt)*)
) => {
define_ioctl_data!(
struct $ioctl_ty, $mem_ty { $($rest)* } =>
($($ioctl_fields)* $field: $ty,),
($($counted_fields)*),
($($noncounted_fields)* $field: $ty,)
);
};
(struct $ioctl_ty:ident, $mem_ty:ident {
$field:ident: $ty:ty [array<$el:ty, $counted_by:ident>],
$($rest:tt)*
} =>
($($ioctl_fields:tt)*),
($($counted_fields:tt)*),
($($noncounted_fields:tt)*)
) => {
define_ioctl_data!(
struct $ioctl_ty, $mem_ty { $($rest)* } =>
($($ioctl_fields)* $field: $ty,),
($($counted_fields)* $field: $ty [array<$el, $counted_by>],),
($($noncounted_fields)*)
);
};
(struct $ioctl_ty:ident, $mem_ty:ident {} =>
($($ioctl_field:ident: $ioctl_field_ty:ty,)*),
($($counted_field:ident: $counted_ty:ty [array<$el:ty, $counted_by:ident>],)*),
($($noncounted_field:ident: $noncounted_ty:ty,)*)
) => {
// FIXME check ioctl_ty doesn't have padding
const _: $ioctl_ty = $ioctl_ty {
$($ioctl_field: unsafe { mem::zeroed::<$ioctl_field_ty>() },)*
};
#[repr(C)]
pub struct ${concat(__, $mem_ty, Noncounted)} {
$($noncounted_field: $noncounted_ty,)*
}
pub struct $mem_ty<'a> {
noncounted_fields: &'a mut ${concat(__, $mem_ty, Noncounted)},
$($counted_field: &'a mut [$el],)*
}
impl $crate::ioctl_data::IoctlData for $ioctl_ty {
unsafe fn write(&self) -> Vec<u8> {
let noncounted_fields = ${concat(__, $mem_ty, Noncounted)} {
$($noncounted_field: self.$noncounted_field,)*
};
// FIXME use Vec::with_capacity
let mut data = Vec::<u8>::new();
data.extend_from_slice(&unsafe {
mem::transmute::<
${concat(__, $mem_ty, Noncounted)},
[u8; size_of::<${concat(__, $mem_ty, Noncounted)}>()],
>(noncounted_fields)
});
$(
let size = self.$counted_by as usize * size_of::<$el>();
if self.$counted_field as usize != 0 {
let $counted_field = unsafe {
slice::from_raw_parts(self.$counted_field as *const u8, size)
};
data.extend_from_slice(&$counted_field);
} else {
data.extend(iter::repeat(0u8).take(size));
};
)*
data
}
unsafe fn read_from(&mut self, mut buf: &[u8]) {
// FIXME be robust against malicious scheme implementations by returning an error
// when the buf is the wrong size
let noncounted_fields = buf.split_off(..size_of::<${concat(__, $mem_ty, Noncounted)}>()).unwrap();
$(
let size = self.$counted_by as usize * size_of::<$el>();
let $counted_field = buf.split_off(..size).unwrap();
if self.$counted_field as usize != 0 {
unsafe {
slice::from_raw_parts_mut(self.$counted_field as *mut u8, size).copy_from_slice($counted_field);
}
}
)*
assert!(buf.is_empty());
let noncounted_fields = unsafe { &*core::ptr::from_ref(noncounted_fields).cast::<${concat(__, $mem_ty, Noncounted)}>() };
$(self.$noncounted_field = noncounted_fields.$noncounted_field;)*
}
}
impl<'a> $mem_ty<'a> {
pub fn with(
mut buf: &'a mut [u8],
f: impl FnOnce($mem_ty<'a>) -> syscall::Result<usize>,
) -> syscall::Result<usize> {
let noncounted_fields = buf.split_off_mut(..size_of::<${concat(__, $mem_ty, Noncounted)}>())
.ok_or(syscall::Error::new(syscall::EINVAL))?;
let noncounted_fields = unsafe { &mut *core::ptr::from_mut(noncounted_fields).cast::<${concat(__, $mem_ty, Noncounted)}>() };
$(
let $counted_field = buf.split_off_mut(..noncounted_fields.$counted_by as usize * size_of::<$el>())
.ok_or(syscall::Error::new(syscall::EINVAL))?;
let $counted_field = unsafe {
slice::from_raw_parts_mut(core::ptr::from_mut($counted_field).cast::<$el>(), noncounted_fields.$counted_by as usize)
};
)*
if !buf.is_empty() {
return Err(syscall::Error::new(syscall::EINVAL));
}
f($mem_ty {
noncounted_fields,
$($counted_field,)*
})
}
$(
pub fn $noncounted_field(&self) -> $noncounted_ty {
self.noncounted_fields.$noncounted_field
}
/// Should not be called for fields used as array length
pub fn ${concat(set_, $noncounted_field)}(&mut self, data: $noncounted_ty) {
self.noncounted_fields.$noncounted_field = data;
}
)*
$(
pub fn $counted_field(&self) -> &[$el] {
self.$counted_field
}
pub fn ${concat(set_, $counted_field)}(&mut self, data: &[$el]) {
let copied_count = cmp::min(data.len(), self.$counted_field.len());
self.$counted_field[..copied_count].copy_from_slice(&data[..copied_count]);
self.noncounted_fields.$counted_by = data.len() as _;
}
)*
}
};
}
-11
View File
@@ -1,11 +0,0 @@
#![feature(macro_metavar_expr_concat)]
#![deny(unsafe_op_in_unsafe_fn)]
#![no_std]
extern crate alloc;
#[macro_use]
mod ioctl_data;
pub use ioctl_data::IoctlData;
pub mod drm;
-27
View File
@@ -1,27 +0,0 @@
[package]
name = "redox-rt"
authors = ["4lDO2 <4lDO2@protonmail.com>"]
version = "0.1.0"
edition = "2024"
license = "MIT"
description = "Libc-independent runtime for Redox"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bitflags.workspace = true
goblin = { version = "0.10", default-features = false, features = ["elf32", "elf64", "endian_fd"] }
plain.workspace = true
ioslice.workspace = true
redox_syscall.workspace = true
redox-path.workspace = true
redox_protocols.workspace = true
generic-rt = { path = "../generic-rt" }
[features]
proc = []
default = ["proc"]
[lints]
workspace = true
-492
View File
@@ -1,492 +0,0 @@
use core::{cell::SyncUnsafeCell, mem::offset_of, ptr::NonNull};
use syscall::{data::*, error::*};
use crate::{
Tcb,
proc::{FdGuard, FdGuardUpper, ForkArgs, fork_inner},
signal::{PosixStackt, RtSigarea, SigStack, inner_c},
};
use redox_protocols::protocol::{ProcCall, RtSigInfo};
use super::ForkScratchpad;
// Setup a stack starting from the very end of the address space, and then growing downwards.
pub const STACK_TOP: usize = 1 << 47;
pub const STACK_SIZE: usize = 1024 * 1024;
#[derive(Debug, Default)]
#[repr(C)]
pub struct SigArea {
pub altstack_top: usize,
pub altstack_bottom: usize,
pub tmp_x1_x2: [usize; 2],
pub tmp_x3_x4: [usize; 2],
pub tmp_x5_x6: [usize; 2],
pub tmp_x7_x8: [usize; 2],
pub tmp_sp: usize,
pub onstack: u64,
pub disable_signals_depth: u64,
pub pctl: usize, // TODO: remove
pub last_sig_was_restart: bool,
pub last_sigstack: Option<NonNull<SigStack>>,
pub tmp_rt_inf: RtSigInfo,
pub tmp_id_inf: u64,
}
#[repr(C)]
#[derive(Debug, Default)]
pub struct ArchIntRegs {
pub x30: usize,
pub x29: usize,
pub x28: usize,
pub x27: usize,
pub x26: usize,
pub x25: usize,
pub x24: usize,
pub x23: usize,
pub x22: usize,
pub x21: usize,
pub x20: usize,
pub x19: usize,
pub x18: usize,
pub x17: usize,
pub x16: usize,
pub x15: usize,
pub x14: usize,
pub x13: usize,
pub x12: usize,
pub x11: usize,
pub x10: usize,
pub x9: usize,
pub x8: usize,
pub x7: usize,
pub x6: usize,
pub x5: usize,
pub x4: usize,
pub x3: usize,
pub x2: usize,
pub x1: usize,
pub sp: usize,
pub nzcv: usize, // user-accessible PSTATE bits
pub pc: usize,
pub x0: usize,
}
/// Deactive TLS, used before exec() on Redox to not trick target executable into thinking TLS
/// is already initialized as if it was a thread.
pub unsafe fn deactivate_tcb(open_via_dup: &FdGuardUpper) -> Result<()> {
let mut env = syscall::EnvRegisters::default();
let file = open_via_dup.dup_into_upper(b"regs/env")?;
env.tpidr_el0 = 0;
file.write(&mut env)?;
crate::TLS_ACTIVATED.store(false, core::sync::atomic::Ordering::Relaxed);
Ok(())
}
unsafe extern "C" fn fork_impl(args: &ForkArgs, initial_rsp: *mut usize) -> usize {
Error::mux(fork_inner(initial_rsp, args))
}
unsafe extern "C" fn child_hook(scratchpad: &ForkScratchpad) {
//let _ = syscall::write(1, alloc::format!("CUR{cur_filetable_fd}PROC{new_proc_fd}THR{new_thr_fd}\n").as_bytes());
let _ = crate::sys::close(scratchpad.cur_filetable_fd);
unsafe {
crate::child_hook_common(crate::ChildHookCommonArgs {
new_thr_fd: FdGuard::new(scratchpad.new_thr_fd),
new_proc_fd: if scratchpad.new_proc_fd == usize::MAX {
None
} else {
Some(FdGuard::new(scratchpad.new_proc_fd))
},
new_filetable_fd: FdGuard::new(scratchpad.new_filetable_fd)
.to_upper()
.unwrap(),
})
};
}
asmfunction!(__relibc_internal_fork_wrapper (usize) -> usize: ["
stp x29, x30, [sp, #-16]!
stp x27, x28, [sp, #-16]!
stp x25, x26, [sp, #-16]!
stp x23, x24, [sp, #-16]!
stp x21, x22, [sp, #-16]!
stp x19, x20, [sp, #-16]!
//TODO: store floating point regs
// x0: &ForkArgs
mov x1, sp
bl {fork_impl}
ldp x19, x20, [sp], #16
ldp x21, x22, [sp], #16
ldp x23, x24, [sp], #16
ldp x25, x26, [sp], #16
ldp x27, x28, [sp], #16
ldp x29, x30, [sp], #16
ret
"] <= [fork_impl = sym fork_impl]);
asmfunction!(__relibc_internal_fork_ret: ["
# scratchpad is in x1, move to x0 for child_hook
mov x0, x1
bl {child_hook}
//TODO: load floating point regs
mov x0, xzr
ldp x19, x20, [sp], #16
ldp x21, x22, [sp], #16
ldp x23, x24, [sp], #16
ldp x25, x26, [sp], #16
ldp x27, x28, [sp], #16
ldp x29, x30, [sp], #16
ret
"] <= [child_hook = sym child_hook]);
// https://devblogs.microsoft.com/oldnewthing/20220811-00/?p=106963
asmfunction!(__relibc_internal_sigentry: ["
// Clear any active reservation.
clrex
// The old pc and x0 are saved in the sigcontrol struct.
mrs x0, tpidr_el0 // ABI ptr
ldr x0, [x0] // TCB ptr
// Save x1-x6 and sp
stp x1, x2, [x0, #{tcb_sa_off} + {sa_tmp_x1_x2}]
stp x3, x4, [x0, #{tcb_sa_off} + {sa_tmp_x3_x4}]
stp x5, x6, [x0, #{tcb_sa_off} + {sa_tmp_x5_x6}]
stp x7, x8, [x0, #{tcb_sa_off} + {sa_tmp_x7_x8}]
mov x1, sp
str x1, [x0, #{tcb_sa_off} + {sa_tmp_sp}]
ldr x6, [x0, #{tcb_sa_off} + {sa_pctl}]
1:
// Load x1 with the thread's bits
add x5, x0, #{tcb_sc_off} + {sc_word}
ldaxr x1, [x5]
// First check if there are standard thread signals,
and x4, x1, x1, lsr #32 // x4 := x1 & (x1 >> 32)
cbnz x4, 3f // jump if x4 != 0
clrex
// and if not, load process pending bitset.
add x5, x6, #{pctl_pending}
ldaxr x2, [x5]
// Check if there are standard proc signals:
lsr x3, x1, #32 // mask
and w3, w2, w3 // pending unblocked proc
cbz w3, 4f // skip 'fetch_andn' step if zero
// If there was one, find which one, and try clearing the bit (last value in x3, addr in x6)
// this picks the MSB rather than the LSB, unlike x86. POSIX does not require any specific
// ordering though.
clz w3, w3
mov w4, #31
sub w3, w4, w3
// x3 now contains the sig_idx
mov x4, #1
lsl x4, x4, x3 // bit to remove
sub x4, x2, x4 // bit was certainly set, so sub is allowed
// x4 is now the new mask to be set
add x5, x6, #{pctl_pending}
add x2, x5, #{pctl_sender_infos}
add x2, x2, w3, uxtb 3
ldar x2, [x2]
// Try clearing the bit, retrying on failure.
stxr w1, x4, [x5] // try setting pending set to x4, set w1 := 0 on success
cbnz w1, 1b // retry everything if this fails
mov x1, x3
b 2f
4:
// Check for realtime signals, thread/proc.
clrex
// Load the pending set again. TODO: optimize this?
// Process pending - realtime
add x1, x6, #{pctl_pending}
ldaxr x2, [x1]
lsr x2, x2, #32
// Thread pending - realtime and allowset
add x5, x0, #{tcb_sc_off} + {sc_word} + 8
ldar x1, [x5]
orr x2, x1, x2 // combine proc and thread pending
and x2, x2, x2, lsr #32 // AND pending with allowset
cbz x2, 7f // spurious signal if realtime is clear
rbit x2, x2
clz x2, x2
// x2 now contains sig_idx - 32
// If realtime signal was directed at thread, handle it as an idempotent signal.
lsr x3, x1, x2 // x3 := x1 >> x2; x1 is thread pending
tbnz x3, #0, 5f // jump if bit is nonzero
// SYS_CALL(fd, payload_base, payload_len, metadata_len, metadata_base | (flags << 8))
// x8 x0 x1 x2 x3 x4
mov x5, x0 // save TCB pointer
mov x6, x2
ldr x8, ={SYS_CALL}
adrp x0, {proc_fd}
ldr x0, [x0, #:lo12:{proc_fd}]
add x1, x5, #{tcb_sa_off} + {sa_tmp_rt_inf}
str x6, [x1]
mov x2, #{RTINF_SIZE}
adrp x4, {proc_call}
add x4, x4, :lo12:{proc_call}
mov x3, #1
svc 0
mov x3, x0
mov x0, x5 // restore TCB pointer
mov x2, x6 // restore signal number - 32
add x1, x2, #32 // signal number
cbnz x3, 1b
b 2f
5:
// A realtime signal was sent to this thread, try clearing its bit.
// x3 contains last rt signal word, x2 contains rt_idx
clrex
// Calculate the absolute sig_idx
add x1, x3, 32
// Load si_pid and si_uid
add x2, x0, #{tcb_sc_off} + {sc_sender_infos}
add x2, x2, w1, uxtb #3
ldar x2, [x2]
add x3, x0, #{tcb_sc_off} + {sc_word} + 8
ldxr x2, [x3]
// Calculate new mask
mov x4, #1
lsl x4, x4, x2
sub x2, x2, x4 // remove bit
stxr w5, x2, [x3]
cbnz w5, 1b
str x2, [x0, #{tcb_sa_off} + {sa_tmp_id_inf}]
b 2f
3:
// A standard signal was sent to this thread, try clearing its bit.
clz w1, w1
mov x2, #31
sub x1, x2, x1
// Load si_pid and si_uid
add x2, x0, #{tcb_sc_off} + {sc_sender_infos}
add x2, x2, w1, uxtb #3
ldar x2, [x2]
// Clear bit from mask
mov x3, #1
lsl x3, x3, x1
sub x4, x4, x3
// Try updating the mask
stxr w3, x1, [x5]
cbnz w3, 1b
str x2, [x0, #{tcb_sa_off} + {sa_tmp_id_inf}]
2:
ldr x3, [x0, #{tcb_sa_off} + {sa_pctl}]
add x3, x3, {pctl_actions}
add x2, x3, w1, uxtb #4 // actions_base + sig_idx * sizeof Action
// TODO: NOT ATOMIC (tearing allowed between regs)!
ldxp x2, x3, [x2]
clrex
// Calculate new sp wrt redzone and alignment
mov x4, sp
sub x4, x4, {REDZONE_SIZE}
and x4, x4, -{STACK_ALIGN}
mov sp, x4
// skip sigaltstack step if SA_ONSTACK is clear
// tbz x2, #{SA_ONSTACK_BIT}, 2f
ldr x2, [x0, #{tcb_sc_off} + {sc_saved_pc}]
ldr x3, [x0, #{tcb_sc_off} + {sc_saved_x0}]
stp x2, x3, [sp, #-16]!
ldr x2, [x0, #{tcb_sa_off} + {sa_tmp_sp}]
mrs x3, nzcv
stp x2, x3, [sp, #-16]!
ldp x2, x3, [x0, #{tcb_sa_off} + {sa_tmp_x1_x2}]
stp x2, x3, [sp, #-16]!
ldp x3, x4, [x0, #{tcb_sa_off} + {sa_tmp_x3_x4}]
stp x4, x3, [sp, #-16]!
ldp x5, x6, [x0, #{tcb_sa_off} + {sa_tmp_x5_x6}]
stp x6, x5, [sp, #-16]!
ldp x7, x8, [x0, #{tcb_sa_off} + {sa_tmp_x7_x8}]
stp x8, x7, [sp, #-16]!
stp x10, x9, [sp, #-16]!
stp x12, x11, [sp, #-16]!
stp x14, x13, [sp, #-16]!
stp x16, x15, [sp, #-16]!
stp x18, x17, [sp, #-16]!
stp x20, x19, [sp, #-16]!
stp x22, x21, [sp, #-16]!
stp x24, x23, [sp, #-16]!
stp x26, x25, [sp, #-16]!
stp x28, x27, [sp, #-16]!
stp x30, x29, [sp, #-16]!
str w1, [sp, #-4]
sub sp, sp, #64
mov x0, sp
bl {inner}
add sp, sp, #64
ldp x30, x29, [sp], #16
ldp x28, x27, [sp], #16
ldp x26, x25, [sp], #16
ldp x24, x23, [sp], #16
ldp x22, x21, [sp], #16
ldp x20, x19, [sp], #16
ldp x18, x17, [sp], #16
ldp x16, x15, [sp], #16
ldp x14, x13, [sp], #16
ldp x12, x11, [sp], #16
ldp x10, x9, [sp], #16
ldp x8, x7, [sp], #16
ldp x6, x5, [sp], #16
ldp x4, x3, [sp], #16
ldp x2, x1, [sp], #16
ldr x0, [sp, #8]
msr nzcv, x0
8:
// x18 is reserved by ABI as 'platform register', so clobbering it should be safe.
mov x18, sp
ldr x0, [x18]
mov sp, x0
ldp x18, x0, [x18, #16]
br x18
7:
// Spurious signal, i.e. all bitsets were 0 at the time they were checked
clrex
ldr x1, [x0, #{tcb_sc_off} + {sc_flags}]
and x1, x1, ~1
str x1, [x0, #{tcb_sc_off} + {sc_flags}]
ldp x1, x2, [x0, #{tcb_sa_off} + {sa_tmp_x1_x2}]
ldp x3, x4, [x0, #{tcb_sa_off} + {sa_tmp_x3_x4}]
ldp x5, x6, [x0, #{tcb_sa_off} + {sa_tmp_x5_x6}]
ldr x18, [x0, #{tcb_sc_off} + {sc_saved_pc}]
ldr x0, [x0, #{tcb_sc_off} + {sc_saved_x0}]
br x18
"] <= [
pctl_pending = const (offset_of!(SigProcControl, pending)),
pctl_actions = const (offset_of!(SigProcControl, actions)),
pctl_sender_infos = const (offset_of!(SigProcControl, sender_infos)),
tcb_sc_off = const (offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, control)),
tcb_sa_off = const (offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, arch)),
sa_tmp_x1_x2 = const offset_of!(SigArea, tmp_x1_x2),
sa_tmp_x3_x4 = const offset_of!(SigArea, tmp_x3_x4),
sa_tmp_x5_x6 = const offset_of!(SigArea, tmp_x5_x6),
sa_tmp_x7_x8 = const offset_of!(SigArea, tmp_x7_x8),
sa_tmp_sp = const offset_of!(SigArea, tmp_sp),
sa_tmp_rt_inf = const offset_of!(SigArea, tmp_rt_inf),
sa_tmp_id_inf = const offset_of!(SigArea, tmp_id_inf),
sa_pctl = const offset_of!(SigArea, pctl),
sc_saved_pc = const offset_of!(Sigcontrol, saved_ip),
sc_saved_x0 = const offset_of!(Sigcontrol, saved_archdep_reg),
sc_sender_infos = const offset_of!(Sigcontrol, sender_infos),
sc_word = const offset_of!(Sigcontrol, word),
sc_flags = const offset_of!(Sigcontrol, control_flags),
proc_fd = sym PROC_FD,
inner = sym inner_c,
proc_call = sym PROC_CALL,
SA_ONSTACK_BIT = const 58, // (1 << 58) >> 32 = 0x0400_0000
SYS_CALL = const syscall::SYS_CALL,
STACK_ALIGN = const 16,
REDZONE_SIZE = const 128,
RTINF_SIZE = const size_of::<RtSigInfo>(),
]);
asmfunction!(__relibc_internal_rlct_clone_ret: ["
# Load registers
ldp x8, x0, [sp], #16
ldp x1, x2, [sp], #16
ldp x3, x4, [sp], #16
# Call entry point
blr x8
ret
"] <= []);
pub fn current_sp() -> usize {
let sp: usize;
unsafe {
core::arch::asm!("mov {}, sp", out(reg) sp);
}
sp
}
pub unsafe fn manually_enter_trampoline() {
let ctl = unsafe { &Tcb::current().unwrap().os_specific.control };
ctl.saved_archdep_reg.set(0);
let ip_location = &ctl.saved_ip as *const _ as usize;
unsafe {
core::arch::asm!("
bl 2f
b 3f
2:
str lr, [x0]
b __relibc_internal_sigentry
3:
",
inout("x0") ip_location => _, out("lr") _);
}
}
pub unsafe fn arch_pre(stack: &mut SigStack, os: &mut SigArea) -> PosixStackt {
PosixStackt {
sp: core::ptr::null_mut(), // TODO
size: 0, // TODO
flags: 0, // TODO
}
}
pub fn arch_ret_to_sig(stack: &mut SigStack, control: &Sigcontrol) {
let orig_pc = core::mem::replace(
&mut stack.regs.pc,
__relibc_internal_sigentry as *const () as usize,
);
control.saved_ip.set(orig_pc);
control.saved_archdep_reg.set(stack.regs.x0);
}
pub(crate) static PROC_FD: SyncUnsafeCell<usize> = SyncUnsafeCell::new(usize::MAX);
static PROC_CALL: [usize; 1] = [ProcCall::Sigdeq as usize];
-418
View File
@@ -1,418 +0,0 @@
use core::{cell::SyncUnsafeCell, mem::offset_of, ptr::NonNull, sync::atomic::Ordering};
use syscall::*;
use crate::{
proc::{FdGuard, FdGuardUpper, ForkArgs, fork_inner},
signal::{PROC_CONTROL_STRUCT, PosixStackt, RtSigarea, SigStack, inner_fastcall},
};
use redox_protocols::protocol::{ProcCall, RtSigInfo};
use super::ForkScratchpad;
// Setup a stack starting from the very end of the address space, and then growing downwards.
pub const STACK_TOP: usize = 1 << 31;
pub const STACK_SIZE: usize = 1024 * 1024;
#[derive(Debug, Default)]
#[repr(C)]
pub struct SigArea {
pub altstack_top: usize,
pub altstack_bottom: usize,
pub tmp_eip: usize,
pub tmp_esp: usize,
pub tmp_eax: usize,
pub tmp_ebx: usize,
pub tmp_ecx: usize,
pub tmp_edx: usize,
pub tmp_edi: usize,
pub tmp_esi: usize,
pub tmp_rt_inf: RtSigInfo,
pub tmp_signo: usize,
pub tmp_id_inf: u64,
pub tmp_mm0: u64,
pub disable_signals_depth: u64,
pub last_sig_was_restart: bool,
pub last_sigstack: Option<NonNull<SigStack>>,
}
#[derive(Debug, Default)]
#[repr(C, align(16))]
pub struct ArchIntRegs {
pub fxsave: [u16; 29],
// ensure fxsave region is 16 byte aligned
pub _pad: [usize; 2], // fxsave "available" +0
pub ebp: usize, // fxsave "available" +8
pub esi: usize, // avail +12
pub edi: usize, // avail +16
pub ebx: usize, // avail +20
pub eax: usize, // avail +24
pub ecx: usize, // avail +28
pub edx: usize, // avail +32
pub eflags: usize, // avail +36
pub eip: usize, // avail +40
pub esp: usize, // avail +44
}
/// Deactive TLS, used before exec() on Redox to not trick target executable into thinking TLS
/// is already initialized as if it was a thread.
pub unsafe fn deactivate_tcb(open_via_dup: &FdGuardUpper) -> Result<()> {
let mut env = syscall::EnvRegisters::default();
let file = open_via_dup.dup_into_upper(b"regs/env")?;
env.fsbase = 0;
env.gsbase = 0;
file.write(&mut env)?;
crate::TLS_ACTIVATED.store(false, core::sync::atomic::Ordering::Relaxed);
Ok(())
}
unsafe extern "fastcall" fn fork_impl(args: &ForkArgs, initial_rsp: *mut usize) -> usize {
Error::mux(fork_inner(initial_rsp, args))
}
// TODO: duplicate code with x86_64
unsafe extern "cdecl" fn child_hook(scratchpad: ForkScratchpad) {
let _ = crate::sys::close(scratchpad.cur_filetable_fd);
unsafe {
crate::child_hook_common(crate::ChildHookCommonArgs {
new_thr_fd: FdGuard::new(scratchpad.new_thr_fd),
new_proc_fd: if scratchpad.new_proc_fd == usize::MAX {
None
} else {
Some(FdGuard::new(scratchpad.new_proc_fd))
},
new_filetable_fd: FdGuard::new(scratchpad.new_filetable_fd)
.to_upper()
.unwrap(),
})
};
}
asmfunction!(__relibc_internal_fork_wrapper (usize) -> usize: ["
mov ecx, [esp+4]
push ebp
mov ebp, esp
// Push preserved registers
push ebx
push edi
push esi
push ebp
sub esp, 32
//TODO stmxcsr [esp+16]
fnstcw [esp+24]
mov edx, esp
call {fork_impl}
jmp 2f
"] <= [fork_impl = sym fork_impl]);
asmfunction!(__relibc_internal_fork_ret: ["
// Arguments already on the stack
call {child_hook}
//TODO ldmxcsr [esp+16]
fldcw [esp+24]
xor eax, eax
.p2align 4
2:
add esp, 32
// Pop preserved registers
pop ebp
pop esi
pop edi
pop ebx
pop ebp
ret
"] <= [child_hook = sym child_hook]);
asmfunction!(__relibc_internal_sigentry: ["
// Save some registers
mov gs:[{tcb_sa_off} + {sa_tmp_esp}], esp
mov gs:[{tcb_sa_off} + {sa_tmp_eax}], eax
mov gs:[{tcb_sa_off} + {sa_tmp_edx}], edx
mov gs:[{tcb_sa_off} + {sa_tmp_ecx}], ecx
mov gs:[{tcb_sa_off} + {sa_tmp_ebx}], ebx
mov gs:[{tcb_sa_off} + {sa_tmp_edi}], edi
mov gs:[{tcb_sa_off} + {sa_tmp_esi}], esi
1:
// Read standard signal word - first for this thread
mov edx, gs:[{tcb_sc_off} + {sc_word} + 4]
mov eax, gs:[{tcb_sc_off} + {sc_word}]
and eax, edx
bsf eax, eax
jnz 9f
// Read standard signal word - for the process
lea ecx, [{pctl}]
mov eax, [ecx + {pctl_pending}]
and eax, edx
bsf eax, eax
jz 3f
// Read si_pid and si_uid, atomically.
movq gs:[{tcb_sa_off} + {sa_tmp_mm0}], mm0
movq mm0, [ecx + {pctl_sender_infos} + eax * 8]
movq gs:[{tcb_sa_off} + {sa_tmp_id_inf}], mm0
movq mm0, gs:[{tcb_sa_off} + {sa_tmp_mm0}]
// Try clearing the pending bit, otherwise retry if another thread did that first
lock btr [ecx + {pctl_pending}], eax
jnc 1b
jmp 2f
3:
// Read realtime thread and process signal word together
mov edx, [ecx + {pctl_pending} + 4]
mov eax, gs:[{tcb_sc_off} + {sc_word} + 8]
or eax, edx
and eax, gs:[{tcb_sc_off} + {sc_word} + 12]
bsf eax, eax
jz 7f // spurious signal
// If thread rather than process was specifically targeted, send the signal to it first.
bt edx, eax
jnc 8f
// SYS_CALL(fd, payload_base, payload_len, metadata_len, metadata_base)
// eax ebx ecx edx esi edi
mov ebx, [{proc_fd}]
mov ecx, gs:[0]
add ecx, {tcb_sa_off} + {sa_tmp_rt_inf}
mov [ecx], eax
mov gs:[{tcb_sa_off} + {sa_tmp_signo}], eax
mov edx, {RTINF_SIZE}
mov esi, 1
lea edi, [{proc_call}]
mov eax, {SYS_CALL}
int 0x80
test eax, eax
jnz 1b
mov eax, gs:[{tcb_sa_off} + {sa_tmp_signo}]
add eax, 32
jmp 2f
8:
add eax, 32
9:
// Read si_pid and si_uid, atomically.
movq gs:[{tcb_sa_off} + {sa_tmp_mm0}], mm0
movq mm0, gs:[{tcb_sc_off} + {sc_sender_infos} + eax * 8]
movq gs:[{tcb_sa_off} + {sa_tmp_id_inf}], mm0
movq mm0, gs:[{tcb_sa_off} + {sa_tmp_mm0}]
mov edx, eax
shr edx, 5
mov ecx, eax
and ecx, 31
lock btr gs:[{tcb_sc_off} + {sc_word} + edx * 8], ecx
add eax, 64
2:
and esp, -{STACK_ALIGN}
mov edx, eax
add edx, edx
bt dword ptr [{pctl} + {pctl_actions} + edx * 8 + 4], 28
jnc 4f
mov edx, gs:[{tcb_sa_off} + {sa_altstack_top}]
cmp esp, edx
ja 3f
cmp esp, gs:[{tcb_sa_off} + {sa_altstack_bottom}]
jnbe 4f
3:
mov esp, edx
4:
// Now that we have a stack, we can finally start populating the signal stack.
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_esp}]
push dword ptr gs:[{tcb_sc_off} + {sc_saved_eip}]
push dword ptr gs:[{tcb_sc_off} + {sc_saved_eflags}]
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_edx}]
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_ecx}]
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_eax}]
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_ebx}]
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_edi}]
push dword ptr gs:[{tcb_sa_off} + {sa_tmp_esi}]
push ebp
sub esp, 2 * 4 + 29 * 16
fxsave [esp]
mov [esp - 4], eax
sub esp, 48
mov ecx, esp
call {inner}
fxrstor [esp + 48]
add esp, 48 + 29 * 16 + 2 * 4
pop ebp
pop esi
pop edi
pop ebx
pop eax
pop ecx
pop edx
popfd
pop dword ptr gs:[{tcb_sa_off} + {sa_tmp_eip}]
.globl __relibc_internal_sigentry_crit_first
__relibc_internal_sigentry_crit_first:
pop esp
.globl __relibc_internal_sigentry_crit_second
__relibc_internal_sigentry_crit_second:
jmp dword ptr gs:[{tcb_sa_off} + {sa_tmp_eip}]
7:
mov eax, gs:[0]
lea esp, [eax + {tcb_sc_off} + {sc_saved_eflags}]
popfd
mov esp, gs:[{tcb_sa_off} + {sa_tmp_esp}]
mov eax, gs:[{tcb_sc_off} + {sc_saved_eip}]
mov gs:[{tcb_sa_off} + {sa_tmp_eip}], eax
mov eax, gs:[{tcb_sa_off} + {sa_tmp_eax}]
mov ebx, gs:[{tcb_sa_off} + {sa_tmp_ebx}]
mov ecx, gs:[{tcb_sa_off} + {sa_tmp_ecx}]
mov edx, gs:[{tcb_sa_off} + {sa_tmp_edx}]
mov edi, gs:[{tcb_sa_off} + {sa_tmp_edi}]
mov esi, gs:[{tcb_sa_off} + {sa_tmp_esi}]
and dword ptr gs:[{tcb_sc_off} + {sc_control}], ~1
.globl __relibc_internal_sigentry_crit_third
__relibc_internal_sigentry_crit_third:
jmp dword ptr gs:[{tcb_sa_off} + {sa_tmp_eip}]
"] <= [
inner = sym inner_fastcall,
sa_tmp_eip = const offset_of!(SigArea, tmp_eip),
sa_tmp_esp = const offset_of!(SigArea, tmp_esp),
sa_tmp_eax = const offset_of!(SigArea, tmp_eax),
sa_tmp_ebx = const offset_of!(SigArea, tmp_ebx),
sa_tmp_ecx = const offset_of!(SigArea, tmp_ecx),
sa_tmp_edx = const offset_of!(SigArea, tmp_edx),
sa_tmp_edi = const offset_of!(SigArea, tmp_edi),
sa_tmp_esi = const offset_of!(SigArea, tmp_esi),
sa_tmp_mm0 = const offset_of!(SigArea, tmp_mm0),
sa_tmp_rt_inf = const offset_of!(SigArea, tmp_rt_inf),
sa_tmp_id_inf = const offset_of!(SigArea, tmp_id_inf),
sa_tmp_signo = const offset_of!(SigArea, tmp_signo),
sa_altstack_top = const offset_of!(SigArea, altstack_top),
sa_altstack_bottom = const offset_of!(SigArea, altstack_bottom),
sc_control = const offset_of!(Sigcontrol, control_flags),
sc_saved_eflags = const offset_of!(Sigcontrol, saved_archdep_reg),
sc_saved_eip = const offset_of!(Sigcontrol, saved_ip),
sc_word = const offset_of!(Sigcontrol, word),
sc_sender_infos = const offset_of!(Sigcontrol, sender_infos),
tcb_sa_off = const offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, arch),
tcb_sc_off = const offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, control),
pctl_actions = const offset_of!(SigProcControl, actions),
pctl_sender_infos = const offset_of!(SigProcControl, sender_infos),
pctl_pending = const offset_of!(SigProcControl, pending),
pctl = sym PROC_CONTROL_STRUCT,
proc_fd = sym PROC_FD,
proc_call = sym PROC_CALL,
STACK_ALIGN = const 16,
SYS_CALL = const syscall::SYS_CALL,
RTINF_SIZE = const size_of::<RtSigInfo>(),
]);
asmfunction!(__relibc_internal_rlct_clone_ret -> usize: ["
# Load registers
pop eax
sub esp, 8
mov DWORD PTR [esp], 0x00001F80
# TODO: ldmxcsr [esp]
mov WORD PTR [esp], 0x037F
fldcw [esp]
add esp, 8
# Call entry point
call eax
ret
"] <= []);
unsafe extern "C" {
fn __relibc_internal_sigentry_crit_first();
fn __relibc_internal_sigentry_crit_second();
fn __relibc_internal_sigentry_crit_third();
}
pub unsafe fn arch_pre(stack: &mut SigStack, area: &mut SigArea) -> PosixStackt {
if stack.regs.eip == __relibc_internal_sigentry_crit_first as *const () as usize {
let stack_ptr = stack.regs.esp as *const usize;
stack.regs.esp = unsafe { stack_ptr.read() };
stack.regs.eip = unsafe { stack_ptr.sub(1).read() };
} else if stack.regs.eip == __relibc_internal_sigentry_crit_second as *const () as usize
|| stack.regs.eip == __relibc_internal_sigentry_crit_third as *const () as usize
{
stack.regs.eip = area.tmp_eip;
}
PosixStackt {
sp: stack.regs.esp as *mut (),
size: 0, // TODO
flags: 0, // TODO
}
}
pub fn arch_ret_to_sig(stack: &mut SigStack, control: &Sigcontrol) {
let orig_eip = core::mem::replace(
&mut stack.regs.eip,
__relibc_internal_sigentry as *const () as usize,
);
control.saved_ip.set(orig_eip);
control.saved_archdep_reg.set(stack.regs.eflags);
}
#[unsafe(no_mangle)]
pub unsafe fn manually_enter_trampoline() {
let c = unsafe { &crate::Tcb::current().unwrap().os_specific.control };
c.control_flags.store(
c.control_flags.load(Ordering::Relaxed) | syscall::flag::INHIBIT_DELIVERY.bits(),
Ordering::Release,
);
c.saved_archdep_reg.set(0); // TODO: Just reset DF on x86?
unsafe {
core::arch::asm!("
call 2f
jmp 3f
2:
pop dword ptr gs:[{tcb_sc_off} + {sc_saved_eip}]
jmp __relibc_internal_sigentry
3:
",
tcb_sc_off = const offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, control),
sc_saved_eip = const offset_of!(Sigcontrol, saved_ip),
);
}
}
/// Get current stack pointer, weak granularity guarantees.
pub fn current_sp() -> usize {
let sp: usize;
unsafe {
core::arch::asm!("mov {}, esp", out(reg) sp);
}
sp
}
pub static PROC_FD: SyncUnsafeCell<usize> = SyncUnsafeCell::new(usize::MAX);
static PROC_CALL: u64 = ProcCall::Sigdeq as u64;
-28
View File
@@ -1,28 +0,0 @@
#[cfg(target_arch = "aarch64")]
pub use self::aarch64::*;
#[cfg(target_arch = "aarch64")]
pub mod aarch64;
#[cfg(target_arch = "x86")]
pub use self::i686::*;
#[cfg(target_arch = "x86")]
pub mod i686;
#[cfg(target_arch = "x86_64")]
pub use self::x86_64::*;
#[cfg(target_arch = "x86_64")]
pub mod x86_64;
#[cfg(target_arch = "riscv64")]
pub use self::riscv64::*;
#[cfg(target_arch = "riscv64")]
pub mod riscv64;
#[derive(Debug)]
#[repr(C)]
pub struct ForkScratchpad {
pub cur_filetable_fd: usize,
pub new_filetable_fd: usize,
pub new_proc_fd: usize,
pub new_thr_fd: usize,
}
-661
View File
@@ -1,661 +0,0 @@
use core::cell::SyncUnsafeCell;
use crate::{
Tcb,
proc::{FdGuard, FdGuardUpper, ForkArgs, fork_inner},
signal::{PosixStackt, RtSigarea, SigStack, get_sigaltstack, inner_c},
};
use core::{mem::offset_of, ptr::NonNull, sync::atomic::Ordering};
use redox_protocols::protocol::{ProcCall, RtSigInfo};
use syscall::{data::*, error::*};
use super::ForkScratchpad;
// Setup a stack starting from the very end of the address space, and then growing downwards.
pub const STACK_TOP: usize = 1 << 38;
pub const STACK_SIZE: usize = 1024 * 1024;
#[derive(Debug, Default)]
#[repr(C)]
pub struct SigArea {
pub tmp_sp: u64,
pub tmp_t1: u64,
pub tmp_t2: u64,
pub tmp_t3: u64,
pub tmp_t4: u64,
pub tmp_a0: u64,
pub tmp_a1: u64,
pub tmp_a2: u64,
pub tmp_a3: u64,
pub tmp_a4: u64,
pub tmp_a7: u64,
pub pctl: usize, // TODO: remove
pub tmp_ip: u64,
pub tmp_rt_inf: RtSigInfo,
pub tmp_id_inf: u64,
pub altstack_top: usize,
pub altstack_bottom: usize,
pub disable_signals_depth: u64,
pub last_sig_was_restart: bool,
pub last_sigstack: Option<NonNull<SigStack>>,
}
#[repr(C)]
#[derive(Debug, Default)]
pub struct ArchIntRegs {
pub int_regs: [u64; 31],
pub pc: u64,
pub fp_regs: [u64; 32],
pub fcsr: u32,
_pad: u32,
}
/// Deactive TLS, used before exec() on Redox to not trick target executable into thinking TLS
/// is already initialized as if it was a thread.
pub unsafe fn deactivate_tcb(open_via_dup: &FdGuardUpper) -> Result<()> {
let mut env = syscall::EnvRegisters::default();
let file = open_via_dup.dup_into_upper(b"regs/env")?;
env.tp = 0;
file.write(&mut env)?;
crate::TLS_ACTIVATED.store(false, core::sync::atomic::Ordering::Relaxed);
Ok(())
}
unsafe extern "C" fn fork_impl(args: &ForkArgs, initial_rsp: *mut usize) -> usize {
Error::mux(fork_inner(initial_rsp, args))
}
unsafe extern "C" fn child_hook(scratchpad: &ForkScratchpad) {
let _ = crate::sys::close(scratchpad.cur_filetable_fd);
unsafe {
crate::child_hook_common(crate::ChildHookCommonArgs {
new_thr_fd: FdGuard::new(scratchpad.new_thr_fd),
new_proc_fd: if scratchpad.new_proc_fd == usize::MAX {
None
} else {
Some(FdGuard::new(scratchpad.new_proc_fd))
},
new_filetable_fd: FdGuard::new(scratchpad.new_filetable_fd)
.to_upper()
.unwrap(),
})
};
}
asmfunction!(__relibc_internal_fork_wrapper (usize) -> usize: ["
.attribute arch, \"rv64gc\" # rust bug 80608
addi sp, sp, -200
sd s0, 0(sp)
sd s1, 8(sp)
sd s2, 16(sp)
sd s3, 24(sp)
sd s4, 32(sp)
sd s5, 40(sp)
sd s6, 48(sp)
sd s7, 56(sp)
sd s8, 64(sp)
sd s9, 72(sp)
sd s10, 80(sp)
sd s11, 88(sp)
sd ra, 96(sp)
fsd fs0, 104(sp)
fsd fs1, 112(sp)
fsd fs2, 120(sp)
fsd fs3, 128(sp)
fsd fs4, 136(sp)
fsd fs5, 144(sp)
fsd fs6, 152(sp)
fsd fs7, 160(sp)
fsd fs8, 168(sp)
fsd fs9, 176(sp)
fsd fs10, 184(sp)
fsd fs11, 192(sp)
// a0 is forwarded from this function
mv a1, sp
jal {fork_impl}
ld s0, 0(sp)
ld s1, 8(sp)
ld s2, 16(sp)
ld s3, 24(sp)
ld s4, 32(sp)
ld s5, 40(sp)
ld s6, 48(sp)
ld s7, 56(sp)
ld s8, 64(sp)
ld s9, 72(sp)
ld s10, 80(sp)
ld s11, 88(sp)
ld ra, 96(sp)
fld fs0, 104(sp)
fld fs1, 112(sp)
fld fs2, 120(sp)
fld fs3, 128(sp)
fld fs4, 136(sp)
fld fs5, 144(sp)
fld fs6, 152(sp)
fld fs7, 160(sp)
fld fs8, 168(sp)
fld fs9, 176(sp)
fld fs10, 184(sp)
fld fs11, 192(sp)
addi sp, sp, 200
ret
"] <= [fork_impl = sym fork_impl]);
asmfunction!(__relibc_internal_fork_ret: ["
.attribute arch, \"rv64gc\" # rust bug 80608
# scratchpad is in a1, move to a0 for child_hook
mv a0, a1
jal {child_hook}
mv a0, zero
ld s0, 0(sp)
ld s1, 8(sp)
ld s2, 16(sp)
ld s3, 24(sp)
ld s4, 32(sp)
ld s5, 40(sp)
ld s6, 48(sp)
ld s7, 56(sp)
ld s8, 64(sp)
ld s9, 72(sp)
ld s10, 80(sp)
ld s11, 88(sp)
ld ra, 96(sp)
fld fs0, 104(sp)
fld fs1, 112(sp)
fld fs2, 120(sp)
fld fs3, 128(sp)
fld fs4, 136(sp)
fld fs5, 144(sp)
fld fs6, 152(sp)
fld fs7, 160(sp)
fld fs8, 168(sp)
fld fs9, 176(sp)
fld fs10, 184(sp)
fld fs11, 192(sp)
addi sp, sp, 200
ret
"] <= [child_hook = sym child_hook]);
asmfunction!(__relibc_internal_sigentry: ["
.attribute arch, \"rv64gc\" # rust bug 80608
// Save some registers
ld t0, -8(tp) // Tcb
sd sp, ({tcb_sa_off} + {sa_tmp_sp})(t0)
sd t1, ({tcb_sa_off} + {sa_tmp_t1})(t0)
sd t2, ({tcb_sa_off} + {sa_tmp_t2})(t0)
sd t3, ({tcb_sa_off} + {sa_tmp_t3})(t0)
sd t4, ({tcb_sa_off} + {sa_tmp_t4})(t0)
ld t4, ({tcb_sa_off} + {sa_off_pctl})(t0)
// First, select signal, always pick first available bit
99:
// Read first signal word
ld t1, ({tcb_sc_off} + {sc_word})(t0)
srli t2, t1, 32 // bitset to low word
and t1, t1, t2 // masked bitset in low word
beqz t1, 3f
// Found in first thread signal word
mv t3, x0
2: andi t2, t1, 1
bnez t2, 10f
addi t3, t3, 1
srli t1, t1, 1
j 2b
// If no unblocked thread signal was found, check for process.
// This is competitive; we need to atomically check if *we* cleared the process-wide pending
// bit, otherwise restart.
3: lw t1, {pctl_off_pending}(t4)
and t1, t1, t2
beqz t1, 3f
// Found in first process signal word
li t3, -1
2: andi t2, t1, 1
addi t3, t3, 1
srli t1, t1, 1
beqz t2, 2b
slli t1, t3, 3 // * 8 == size_of SenderInfo
add t1, t1, t4
ld t1, {pctl_off_sender_infos}(t1)
sd t1, ({tcb_sa_off} + {sa_tmp_id_inf})(t0)
li t1, 1
sll t1, t1, t3
not t1, t1
addi t2, t4, {pctl_off_pending}
amoand.w.aq t2, t1, (t2)
and t1, t1, t2
bne t1, t2, 9f
3:
// Read second signal word - both process and thread simultaneously.
// This must be done since POSIX requires low realtime signals to be picked first.
ld t1, ({tcb_sc_off} + {sc_word} + 8)(t0)
lw t2, ({pctl_off_pending} + 4)(t4)
or t4, t1, t2
srli t2, t1, 32
and t4, t2, t4
beqz t4, 7f
li t3, -1
2: andi t2, t4, 1
addi t3, t3, 1
srli t4, t4, 1
beqz t2, 2b
li t2, 1
sll t2, t2, t3
and t1, t1, t2
addi t3, t3, 32
bnez t1, 10f // thread signal
// otherwise, try (competitively) dequeueing realtime signal
// SYS_CALL(fd, payload_base, payload_len, metadata_len, metadata_base)
// a7 a0 a1 a2 a3 a4
// TODO: This SYS_CALL invocation has not yet been tested due to toolchain issues.
sd a0, ({tcb_sa_off} + {sa_tmp_a0})(t0)
sd a1, ({tcb_sa_off} + {sa_tmp_a1})(t0)
sd a2, ({tcb_sa_off} + {sa_tmp_a2})(t0)
sd a3, ({tcb_sa_off} + {sa_tmp_a3})(t0)
sd a4, ({tcb_sa_off} + {sa_tmp_a4})(t0)
sd a7, ({tcb_sa_off} + {sa_tmp_a7})(t0)
li a7, {SYS_CALL}
addi a2, t3, -32
add a1, t0, {tcb_sa_off} + {sa_tmp_rt_inf} // out pointer of dequeued realtime sig
sd a2, (a1)
li a2, {RTINF_SIZE}
li a3, 1
1337:
auipc a4, %pcrel_hi({proc_fd})
addi a4, a4, %pcrel_lo(1337b)
ecall
ld a3, ({tcb_sa_off} + {sa_tmp_a3})(t0)
ld a4, ({tcb_sa_off} + {sa_tmp_a4})(t0)
bnez a0, 99b // assumes error can only be EAGAIN
j 9f
10: // thread signal. t3 holds signal number
srli t1, t3, 5
bnez t1, 2f // FIXME senderinfo?
sll t2, t3, 3 // * 8 == size_of SenderInfo
add t2, t2, t0
ld t2, ({tcb_sc_off} + {sc_sender_infos})(t2)
sd t2, ({tcb_sa_off} + {sa_tmp_id_inf})(t0)
2: andi t4, t3, 31
li t2, 1
sll t2, t2, t4
not t2, t2
sll t1, t1, 3
add t1, t1, t0
addi t1, t1, {tcb_sc_off} + {sc_word}
amoand.w.aq x0, t2, (t1)
addi t3, t3, 64 // indicate signal was targeted at thread
9: // process signal t3 holds signal number
// By now we have selected a signal, stored in eax (6-bit). We now need to choose whether or
// not to switch to the alternate signal stack. If SA_ONSTACK is clear for this signal, then
// skip the sigaltstack logic.
ld t4, ({tcb_sa_off} + {sa_off_pctl})(t0)
andi t1, t3, 63
slli t1, t1, 4 // * 16 == size_of RawAction
add t1, t1, t4
ld t1, {pctl_off_actions}(t1)
slli t1, t1, 63-58 // SA_ONSTACK in sign bit
bgez t1, 3f
// If current RSP is above altstack region, switch to altstack
ld t1, ({tcb_sa_off} + {sa_altstack_top})(t0)
bgtu sp, t1, 2f
ld t2, ({tcb_sa_off} + {sa_altstack_bottom})(t0)
bgtu sp, t3, 3f
2: mv sp, t1
3:
// form mcontext on stack
addi sp, sp, -33 * 8
fsd f0, (0 * 8)(sp)
fsd f1, (1 * 8)(sp)
fsd f2, (2 * 8)(sp)
fsd f3, (3 * 8)(sp)
fsd f4, (4 * 8)(sp)
fsd f5, (5 * 8)(sp)
fsd f6, (6 * 8)(sp)
fsd f7, (7 * 8)(sp)
fsd f8, (8 * 8)(sp)
fsd f9, (9 * 8)(sp)
fsd f10, (10 * 8)(sp)
fsd f11, (11 * 8)(sp)
fsd f12, (12 * 8)(sp)
fsd f13, (13 * 8)(sp)
fsd f14, (14 * 8)(sp)
fsd f15, (15 * 8)(sp)
fsd f16, (16 * 8)(sp)
fsd f17, (17 * 8)(sp)
fsd f18, (18 * 8)(sp)
fsd f19, (19 * 8)(sp)
fsd f20, (20 * 8)(sp)
fsd f21, (21 * 8)(sp)
fsd f22, (22 * 8)(sp)
fsd f23, (23 * 8)(sp)
fsd f24, (24 * 8)(sp)
fsd f25, (25 * 8)(sp)
fsd f26, (26 * 8)(sp)
fsd f27, (27 * 8)(sp)
fsd f28, (28 * 8)(sp)
fsd f29, (29 * 8)(sp)
fsd f30, (30 * 8)(sp)
fsd f31, (31 * 8)(sp)
csrr t1, fcsr
sw t1, (32 * 8)(sp)
addi sp, sp, -32 * 8
sd x1, 0(sp)
ld t1, ({tcb_sa_off} + {sa_tmp_sp})(t0)
sd t1, (1 * 8)(sp) // x2 is sp
sd x3, (2 * 8)(sp)
sd x4, (3 * 8)(sp)
ld t1, ({tcb_sc_off} + {sc_saved_t0})(t0)
sd t1, (4 * 8)(sp) // x5 is t0
ld t1, ({tcb_sa_off} + {sa_tmp_t1})(t0)
sd t1, (5 * 8)(sp) // x6 is t1
ld t1, ({tcb_sa_off} + {sa_tmp_t2})(t0)
sd t1, (6 * 8)(sp) // x7 is t2
sd x8, (7 * 8)(sp)
sd x9, (8 * 8)(sp)
sd x10, (9 * 8)(sp)
sd x11, (10 * 8)(sp)
sd x12, (11 * 8)(sp)
sd x13, (12 * 8)(sp)
sd x14, (13 * 8)(sp)
sd x15, (14 * 8)(sp)
sd x16, (15 * 8)(sp)
sd x17, (16 * 8)(sp)
sd x18, (17 * 8)(sp)
sd x19, (18 * 8)(sp)
sd x20, (19 * 8)(sp)
sd x21, (20 * 8)(sp)
sd x22, (21 * 8)(sp)
sd x23, (22 * 8)(sp)
sd x24, (23 * 8)(sp)
sd x25, (24 * 8)(sp)
sd x26, (25 * 8)(sp)
sd x27, (26 * 8)(sp)
ld t1, ({tcb_sa_off} + {sa_tmp_t3})(t0)
sd t1, (27 * 8)(sp) // t3 is x28
ld t1, ({tcb_sa_off} + {sa_tmp_t4})(t0)
sd t1, (28 * 8)(sp) // t4 is x29
sd x30, (29 * 8)(sp)
sd x31, (30 * 8)(sp)
ld t1, ({tcb_sc_off} + {sc_saved_ip})(t0)
sd t1, (31 * 8)(sp)
// form ucontext
addi sp, sp, -64
sw t3, 60(sp)
mv t0, sp
jal {inner}
addi sp, sp, 64
addi t0, sp, 32 * 8
fld f0, (0 * 8)(t0)
fld f1, (1 * 8)(t0)
fld f2, (2 * 8)(t0)
fld f3, (3 * 8)(t0)
fld f4, (4 * 8)(t0)
fld f5, (5 * 8)(t0)
fld f6, (6 * 8)(t0)
fld f7, (7 * 8)(t0)
fld f8, (8 * 8)(t0)
fld f9, (9 * 8)(t0)
fld f10, (10 * 8)(t0)
fld f11, (11 * 8)(t0)
fld f12, (12 * 8)(t0)
fld f13, (13 * 8)(t0)
fld f14, (14 * 8)(t0)
fld f15, (15 * 8)(t0)
fld f16, (16 * 8)(t0)
fld f17, (17 * 8)(t0)
fld f18, (18 * 8)(t0)
fld f19, (19 * 8)(t0)
fld f20, (20 * 8)(t0)
fld f21, (21 * 8)(t0)
fld f22, (22 * 8)(t0)
fld f23, (23 * 8)(t0)
fld f24, (24 * 8)(t0)
fld f25, (25 * 8)(t0)
fld f26, (26 * 8)(t0)
fld f27, (27 * 8)(t0)
fld f28, (28 * 8)(t0)
fld f29, (29 * 8)(t0)
fld f30, (30 * 8)(t0)
fld f31, (31 * 8)(t0)
lw t1, (32 * 8)(t0)
csrw fcsr, t1
ld x1, 0(sp)
// skip sp
// skip gp
ld x4, (3 * 8)(sp)
ld x5, (4 * 8)(sp)
ld x6, (5 * 8)(sp)
ld x7, (6 * 8)(sp)
ld x8, (7 * 8)(sp)
ld x9, (8 * 8)(sp)
ld x10, (9 * 8)(sp)
ld x11, (10 * 8)(sp)
ld x12, (11 * 8)(sp)
ld x13, (12 * 8)(sp)
ld x14, (13 * 8)(sp)
ld x15, (14 * 8)(sp)
ld x16, (15 * 8)(sp)
ld x17, (16 * 8)(sp)
ld x18, (17 * 8)(sp)
ld x19, (18 * 8)(sp)
ld x20, (19 * 8)(sp)
ld x21, (20 * 8)(sp)
ld x22, (21 * 8)(sp)
ld x23, (22 * 8)(sp)
ld x24, (23 * 8)(sp)
ld x25, (24 * 8)(sp)
ld x26, (25 * 8)(sp)
ld x27, (26 * 8)(sp)
ld x28, (27 * 8)(sp)
ld x29, (28 * 8)(sp)
ld x30, (29 * 8)(sp)
ld x31, (30 * 8)(sp)
ld gp, (31 * 8)(sp) // new IP; this clobbers register x3/gp which is ABI reserved
.global __relibc_internal_sigentry_crit_first
__relibc_internal_sigentry_crit_first:
ld sp, (1 * 8)(sp)
.global __relibc_internal_sigentry_crit_second
__relibc_internal_sigentry_crit_second:
jr gp
7:
// A spurious signal occurred. Signals are still disabled here, but will need to be re-enabled.
// restore stack
ld sp, ({tcb_sa_off} + {sa_tmp_sp})(t0)
// move saved IP away from control, allowing arch_pre to save us if interrupted.
ld t1, ({tcb_sc_off} + {sc_saved_ip})(t0)
sd t1, ({tcb_sa_off} + {sa_tmp_ip})(t0)
// restore regs
ld t2, ({tcb_sa_off} + {sa_tmp_t2})(t0)
ld t3, ({tcb_sa_off} + {sa_tmp_t3})(t0)
ld t4, ({tcb_sa_off} + {sa_tmp_t4})(t0)
// move saved t0 away from control as well
mv t1, t0
ld t0, ({tcb_sc_off} + {sc_saved_t0})(t0)
// Re-enable signals. This code can be interrupted after this signal, so we need to define
// 'crit_third'.
ld gp, ({tcb_sc_off} + {sc_control})(t1)
andi gp, gp, ~1
sd gp, ({tcb_sc_off} + {sc_control})(t1)
.globl __relibc_internal_sigentry_crit_third
__relibc_internal_sigentry_crit_third:
ld gp, ({tcb_sa_off} + {sa_tmp_ip})(t1)
.globl __relibc_internal_sigentry_crit_fourth
__relibc_internal_sigentry_crit_fourth:
ld t1, ({tcb_sa_off} + {sa_tmp_t1})(t1)
.globl __relibc_internal_sigentry_crit_fifth
__relibc_internal_sigentry_crit_fifth:
jr gp
"] <= [
tcb_sc_off = const (offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, control)),
sc_word = const offset_of!(Sigcontrol, word),
sc_saved_t0 = const offset_of!(Sigcontrol, saved_archdep_reg),
sc_saved_ip = const offset_of!(Sigcontrol, saved_ip),
sc_sender_infos = const offset_of!(Sigcontrol, sender_infos),
sc_control = const offset_of!(Sigcontrol, control_flags),
tcb_sa_off = const (offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, arch)),
sa_off_pctl = const offset_of!(SigArea, pctl),
sa_tmp_sp = const offset_of!(SigArea, tmp_sp),
sa_tmp_t1 = const offset_of!(SigArea, tmp_t1),
sa_tmp_t2 = const offset_of!(SigArea, tmp_t2),
sa_tmp_t3 = const offset_of!(SigArea, tmp_t3),
sa_tmp_t4 = const offset_of!(SigArea, tmp_t4),
sa_tmp_a0 = const offset_of!(SigArea, tmp_a0),
sa_tmp_a1 = const offset_of!(SigArea, tmp_a1),
sa_tmp_a2 = const offset_of!(SigArea, tmp_a2),
sa_tmp_a3 = const offset_of!(SigArea, tmp_a3),
sa_tmp_a4 = const offset_of!(SigArea, tmp_a4),
sa_tmp_a7 = const offset_of!(SigArea, tmp_a7),
sa_tmp_ip = const offset_of!(SigArea, tmp_ip),
sa_tmp_id_inf = const offset_of!(SigArea, tmp_id_inf),
sa_tmp_rt_inf = const offset_of!(SigArea, tmp_rt_inf),
sa_altstack_top = const offset_of!(SigArea, altstack_top),
sa_altstack_bottom = const offset_of!(SigArea, altstack_bottom),
pctl_off_actions = const offset_of!(SigProcControl, actions),
inner = sym inner_c,
pctl_off_pending = const offset_of!(SigProcControl, pending),
pctl_off_sender_infos = const offset_of!(SigProcControl, sender_infos),
SYS_CALL = const syscall::SYS_CALL,
RTINF_SIZE = const size_of::<RtSigInfo>(),
proc_fd = sym PROC_FD,
]);
asmfunction!(__relibc_internal_rlct_clone_ret: ["
ld t0, 0(sp)
ld a0, 8(sp)
ld a1, 16(sp)
ld a2, 24(sp)
ld a3, 32(sp)
ld a4, 40(sp)
ld a5, 48(sp)
addi sp, sp, 56
jalr t0
ret
"] <= []);
pub fn current_sp() -> usize {
let sp: usize;
unsafe {
core::arch::asm!(
"mv {}, sp",
out(reg) sp,
options(nomem));
}
sp
}
pub unsafe fn manually_enter_trampoline() {
let ctl = unsafe { &Tcb::current().unwrap().os_specific.control };
ctl.control_flags.store(
ctl.control_flags.load(Ordering::Relaxed) | syscall::flag::INHIBIT_DELIVERY.bits(),
Ordering::Release,
);
ctl.saved_archdep_reg.set(0);
let ip_location = &ctl.saved_ip as *const _ as usize;
unsafe {
core::arch::asm!("
jal 2f
j 3f
2:
sd ra, 0(t0)
la t0, __relibc_internal_sigentry
jalr x0, t0
3:
",
inout("t0") ip_location => _, out("ra") _);
}
}
unsafe extern "C" {
fn __relibc_internal_sigentry_crit_first();
fn __relibc_internal_sigentry_crit_second();
fn __relibc_internal_sigentry_crit_third();
fn __relibc_internal_sigentry_crit_fourth();
fn __relibc_internal_sigentry_crit_fifth();
}
pub unsafe fn arch_pre(stack: &mut SigStack, area: &mut SigArea) -> PosixStackt {
// It is impossible to update SP and PC atomically. Instead, we abuse the fact that
// signals are disabled in the prologue of the signal trampoline, which allows us to emulate
// atomicity inside the critical section, consisting of one instruction at 'crit_first', and
// one at 'crit_second', see asm.
if stack.regs.pc == __relibc_internal_sigentry_crit_first as *const () as u64 {
// Reexecute 'ld sp, (1 * 8)(sp)'
let stack_ptr = stack.regs.int_regs[1] as *const u64; // x2
stack.regs.int_regs[1] = unsafe { stack_ptr.add(1).read() };
// and 'jr gp' steps.
stack.regs.pc = stack.regs.int_regs[2];
} else if stack.regs.pc == __relibc_internal_sigentry_crit_second as *const () as u64
|| stack.regs.pc == __relibc_internal_sigentry_crit_fifth as *const () as u64
{
// just reexecute the jump
stack.regs.pc = stack.regs.int_regs[2];
} else if stack.regs.pc == __relibc_internal_sigentry_crit_third as *const () as u64 {
// ld gp, ({tcb_sa_off} + {sa_tmp_ip})(t1)
stack.regs.int_regs[2] = area.tmp_ip;
// ld t1, ({tcb_sa_off} + {sa_tmp_t1})(t1)
stack.regs.int_regs[5] = area.tmp_t1;
// j gp
stack.regs.pc = stack.regs.int_regs[2];
} else if stack.regs.pc == __relibc_internal_sigentry_crit_fourth as *const () as u64 {
// ld t1, ({tcb_sa_off} + {sa_tmp_t1})(t1)
stack.regs.int_regs[5] = area.tmp_t1;
// jr gp
stack.regs.pc = stack.regs.int_regs[2];
}
get_sigaltstack(area, stack.regs.int_regs[1] as usize).into()
}
pub fn arch_ret_to_sig(stack: &mut SigStack, control: &Sigcontrol) {
let orig_pc = core::mem::replace(
&mut stack.regs.pc,
__relibc_internal_sigentry as *const () as u64,
);
control.saved_ip.set(orig_pc as usize);
control
.saved_archdep_reg
.set(stack.regs.int_regs[4] as usize); // t0
}
pub(crate) static PROC_FD: SyncUnsafeCell<usize> = SyncUnsafeCell::new(usize::MAX);
static PROC_CALL: [usize; 1] = [ProcCall::Sigdeq as usize];
-535
View File
@@ -1,535 +0,0 @@
use core::{
cell::SyncUnsafeCell,
mem::offset_of,
ptr::NonNull,
sync::atomic::{AtomicU8, Ordering},
};
use syscall::{
data::{SigProcControl, Sigcontrol},
error::*,
};
use crate::{
Tcb,
proc::{FdGuard, FdGuardUpper, ForkArgs, fork_inner},
signal::{PROC_CONTROL_STRUCT, PosixStackt, RtSigarea, SigStack, get_sigaltstack, inner_c},
};
use redox_protocols::protocol::{ProcCall, RtSigInfo};
use super::ForkScratchpad;
// Setup a stack starting from the very end of the address space, and then growing downwards.
pub const STACK_TOP: usize = 1 << 47;
pub const STACK_SIZE: usize = 8 * 1024 * 1024;
#[derive(Debug, Default)]
#[repr(C)]
pub struct SigArea {
pub tmp_rip: usize,
pub tmp_rsp: usize,
pub tmp_rax: usize,
pub tmp_rdx: usize,
pub tmp_rdi: usize,
pub tmp_rsi: usize,
pub tmp_r8: usize,
pub tmp_r10: usize,
pub tmp_r12: usize,
pub tmp_rt_inf: RtSigInfo,
pub tmp_id_inf: u64,
pub altstack_top: usize,
pub altstack_bottom: usize,
pub disable_signals_depth: u64,
pub last_sig_was_restart: bool,
pub last_sigstack: Option<NonNull<SigStack>>,
}
#[repr(C, align(16))]
#[derive(Debug, Default)]
pub struct ArchIntRegs {
pub ymm_upper: [u128; 16],
pub fxsave: [u128; 29],
pub r15: usize, // fxsave "available" +0
pub r14: usize, // available +8
pub r13: usize, // available +16
pub r12: usize, // available +24
pub rbp: usize, // available +32
pub rbx: usize, // available +40
pub r11: usize, // outside fxsave, and so on
pub r10: usize,
pub r9: usize,
pub r8: usize,
pub rax: usize,
pub rcx: usize,
pub rdx: usize,
pub rsi: usize,
pub rdi: usize,
pub rflags: usize,
pub rip: usize,
pub rsp: usize,
}
/// Deactive TLS, used before exec() on Redox to not trick target executable into thinking TLS
/// is already initialized as if it was a thread.
pub unsafe fn deactivate_tcb(open_via_dup: &FdGuardUpper) -> Result<()> {
let mut env = syscall::EnvRegisters::default();
let file = open_via_dup.dup_into_upper(b"regs/env")?;
env.fsbase = 0;
env.gsbase = 0;
file.write(&env)?;
crate::TLS_ACTIVATED.store(false, core::sync::atomic::Ordering::Relaxed);
Ok(())
}
unsafe extern "sysv64" fn fork_impl(args: &ForkArgs, initial_rsp: *mut usize) -> usize {
Error::mux(fork_inner(initial_rsp, args))
}
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "sysv64" fn child_hook(scratchpad: &ForkScratchpad) {
let _ = crate::sys::close(scratchpad.cur_filetable_fd);
crate::child_hook_common(crate::ChildHookCommonArgs {
new_thr_fd: FdGuard::new(scratchpad.new_thr_fd),
new_proc_fd: if scratchpad.new_proc_fd == usize::MAX {
None
} else {
Some(FdGuard::new(scratchpad.new_proc_fd))
},
new_filetable_fd: FdGuard::new(scratchpad.new_filetable_fd)
.to_upper()
.unwrap(),
});
}
asmfunction!(__relibc_internal_fork_wrapper (usize) -> usize: ["
push rbp
mov rbp, rsp
push rbx
push rbp
push r12
push r13
push r14
push r15
sub rsp, 16
stmxcsr [rsp+16]
fnstcw [rsp+8]
// rdi: &ForkArgs
// rsi: initial_rsp
mov rsi, rsp
call {fork_impl}
add rsp, 64
pop rbp
ret
"] <= [fork_impl = sym fork_impl]);
asmfunction!(__relibc_internal_fork_ret: ["
# scratchpad is in rsi, move to rdi for child_hook
mov rdi, rsi
call {child_hook}
ldmxcsr [rsp + 16]
mov rcx, [rsp + 8]
xor rax, rax
add rsp, 16
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rbx
pop rbp
ret
"] <= [child_hook = sym child_hook]);
asmfunction!(__relibc_internal_rlct_clone_ret: ["
# Load registers
pop rax
pop rdi
pop rsi
pop rdx
pop rcx
pop r8
pop r9
mov DWORD PTR [rsp - 8], 0x00001F80
ldmxcsr [rsp - 8]
mov WORD PTR [rsp - 8], 0x037F
fldcw [rsp - 8]
# Call entry point
call rax
ret
"] <= []);
asmfunction!(__relibc_internal_sigentry: ["
// Save some registers
mov fs:[{tcb_sa_off} + {sa_tmp_rsp}], rsp
mov fs:[{tcb_sa_off} + {sa_tmp_rax}], rax
mov fs:[{tcb_sa_off} + {sa_tmp_rdx}], rdx
mov fs:[{tcb_sa_off} + {sa_tmp_rdi}], rdi
mov fs:[{tcb_sa_off} + {sa_tmp_rsi}], rsi
mov fs:[{tcb_sa_off} + {sa_tmp_r8}], r8
mov fs:[{tcb_sa_off} + {sa_tmp_r10}], r10
mov fs:[{tcb_sa_off} + {sa_tmp_r12}], r12
// First, select signal, always pick first available bit
1:
// Read standard signal word - first targeting this thread
mov rax, fs:[{tcb_sc_off} + {sc_word}]
mov rdx, rax
shr rdx, 32
and eax, edx
bsf eax, eax
jnz 2f
// If no unblocked thread signal was found, check for process.
// This is competitive; we need to atomically check if *we* cleared the process-wide pending
// bit, otherwise restart.
mov eax, [rip + {pctl} + {pctl_off_pending}]
and eax, edx
bsf eax, eax
jz 8f
lea rdi, [rip + {pctl} + {pctl_off_sender_infos}]
mov rdi, [rdi + rax * 8]
lock btr [rip + {pctl} + {pctl_off_pending}], eax
mov fs:[{tcb_sa_off} + {sa_tmp_id_inf}], rdi
jc 9f
8:
// Read second signal word - both process and thread simultaneously.
// This must be done since POSIX requires low realtime signals to be picked first.
mov edx, fs:[{tcb_sc_off} + {sc_word} + 8]
mov eax, [rip + {pctl} + {pctl_off_pending} + 4]
or eax, edx
and eax, fs:[{tcb_sc_off} + {sc_word} + 12]
bsf eax, eax
jz 7f
bt edx, eax // check if signal was sent to thread specifically
jnc 81f
// if so, continue as usual
add eax, 32
jmp 2f
81:
// otherwise, try (competitively) dequeueing realtime signal
// SYS_CALL(fd, payload_base, payload_len, metadata_len | (flags << 8), metadata_base)
// rax rdi rsi rdx r10 r8
mov r12d, eax
mov rsi, fs:[0]
mov rdi, [rip+{proc_fd}]
add rsi, {tcb_sa_off} + {sa_tmp_rt_inf} // out pointer of dequeued realtime sig
mov rdx, {RTINF_SIZE}
mov [rsi], eax
lea r8, [rip + {proc_call_sigdeq}]
mov r10, 1
mov eax, {SYS_CALL}
syscall
test eax, eax
jnz 1b // assumes error can only be EAGAIN
lea eax, [r12d + 32]
jmp 9f
2:
mov edx, eax
shr edx, 5
mov rdi, fs:[{tcb_sc_off} + {sc_sender_infos} + eax * 8]
lock btr fs:[{tcb_sc_off} + {sc_word} + edx * 4], eax
mov fs:[{tcb_sa_off} + {sa_tmp_id_inf}], rdi
add eax, 64 // indicate signal was targeted at thread
9:
sub rsp, {REDZONE_SIZE}
and rsp, -{STACK_ALIGN}
// By now we have selected a signal, stored in eax (6-bit). We now need to choose whether or
// not to switch to the alternate signal stack. If SA_ONSTACK is clear for this signal, then
// skip the sigaltstack logic.
lea rdx, [rip + {pctl} + {pctl_off_actions}]
mov ecx, eax
and ecx, 63
// LEA doesn't support 16x, so just do two x8s.
lea rdx, [rdx + 8 * rcx]
lea rdx, [rdx + 8 * rcx]
bt qword ptr [rdx], {SA_ONSTACK_BIT}
jnc 4f
// Otherwise, the altstack is already active. The sigaltstack being disabled, is equivalent
// to setting 'top' to usize::MAX and 'bottom' to 0.
// If current RSP is above altstack region, switch to altstack
mov rdx, fs:[{tcb_sa_off} + {sa_altstack_top}]
cmp rsp, rdx
cmova rsp, rdx
// If current RSP is below altstack region, also switch to altstack
cmp rsp, fs:[{tcb_sa_off} + {sa_altstack_bottom}]
cmovbe rsp, rdx
.p2align 4
4:
// Now that we have a stack, we can finally start initializing the signal stack!
push fs:[{tcb_sa_off} + {sa_tmp_rsp}]
push fs:[{tcb_sc_off} + {sc_saved_rip}]
push fs:[{tcb_sc_off} + {sc_saved_rflags}]
push fs:[{tcb_sa_off} + {sa_tmp_rdi}]
push fs:[{tcb_sa_off} + {sa_tmp_rsi}]
push fs:[{tcb_sa_off} + {sa_tmp_rdx}]
push rcx
push fs:[{tcb_sa_off} + {sa_tmp_rax}]
push fs:[{tcb_sa_off} + {sa_tmp_r8}]
push r9
push fs:[{tcb_sa_off} + {sa_tmp_r10}]
push r11
push rbx
push rbp
push fs:[{tcb_sa_off} + {sa_tmp_r12}]
push r13
push r14
push r15
sub rsp, (29 + 16) * 16 // fxsave region minus available bytes
fxsave64 [rsp + 16 * 16]
// TODO: self-modifying?
cmp byte ptr [rip + {supports_avx}], 0
je 5f
// Prefer vextractf128 over vextracti128 since the former only requires AVX version 1.
vextractf128 [rsp + 15 * 16], ymm0, 1
vextractf128 [rsp + 14 * 16], ymm1, 1
vextractf128 [rsp + 13 * 16], ymm2, 1
vextractf128 [rsp + 12 * 16], ymm3, 1
vextractf128 [rsp + 11 * 16], ymm4, 1
vextractf128 [rsp + 10 * 16], ymm5, 1
vextractf128 [rsp + 9 * 16], ymm6, 1
vextractf128 [rsp + 8 * 16], ymm7, 1
vextractf128 [rsp + 7 * 16], ymm8, 1
vextractf128 [rsp + 6 * 16], ymm9, 1
vextractf128 [rsp + 5 * 16], ymm10, 1
vextractf128 [rsp + 4 * 16], ymm11, 1
vextractf128 [rsp + 3 * 16], ymm12, 1
vextractf128 [rsp + 2 * 16], ymm13, 1
vextractf128 [rsp + 16], ymm14, 1
vextractf128 [rsp], ymm15, 1
5:
mov [rsp - 4], eax
sub rsp, 64 // alloc space for ucontext fields
mov rdi, rsp
call {inner}
add rsp, 64
fxrstor64 [rsp + 16 * 16]
cmp byte ptr [rip + {supports_avx}], 0
je 6f
vinsertf128 ymm0, ymm0, [rsp + 15 * 16], 1
vinsertf128 ymm1, ymm1, [rsp + 14 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 13 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 12 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 11 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 10 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 9 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 8 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 7 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 6 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 5 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 4 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 3 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 2 * 16], 1
vinsertf128 ymm2, ymm2, [rsp + 16], 1
vinsertf128 ymm2, ymm2, [rsp], 1
6:
add rsp, (29 + 16) * 16
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rbx
pop r11
pop r10
pop r9
pop r8
pop rax
pop rcx
pop rdx
pop rsi
pop rdi
popfq
pop qword ptr fs:[{tcb_sa_off} + {sa_tmp_rip}]
// x86 lacks atomic instructions for setting both the stack and instruction pointer
// simultaneously, except the slow microcoded IRETQ instruction. Thus, we let the arch_pre
// function emulate atomicity between the pop rsp and indirect jump.
.globl __relibc_internal_sigentry_crit_first
__relibc_internal_sigentry_crit_first:
pop rsp
.globl __relibc_internal_sigentry_crit_second
__relibc_internal_sigentry_crit_second:
jmp qword ptr fs:[{tcb_sa_off} + {sa_tmp_rip}]
7:
// A spurious signal occurred. Signals are still disabled here, but will need to be re-enabled.
// restore flags
mov rax, fs:[0] // load FS base
// TODO: Use lahf/sahf rather than pushfq/popfq?
lea rsp, [rax + {tcb_sc_off} + {sc_saved_rflags}]
popfq
// restore stack
mov rsp, fs:[{tcb_sa_off} + {sa_tmp_rsp}]
// move saved RIP away from control, allowing arch_pre to save us if interrupted.
mov rax, fs:[{tcb_sc_off} + {sc_saved_rip}]
mov fs:[{tcb_sa_off} + {sa_tmp_rip}], rax
// restore regs
mov rax, fs:[{tcb_sa_off} + {sa_tmp_rax}]
mov rdx, fs:[{tcb_sa_off} + {sa_tmp_rdx}]
// Re-enable signals. This code can be interrupted after this signal, so we need to define
// 'crit_third'.
and qword ptr fs:[{tcb_sc_off} + {sc_control}], ~1
.globl __relibc_internal_sigentry_crit_third
__relibc_internal_sigentry_crit_third:
jmp qword ptr fs:[{tcb_sa_off} + {sa_tmp_rip}]
"] <= [
inner = sym inner_c,
sa_tmp_rip = const offset_of!(SigArea, tmp_rip),
sa_tmp_rsp = const offset_of!(SigArea, tmp_rsp),
sa_tmp_rax = const offset_of!(SigArea, tmp_rax),
sa_tmp_rdx = const offset_of!(SigArea, tmp_rdx),
sa_tmp_rdi = const offset_of!(SigArea, tmp_rdi),
sa_tmp_rsi = const offset_of!(SigArea, tmp_rsi),
sa_tmp_r8 = const offset_of!(SigArea, tmp_r8),
sa_tmp_r10 = const offset_of!(SigArea, tmp_r10),
sa_tmp_r12 = const offset_of!(SigArea, tmp_r12),
sa_tmp_rt_inf = const offset_of!(SigArea, tmp_rt_inf),
sa_tmp_id_inf = const offset_of!(SigArea, tmp_id_inf),
sa_altstack_top = const offset_of!(SigArea, altstack_top),
sa_altstack_bottom = const offset_of!(SigArea, altstack_bottom),
sc_saved_rflags = const offset_of!(Sigcontrol, saved_archdep_reg),
sc_saved_rip = const offset_of!(Sigcontrol, saved_ip),
sc_word = const offset_of!(Sigcontrol, word),
sc_sender_infos = const offset_of!(Sigcontrol, sender_infos),
sc_control = const offset_of!(Sigcontrol, control_flags),
tcb_sa_off = const offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, arch),
tcb_sc_off = const offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, control),
pctl_off_actions = const offset_of!(SigProcControl, actions),
pctl_off_pending = const offset_of!(SigProcControl, pending),
pctl_off_sender_infos = const offset_of!(SigProcControl, sender_infos),
pctl = sym PROC_CONTROL_STRUCT,
supports_avx = sym SUPPORTS_AVX,
REDZONE_SIZE = const 128,
STACK_ALIGN = const 16,
SA_ONSTACK_BIT = const 58, // (1 << 58) >> 32 = 0x0400_0000
SYS_CALL = const syscall::SYS_CALL,
proc_call_sigdeq = sym PROC_CALL_SIGDEQ,
RTINF_SIZE = const size_of::<RtSigInfo>(),
proc_fd = sym PROC_FD,
]);
unsafe extern "C" {
fn __relibc_internal_sigentry_crit_first();
fn __relibc_internal_sigentry_crit_second();
fn __relibc_internal_sigentry_crit_third();
}
/// Fixes some edge cases, and calculates the value for uc_stack.
pub unsafe fn arch_pre(stack: &mut SigStack, area: &mut SigArea) -> PosixStackt {
// It is impossible to update RSP and RIP atomically on x86_64, without using IRETQ, which is
// almost as slow as calling a SIGRETURN syscall would be. Instead, we abuse the fact that
// signals are disabled in the prologue of the signal trampoline, which allows us to emulate
// atomicity inside the critical section, consisting of one instruction at 'crit_first', one at
// 'crit_second', and one at 'crit_third', see asm.
if stack.regs.rip == __relibc_internal_sigentry_crit_first as *const () as usize {
// Reexecute pop rsp and jump steps. This case needs to be different from the one below,
// since rsp has not been overwritten with the previous context's stack, just yet. At this
// point, we know [rsp+0] contains the saved RSP, and [rsp-8] contains the saved RIP.
let stack_ptr = stack.regs.rsp as *const usize;
stack.regs.rsp = unsafe { stack_ptr.read() };
stack.regs.rip = unsafe { stack_ptr.sub(1).read() };
} else if stack.regs.rip == __relibc_internal_sigentry_crit_second as *const () as usize
|| stack.regs.rip == __relibc_internal_sigentry_crit_third as *const () as usize
{
// Almost finished, just reexecute the jump before tmp_rip is overwritten by this
// deeper-level signal.
stack.regs.rip = area.tmp_rip;
}
get_sigaltstack(area, stack.regs.rsp).into()
}
/// Rearrange the restore-stack and sigarea in a way that makes it look like a new signal was
/// immediately delivered after restoring the allowset to what it was prior to the original signal delivery.
pub fn arch_ret_to_sig(stack: &mut SigStack, control: &Sigcontrol) {
let orig_rip = core::mem::replace(
&mut stack.regs.rip,
__relibc_internal_sigentry as *const () as usize,
);
control.saved_ip.set(orig_rip);
control.saved_archdep_reg.set(stack.regs.rflags);
}
pub(crate) static SUPPORTS_AVX: AtomicU8 = AtomicU8::new(0);
// __relibc will be prepended to the name, so no_mangle is fine
#[allow(unsafe_op_in_unsafe_fn)]
#[unsafe(no_mangle)]
pub unsafe fn manually_enter_trampoline() {
let c = &Tcb::current().unwrap().os_specific.control;
c.control_flags.store(
c.control_flags.load(Ordering::Relaxed) | syscall::flag::INHIBIT_DELIVERY.bits(),
Ordering::Release,
);
c.saved_archdep_reg.set(0); // TODO: Just reset DF on x86?
core::arch::asm!("
lea rax, [rip + 2f]
mov fs:[{tcb_sc_off} + {sc_saved_rip}], rax
jmp __relibc_internal_sigentry
2:
",
out("rax") _,
tcb_sc_off = const offset_of!(crate::Tcb, os_specific) + offset_of!(RtSigarea, control),
sc_saved_rip = const offset_of!(Sigcontrol, saved_ip),
);
}
/// Get current stack pointer, weak granularity guarantees.
pub fn current_sp() -> usize {
let sp: usize;
unsafe {
core::arch::asm!("mov {}, rsp", out(reg) sp);
}
sp
}
static PROC_CALL_SIGDEQ: u64 = ProcCall::Sigdeq as u64;
pub(crate) static PROC_FD: SyncUnsafeCell<usize> = SyncUnsafeCell::new(usize::MAX);
-366
View File
@@ -1,366 +0,0 @@
#![no_std]
#![allow(internal_features)]
#![deny(unsafe_op_in_unsafe_fn)]
#![feature(core_intrinsics, int_roundings, slice_ptr_get, sync_unsafe_cell)]
#![forbid(unreachable_patterns)]
use core::cell::UnsafeCell;
use generic_rt::GenericTcb;
use redox_protocols::protocol::ProcMeta;
use syscall::Sigcontrol;
use self::{
proc::{FdGuard, FdGuardUpper, STATIC_PROC_INFO},
sync::Mutex,
sys::FdTbl,
};
extern crate alloc;
#[macro_export]
macro_rules! asmfunction(
($name:ident $(($($arg:ty),*))? $(-> $ret:ty)? : [$($asmstmt:expr),*$(,)?] <= [$($decl:ident = $(sym $symname:ident)?$(const $constval:expr)?),*$(,)?]$(,)? ) => {
::core::arch::global_asm!(concat!("
.p2align 4
.section .text.", stringify!($name), ", \"ax\", @progbits
.globl ", stringify!($name), "
.type ", stringify!($name), ", @function
", stringify!($name), ":
", $($asmstmt, "\n",)* "
.size ", stringify!($name), ", . - ", stringify!($name), "
"), $($decl = $(sym $symname)?$(const $constval)?),*);
unsafe extern "C" {
pub fn $name($($(_: $arg),*)?) $(-> $ret)?;
}
}
);
pub mod arch;
pub mod proc;
// TODO: Replace auxvs with a non-stack-based interface, but keep getauxval for compatibility
#[path = "../../src/platform/auxv_defs.rs"]
pub mod auxv_defs;
pub mod signal;
pub mod sync;
pub mod sys;
pub mod thread;
#[derive(Debug, Default)]
pub struct RtTcb {
pub control: Sigcontrol,
pub arch: UnsafeCell<crate::arch::SigArea>,
pub thr_fd: UnsafeCell<Option<FdGuardUpper>>,
}
impl RtTcb {
pub fn current() -> &'static Self {
unsafe { &Tcb::current().unwrap().os_specific }
}
pub fn thread_fd(&self) -> &FdGuardUpper {
unsafe { (&*self.thr_fd.get()).as_ref().unwrap() }
}
}
pub type Tcb = GenericTcb<RtTcb>;
// TODO: Remove this by keeping the TCB initialized during exec
// and informing ld.so through some other way.
pub static TLS_ACTIVATED: core::sync::atomic::AtomicBool =
core::sync::atomic::AtomicBool::new(false);
/// OS and architecture specific code to activate TLS - Redox aarch64
#[allow(unsafe_op_in_unsafe_fn)]
#[cfg(target_arch = "aarch64")]
pub unsafe fn tcb_activate(_tcb: &RtTcb, tls_end: usize, tls_len: usize) {
// Uses ABI page
let abi_ptr = tls_end - tls_len - 16;
core::ptr::write(abi_ptr as *mut usize, tls_end);
core::arch::asm!(
"msr tpidr_el0, {}",
in(reg) abi_ptr,
);
TLS_ACTIVATED.store(true, core::sync::atomic::Ordering::Relaxed);
}
/// OS and architecture specific code to activate TLS - Redox x86
#[allow(unsafe_op_in_unsafe_fn)]
#[cfg(target_arch = "x86")]
pub unsafe fn tcb_activate(tcb: &RtTcb, tls_end: usize, _tls_len: usize) {
let mut env = syscall::EnvRegisters::default();
let file_fd = crate::sys::dup_into_upper_raw(tcb.thread_fd().as_raw_fd(), b"regs/env")
.expect("failed to open handle for process registers");
syscall::read(file_fd, &mut env).expect("failed to read gsbase");
env.gsbase = tls_end as u32;
syscall::write(file_fd, &env).expect("failed to write gsbase");
let _ = crate::sys::close_raw(file_fd);
TLS_ACTIVATED.store(true, core::sync::atomic::Ordering::Relaxed);
}
/// OS and architecture specific code to activate TLS - Redox x86_64
#[allow(unsafe_op_in_unsafe_fn)]
#[cfg(target_arch = "x86_64")]
pub unsafe fn tcb_activate(tcb: &RtTcb, tls_end_and_tcb_start: usize, _tls_len: usize) {
let mut env = syscall::EnvRegisters::default();
let file_fd = crate::sys::dup_into_upper_raw(tcb.thread_fd().as_raw_fd(), b"regs/env")
.expect("failed to open handle for process registers");
syscall::read(file_fd, &mut env).expect("failed to read fsbase");
env.fsbase = tls_end_and_tcb_start as u64;
syscall::write(file_fd, &env).expect("failed to write fsbase");
let _ = crate::sys::close_raw(file_fd);
TLS_ACTIVATED.store(true, core::sync::atomic::Ordering::Relaxed);
}
/// OS and architecture specific code to activate TLS - Redox riscv64
#[allow(unsafe_op_in_unsafe_fn)]
#[cfg(target_arch = "riscv64")]
pub unsafe fn tcb_activate(_tcb: &RtTcb, tls_end: usize, tls_len: usize) {
// tp points to static tls block
// FIXME limited to a single initial master
let tls_start = tls_end - tls_len;
let abi_ptr = tls_start - 8;
core::ptr::write(abi_ptr as *mut usize, tls_end);
core::arch::asm!(
"mv tp, {}",
in(reg) tls_start
);
TLS_ACTIVATED.store(true, core::sync::atomic::Ordering::Relaxed);
}
/// Initialize redox-rt in situations where relibc is not used
#[allow(unsafe_op_in_unsafe_fn)]
#[cfg(not(feature = "proc"))]
pub unsafe fn initialize_freestanding(this_thr_fd: FdGuardUpper) -> &'static FdGuardUpper {
// TODO: This code is a hack! Integrate the ld_so TCB code into generic-rt, and then use that
// (this function will need pointers to the ELF structs normally passed in auxvs), so the TCB
// is initialized properly.
// TODO: TLS
let page = {
&mut *(syscall::fmap(
!0,
&syscall::Map {
offset: 0,
size: syscall::PAGE_SIZE,
flags: syscall::MapFlags::PROT_READ
| syscall::MapFlags::PROT_WRITE
| syscall::MapFlags::MAP_PRIVATE,
address: 0,
},
)
.unwrap() as *mut Tcb)
};
page.tcb_ptr = page;
page.tcb_len = syscall::PAGE_SIZE;
page.tls_end = (page as *mut Tcb).cast();
let cur_filetable_fd = syscall::dup_into(
this_thr_fd.as_raw_fd(),
this_thr_fd.as_raw_fd() + 1,
b"filetable-binary",
)
.expect("failed to open filetable-binary");
*current_filetable() =
FdTbl::from_binary_fd(FdGuard::new(cur_filetable_fd).to_upper().unwrap())
.expect("failed to populate fds");
// Make sure to use ptr::write to prevent dropping the existing FdGuard
page.os_specific.thr_fd.get().write(Some(this_thr_fd));
#[cfg(not(any(target_arch = "aarch64", target_arch = "riscv64")))]
unsafe {
let tcb_addr = page as *mut Tcb as usize;
tcb_activate(&page.os_specific, tcb_addr, 0)
}
#[cfg(target_arch = "aarch64")]
unsafe {
let abi_ptr = core::ptr::addr_of_mut!(page.tcb_ptr);
core::arch::asm!("msr tpidr_el0, {}", in(reg) abi_ptr);
}
#[cfg(target_arch = "riscv64")]
unsafe {
let abi_ptr = core::ptr::addr_of_mut!(page.tcb_ptr) as usize;
core::arch::asm!("mv tp, {}", in(reg) (abi_ptr + 8));
}
TLS_ACTIVATED.store(true, core::sync::atomic::Ordering::Relaxed);
initialize();
(*page.os_specific.thr_fd.get()).as_ref().unwrap()
}
pub(crate) fn read_proc_meta(proc: &FdGuardUpper) -> syscall::Result<ProcMeta> {
let mut bytes = [0_u8; size_of::<ProcMeta>()];
proc.read(&mut bytes)?;
Ok(*plain::from_bytes::<ProcMeta>(&bytes).unwrap())
}
pub unsafe fn initialize(
#[cfg(feature = "proc")] proc_fd: FdGuardUpper,
#[cfg(feature = "proc")] ns_fd: Option<FdGuardUpper>,
) {
#[cfg(feature = "proc")]
let metadata = read_proc_meta(&proc_fd).unwrap();
#[cfg(not(feature = "proc"))]
// Bootstrap mode, don't associate proc fds with PIDs
let metadata = ProcMeta::default();
#[cfg(feature = "proc")]
{
unsafe { crate::arch::PROC_FD.get().write(proc_fd.as_raw_fd()) };
}
unsafe {
STATIC_PROC_INFO.get().write(StaticProcInfo {
pid: metadata.pid,
#[cfg(feature = "proc")]
proc_fd: Some(proc_fd),
#[cfg(not(feature = "proc"))]
proc_fd: None,
})
};
#[cfg(feature = "proc")]
{
*DYNAMIC_PROC_INFO.lock() = DynamicProcInfo {
pgid: metadata.pgid,
ruid: metadata.ruid,
euid: metadata.euid,
suid: metadata.suid,
egid: metadata.egid,
rgid: metadata.rgid,
sgid: metadata.sgid,
ns_fd,
};
}
}
pub(crate) struct StaticProcInfo {
pid: u32,
proc_fd: Option<FdGuardUpper>,
}
pub struct DynamicProcInfo {
pub pgid: u32,
pub euid: u32,
pub suid: u32,
pub ruid: u32,
pub egid: u32,
pub rgid: u32,
pub sgid: u32,
pub ns_fd: Option<FdGuardUpper>,
}
static DYNAMIC_PROC_INFO: Mutex<DynamicProcInfo> = Mutex::new(DynamicProcInfo {
pgid: u32::MAX,
ruid: u32::MAX,
euid: u32::MAX,
suid: u32::MAX,
rgid: u32::MAX,
egid: u32::MAX,
sgid: u32::MAX,
ns_fd: None,
});
#[inline]
pub(crate) fn static_proc_info() -> &'static StaticProcInfo {
unsafe { &*STATIC_PROC_INFO.get() }
}
#[inline]
pub fn current_proc_fd() -> &'static FdGuardUpper {
let info = static_proc_info();
info.proc_fd.as_ref().unwrap()
}
#[inline]
pub fn current_namespace_fd() -> syscall::Result<usize> {
DYNAMIC_PROC_INFO
.lock()
.ns_fd
.as_ref()
.map(|g| g.as_raw_fd())
.ok_or(syscall::Error::new(syscall::ENOENT))
}
struct ChildHookCommonArgs {
new_thr_fd: FdGuard,
new_proc_fd: Option<FdGuard>,
new_filetable_fd: FdGuardUpper,
}
unsafe fn child_hook_common(args: ChildHookCommonArgs) {
let new_filetable_fd = args.new_filetable_fd;
let old_filetable_fd;
{
let mut guard = current_filetable();
old_filetable_fd = guard.take();
guard.set_fd(new_filetable_fd);
guard
.override_at(args.new_thr_fd.as_raw_fd(), args.new_thr_fd.as_raw_fd())
.expect("failed to add new_thr_fd");
if let Some(new_proc_fd) = args.new_proc_fd.as_ref() {
guard
.override_at(new_proc_fd.as_raw_fd(), new_proc_fd.as_raw_fd())
.expect("failed to add new_proc_fd");
}
if let Some(ref old) = old_filetable_fd {
let _ = guard.remove(old.as_raw_fd());
}
}
let new_thr_fd = args.new_thr_fd.to_upper().unwrap();
let new_proc_fd = args.new_proc_fd.map(|x| x.to_upper().unwrap());
// TODO: just pass PID to child rather than obtaining it via IPC?
#[cfg(feature = "proc")]
let metadata = read_proc_meta(
new_proc_fd
.as_ref()
.expect("must be present with proc feature"),
)
.unwrap();
#[cfg(not(feature = "proc"))]
let metadata = ProcMeta::default();
if let Some(proc_fd) = &new_proc_fd {
unsafe { crate::arch::PROC_FD.get().write(proc_fd.as_raw_fd()) };
}
let old_proc_fd = unsafe {
STATIC_PROC_INFO
.get()
.replace(StaticProcInfo {
pid: metadata.pid,
proc_fd: new_proc_fd,
})
.proc_fd
};
drop(old_proc_fd);
let old_thr_fd = unsafe { RtTcb::current().thr_fd.get().replace(Some(new_thr_fd)) };
drop(old_thr_fd);
drop(old_filetable_fd);
}
static FILETABLE: Mutex<FdTbl> = Mutex::new(FdTbl::new());
#[inline]
pub fn current_filetable() -> crate::sync::MutexGuard<'static, FdTbl> {
FILETABLE.lock()
}
-1285
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-68
View File
@@ -1,68 +0,0 @@
// TODO: Share code for simple futex-based mutex between relibc's Mutex<()> and this.
use core::{
cell::UnsafeCell,
ops::{Deref, DerefMut},
sync::atomic::{AtomicU32, Ordering},
};
pub struct Mutex<T> {
pub lockword: AtomicU32,
pub inner: UnsafeCell<T>,
}
unsafe impl<T: Send> Send for Mutex<T> {}
unsafe impl<T: Send> Sync for Mutex<T> {}
impl<T> Mutex<T> {
/// Represents an unlocked [Mutex].
pub const UNLOCKED: u32 = 0;
/// Represents a locked [Mutex].
pub const LOCKED: u32 = 1;
/// Represents a waiting [Mutex].
pub const WAITING: u32 = 2;
pub const fn new(t: T) -> Self {
Self {
lockword: AtomicU32::new(0),
inner: UnsafeCell::new(t),
}
}
pub fn lock(&self) -> MutexGuard<'_, T> {
while self
.lockword
.compare_exchange(
Self::UNLOCKED,
Self::LOCKED,
Ordering::Acquire,
Ordering::Relaxed,
)
.is_err()
{
core::hint::spin_loop();
}
MutexGuard { lock: self }
}
}
pub struct MutexGuard<'l, T> {
lock: &'l Mutex<T>,
}
impl<T> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.inner.get() }
}
}
impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.inner.get() }
}
}
impl<T> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
self.lock
.lockword
.store(Mutex::<T>::UNLOCKED, Ordering::Release);
}
}
-2048
View File
File diff suppressed because it is too large Load Diff
-76
View File
@@ -1,76 +0,0 @@
use core::mem::size_of;
use syscall::Result;
use crate::{RtTcb, arch::*, proc::*, static_proc_info};
/// Spawns a new context sharing the same address space as the current one (i.e. a new thread).
pub unsafe fn rlct_clone_impl(stack: *mut usize, tcb: &RtTcb) -> Result<usize> {
let proc_info = static_proc_info();
let cur_proc_fd = proc_info.proc_fd.as_ref().unwrap();
let cur_thr_fd = RtTcb::current().thread_fd();
let new_thr_fd = cur_proc_fd.dup_into_upper(b"new-thread")?;
// Inherit existing address space
{
let cur_addr_space_fd = cur_thr_fd.dup_into_upper(b"addrspace")?;
let new_addr_space_sel_fd = new_thr_fd.dup_into_upper(b"current-addrspace")?;
let buf = create_set_addr_space_buf(
cur_addr_space_fd.as_raw_fd(),
__relibc_internal_rlct_clone_ret as *const () as usize,
stack as usize,
);
new_addr_space_sel_fd.write(&buf)?;
}
// Inherit reference to file table
{
let cur_filetable_fd = cur_thr_fd.dup_into_upper(b"filetable")?;
let new_filetable_sel_fd = new_thr_fd.dup_into_upper(b"current-filetable")?;
new_filetable_sel_fd.write(&usize::to_ne_bytes(cur_filetable_fd.as_raw_fd()))?;
}
// Since the signal handler is not yet initialized, signals specifically targeting the thread
// (relibc is only required to implement thread-specific signals that already originate from
// the same process) will be discarded. Process-specific signals will ignore this new thread,
// until it has initialized its own signal handler.
let start_fd = new_thr_fd.dup_into_upper(b"start")?;
let fd = new_thr_fd.as_raw_fd();
unsafe {
tcb.thr_fd.get().write(Some(new_thr_fd));
}
// Unblock context.
start_fd.write(&[0])?;
Ok(fd)
}
pub unsafe fn exit_this_thread(stack_base: *mut (), stack_size: usize) -> ! {
let _guard = crate::signal::tmp_disable_signals();
let thread_fd = RtTcb::current().thread_fd();
// TODO: modify interface so it writes directly to the thread fd?
let status_fd = thread_fd.dup_into_upper(b"status").unwrap();
unsafe { exit_this_thread_inner(stack_base, stack_size, status_fd) }
}
/// exit_this_thread, but current thread_fd might has disappear
pub unsafe fn exit_this_thread_inner(
stack_base: *mut (),
stack_size: usize,
status_fd: FdGuard<true>,
) -> ! {
let mut buf = [0; size_of::<usize>() * 3];
plain::slice_from_mut_bytes(&mut buf)
.unwrap()
.copy_from_slice(&[usize::MAX, stack_base as usize, stack_size]);
// TODO: SYS_CALL w/CONSUME
status_fd.write(&buf).unwrap();
unreachable!()
}
-58
View File
@@ -1,58 +0,0 @@
#!/usr/bin/env bash
set -e
target=$1
deps_dir=$2
if [ -z "$target" ] || [ -z "$deps_dir" ]; then
echo "Usage:\n\t./renamesyms.sh TARGET DEPS_DIR"
exit 1
fi
if [ ! -f "$target" ]; then
echo "Target file '$target' does not exist"
exit 1
fi
if [ ! -d "$deps_dir" ] ; then
echo "Deps dir '$deps_dir' does not exist or not a directory"
exit 1
fi
symbols_file=`mktemp`
special_syms=(
__rdl_oom
__rg_alloc
__rg_alloc_zeroed
__rg_dealloc
__rg_oom
__rg_realloc
__rust_alloc
__rust_alloc_error_handler
__rust_alloc_error_handler_should_panic
__rust_alloc_zeroed
__rust_dealloc
__rust_no_alloc_shim_is_unstable
__rust_realloc
)
for dep in `find $deps_dir -type f -name "*.rlib"`; do
"${NM}" --format=posix -g "$dep" 2>/dev/null | sed 's/.*:.*//g' | awk '{if ($2 == "T") print $1}' | sed 's/^\(.*\)$/\1 __relibc_\1/g' >> $symbols_file
done
for special_sym in "${special_syms[@]}"; do
echo "$special_sym __relibc_$special_sym" >> $symbols_file
done
mangled_alloc_syms=$("${NM}" --format=posix -g "$target" 2>/dev/null | awk '{print $1}' | grep "7___rustc" || true)
for sym in $mangled_alloc_syms; do
echo "$sym __relibc_$sym" >> $symbols_file
done
sorted_file=`mktemp`
sort -u "$symbols_file" > "$sorted_file"
rm -f "$symbols_file"
"${OBJCOPY}" --redefine-syms="$sorted_file" "$target"
rm -f "$sorted_file"
-3
View File
@@ -1,3 +0,0 @@
[toolchain]
channel = "nightly-2026-05-24"
components = ["rust-src"]
-21
View File
@@ -1,21 +0,0 @@
blank_lines_lower_bound = 0
blank_lines_upper_bound = 1
brace_style = "SameLineWhere"
disable_all_formatting = false
edition = "2024"
empty_item_single_line = true
fn_single_line = false
force_explicit_abi = true
format_strings = false
hard_tabs = false
imports_granularity = "Crate"
imports_indent = "Block"
imports_layout = "Mixed"
indent_style = "Block"
max_width = 100
newline_style = "Unix"
show_parse_errors = true
skip_children = false
tab_spaces = 4
trailing_comma = "Vertical"
where_single_line = false
-36
View File
@@ -1,36 +0,0 @@
use crate::platform::types::c_char;
/// An abstraction over a byte literal to provide a method to convert safely
/// to a `c_char`.
///
/// The abstraction is required so we can contain architecture specific code
/// in a central location.
pub struct ByteLiteral;
impl ByteLiteral {
/// Casts a byte literal (`u8`) to a `c_char` without using `as`.
///
/// # Panics
/// If `input` is not within the following range of ascii characters:
/// - Octal: `040`..=`176`
/// - Decimal: `30`..=`126`
/// - Hexadecimal: `20`..=`7E`
/// - Byte literals: The space character (` `) upto and including tilde (`~`)
pub const fn cast_cchar(input: u8) -> c_char {
match input {
b' '..=b'~' => {
// `c_char` is an `i8` on these arches
#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
{
input.cast_signed()
}
// `c_char` is already a `u8` on these arches
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
{
input
}
}
_ => panic!("Not a printable ascii character!"),
}
}
}
-13
View File
@@ -1,13 +0,0 @@
double strtod(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr) {
return (long double)strtod(nptr, endptr);
}
double relibc_ldtod(const long double* val) {
return (double)(*val);
}
void relibc_dtold(double val, long double* out) {
*out = (long double)val;
}
-326
View File
@@ -1,326 +0,0 @@
//! Nul-terminated byte strings.
use core::{marker::PhantomData, ptr::NonNull, str::Utf8Error};
use alloc::{borrow::Cow, string::String};
use crate::platform::types::{c_char, wchar_t};
mod private {
pub trait Sealed {}
}
#[derive(Clone, Copy, Debug)]
pub enum Thin {}
#[derive(Clone, Copy, Debug)]
pub enum Wide {}
impl private::Sealed for Thin {}
impl private::Sealed for Wide {}
pub trait Kind: private::Sealed + Copy + 'static {
/// c_char or wchar_t
type C: Copy + 'static;
// u8 or u32
type Char: Copy + From<u8> + Into<u32> + PartialEq + 'static;
const NUL: Self::Char;
const IS_THIN_NOT_WIDE: bool;
fn r2c(c: Self::Char) -> Self::C;
fn c2r(c: Self::C) -> Self::Char;
fn chars_from_bytes(b: &[u8]) -> Option<&[Self::Char]>;
fn chars_to_bytes(c: &[Self::Char]) -> Option<&[u8]>;
unsafe fn strlen(s: *const Self::C) -> usize;
unsafe fn strchr(s: *const Self::C, c: Self::C) -> *const Self::C;
unsafe fn strchrnul(s: *const Self::C, c: Self::C) -> *const Self::C;
}
impl Kind for Thin {
type C = c_char;
type Char = u8;
const NUL: Self::Char = 0;
const IS_THIN_NOT_WIDE: bool = true;
unsafe fn strlen(s: *const c_char) -> usize {
unsafe { crate::header::string::strlen(s) }
}
unsafe fn strchr(s: *const c_char, c: c_char) -> *const c_char {
unsafe { crate::header::string::strchr(s, c.into()) }
}
unsafe fn strchrnul(s: *const c_char, c: c_char) -> *const c_char {
unsafe { crate::header::string::strchrnul(s, c.into()) }
}
fn r2c(c: u8) -> c_char {
c as _
}
fn c2r(c: c_char) -> u8 {
c as _
}
fn chars_from_bytes(b: &[u8]) -> Option<&[Self::Char]> {
Some(b)
}
fn chars_to_bytes(c: &[Self::Char]) -> Option<&[u8]> {
Some(c)
}
}
impl Kind for Wide {
type C = wchar_t;
type Char = u32;
const NUL: Self::Char = 0;
const IS_THIN_NOT_WIDE: bool = false;
unsafe fn strlen(s: *const Self::C) -> usize {
unsafe { crate::header::wchar::wcslen(s) }
}
unsafe fn strchr(s: *const Self::C, c: Self::C) -> *const Self::C {
unsafe { crate::header::wchar::wcschr(s, c) }
}
unsafe fn strchrnul(mut s: *const Self::C, c: Self::C) -> *const Self::C {
// TODO: optimized function
while unsafe { s.read() } != c && unsafe { s.read() } != 0 {
s = unsafe { s.add(1) };
}
s
}
fn r2c(c: Self::Char) -> Self::C {
c as _
}
fn c2r(c: Self::C) -> Self::Char {
c as _
}
fn chars_from_bytes(b: &[u8]) -> Option<&[Self::Char]> {
None
}
fn chars_to_bytes(c: &[Self::Char]) -> Option<&[u8]> {
None
}
}
/// Safe wrapper for immutable borrowed C strings, guaranteed to be the same layout as `*const u8`.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct NulStr<'a, T: Kind> {
ptr: NonNull<T::C>,
_marker: PhantomData<&'a [u8]>,
}
pub type CStr<'a> = NulStr<'a, Thin>;
pub type WStr<'a> = NulStr<'a, Wide>;
impl<'a, T: Kind> NulStr<'a, T> {
/// Safety
///
/// The ptr must be valid up to and including the first NUL byte from the base ptr.
pub const unsafe fn from_ptr(ptr: *const T::C) -> Self {
Self {
ptr: unsafe { NonNull::new_unchecked(ptr.cast_mut()) },
_marker: PhantomData,
}
}
pub unsafe fn from_nullable_ptr(ptr: *const T::C) -> Option<Self> {
if ptr.is_null() {
None
} else {
Some(unsafe { Self::from_ptr(ptr) })
}
}
/// Look for the closest occurence of `c`, and if found, split the string into a slice up to
/// that byte and a `CStr` starting at that byte.
#[inline]
#[doc(alias = "strchrnul")]
pub fn find_get_subslice_or_all(
self,
c: impl Into<T::Char>,
) -> Result<(&'a [T::Char], Self), (&'a [T::Char], Self)> {
let c = c.into();
// SAFETY: strchrnul expects self.as_ptr() to be valid up to and including its last NUL
// byte
let found = unsafe { T::strchrnul(self.as_ptr(), T::r2c(c)) };
// SAFETY: the pointer returned from strchrnul is always a substring of this string, and
// hence always valid as a CStr.
let found = unsafe { Self::from_ptr(found) };
let until = unsafe { self.slice_until_substr(found) };
if found.first() == T::NUL {
// The character was not found, and we got the end of the string instead.
Err((until, found))
} else {
Ok((until, found))
}
}
/// # Safety
///
/// `substr` must be contained within `self`
#[inline]
pub unsafe fn slice_until_substr(self, substr: NulStr<'_, T>) -> &'a [T::Char] {
let index = unsafe {
// SAFETY: the sub-pointer as returned by strchr must be derived from the same
// allocation
substr.as_ptr().offset_from(self.as_ptr()) as usize
};
unsafe { core::slice::from_raw_parts(self.as_ptr().cast::<T::Char>(), index) }
}
/// Look for the closest occurence of `c`, and if found, split the string into a slice up to
/// that byte and a `CStr` starting at that byte.
#[inline]
pub fn find_get_subslice(self, c: T::Char) -> Option<(&'a [T::Char], Self)> {
let rest = self.find(c)?;
// SAFETY: the output of strchr is obviously a substring if it doesn't return NULL
Some((unsafe { self.slice_until_substr(rest) }, rest))
}
/// Look for the closest occurence of `c`, and return a new string starting at that byte if
/// found.
#[doc(alias = "strchr")]
#[doc(alias = "wcschr")]
#[inline]
pub fn find(self, c: T::Char) -> Option<Self> {
unsafe {
// SAFETY: the only requirement is for self.as_ptr() to be valid up to and including
// the nearest NUL byte, which this type requires
let ret = T::strchr(self.as_ptr(), T::r2c(c));
// SAFETY: strchr must either return NULL (not found) or a substring of self, which can
// never exceed the nearest NUL byte of self
Self::from_nullable_ptr(ret)
}
}
// TODO: strrchr, strchrnul wrappers
#[inline]
pub fn contains(self, c: T::Char) -> bool {
self.find(c).is_some()
}
#[inline]
pub fn first(self) -> T::Char {
unsafe {
// SAFETY: Self must be valid up to and including its nearest NUL byte, which certainly
// implies its readable length is nonzero (string is empty if this first byte is 0).
T::c2r(self.ptr.read())
}
}
#[inline]
pub fn first_char(self) -> Option<char> {
char::from_u32(self.first().into())
}
/// Same as `split_first` except also requires that the first char be convertible into `char`
#[inline]
pub fn split_first_char(self) -> Option<(char, Self)> {
self.split_first()
.and_then(|(c, r)| Some((char::from_u32(c.into())?, r)))
}
/// Split this string into `Some((first_byte, string_after_that))` or `None` if empty.
#[inline]
pub fn split_first(self) -> Option<(T::Char, Self)> {
if self.first() == T::NUL {
return None;
}
Some((self.first(), unsafe {
Self::from_ptr(self.as_ptr().add(1))
}))
}
pub fn to_chars_with_nul(self) -> &'a [T::Char] {
unsafe {
// SAFETY: The string must be valid at least until (and including) the NUL byte.
let len = T::strlen(self.ptr.as_ptr());
core::slice::from_raw_parts(self.ptr.as_ptr().cast(), len + 1)
}
}
pub fn to_chars(self) -> &'a [T::Char] {
let s = self.to_chars_with_nul();
&s[..s.len() - 1]
}
pub const fn as_ptr(self) -> *const T::C {
self.ptr.as_ptr()
}
pub const unsafe fn from_chars_with_nul_unchecked(chars: &'a [T::Char]) -> Self {
unsafe { Self::from_ptr(chars.as_ptr().cast()) }
}
pub fn from_chars_with_nul(chars: &'a [T::Char]) -> Result<Self, FromCharsWithNulError> {
if chars.last() != Some(&T::NUL) || chars[..chars.len() - 1].contains(&T::NUL) {
return Err(FromCharsWithNulError);
}
Ok(unsafe { Self::from_chars_with_nul_unchecked(chars) })
}
pub fn from_chars_until_nul(chars: &'a [T::Char]) -> Result<Self, FromCharsUntilNulError> {
if !chars.contains(&T::NUL) {
return Err(FromCharsUntilNulError);
}
Ok(unsafe { Self::from_chars_with_nul_unchecked(chars) })
}
/// Scan the string to get its length.
#[doc(alias = "strlen")]
#[doc(alias = "wcslen")]
#[expect(clippy::len_without_is_empty, reason = "len() signature intentional")]
pub fn len(self) -> usize {
self.to_chars().len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.first() == T::NUL
}
}
impl<'a> CStr<'a> {
pub fn to_owned_cstring(self) -> CString {
CString::from(self.to_cstr())
}
pub fn borrow(string: &'a CString) -> Self {
unsafe { Self::from_ptr(string.as_ptr()) }
}
#[inline]
pub fn to_bytes(self) -> &'a [u8] {
self.to_chars()
}
#[inline]
pub fn to_bytes_with_nul(self) -> &'a [u8] {
self.to_chars_with_nul()
}
pub fn to_str(self) -> Result<&'a str, Utf8Error> {
core::str::from_utf8(self.to_bytes())
}
pub fn to_cstr(self) -> &'a core::ffi::CStr {
unsafe { core::ffi::CStr::from_ptr(self.ptr.as_ptr()) }
}
pub fn to_string_lossy(self) -> Cow<'a, str> {
String::from_utf8_lossy(self.to_bytes())
}
#[inline]
pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &'a [u8]) -> Self {
unsafe { Self::from_chars_with_nul_unchecked(bytes) }
}
#[inline]
pub fn from_bytes_with_nul(bytes: &'a [u8]) -> Result<Self, FromCharsWithNulError> {
Self::from_chars_with_nul(bytes)
}
#[inline]
pub fn from_bytes_until_nul(bytes: &'a [u8]) -> Result<Self, FromCharsUntilNulError> {
Self::from_chars_until_nul(bytes)
}
}
unsafe impl<T: Kind> Send for NulStr<'_, T> {}
unsafe impl<T: Kind> Sync for NulStr<'_, T> {}
impl From<&core::ffi::CStr> for CStr<'_> {
fn from(s: &core::ffi::CStr) -> Self {
// SAFETY:
// * We can assume that `s` is valid because the caller should have upheld its
// safety concerns when constructing it.
unsafe { Self::from_ptr(s.as_ptr()) }
}
}
#[derive(Debug)]
pub struct FromCharsWithNulError;
#[derive(Debug)]
pub struct FromCharsUntilNulError;
pub use alloc::ffi::CString;
-294
View File
@@ -1,294 +0,0 @@
//! Equivalent of Rust's `Vec<T>`, but using relibc's own allocator.
use crate::{
io::{self, Write},
platform::{self, WriteByte, types::*},
};
use core::{
cmp, fmt,
iter::IntoIterator,
mem,
ops::{Deref, DerefMut},
ptr::{self, NonNull},
slice,
};
/// Error that occurs when an allocation fails
#[derive(Debug, Default, Hash, PartialEq, Eq, Clone, Copy)]
pub struct AllocError;
/// A normal vector allocated in Rust needs to be dropped from Rust
/// too, in order to avoid UB. This CVec is an abstraction that works
/// using only C allocations functions and can therefore be dropped
/// from C. Just like the Rust Vec, this does bounds checks to assure
/// you never reach isize::MAX. Unless you need to drop something from
/// C, prefer Rust's builtin Vec.
pub struct CVec<T> {
ptr: NonNull<T>,
len: usize,
cap: usize,
}
impl<T> CVec<T> {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
ptr: NonNull::dangling(),
len: 0,
cap: 0,
}
}
fn check_bounds(i: usize) -> Result<usize, AllocError> {
if i > isize::MAX as usize {
Err(AllocError)
} else {
Ok(i)
}
}
fn check_mul(x: usize, y: usize) -> Result<usize, AllocError> {
x.checked_mul(y)
.ok_or(AllocError)
.and_then(Self::check_bounds)
}
pub fn with_capacity(cap: usize) -> Result<Self, AllocError> {
if cap == 0 {
return Ok(Self::new());
}
let size = Self::check_mul(cap, mem::size_of::<T>())?;
let ptr = NonNull::new(unsafe { platform::alloc(size).cast::<T>() }).ok_or(AllocError)?;
Ok(Self { ptr, len: 0, cap })
}
unsafe fn resize(&mut self, cap: usize) -> Result<(), AllocError> {
let size = Self::check_mul(cap, mem::size_of::<T>())?;
let ptr = if cap == 0 {
NonNull::dangling()
} else if self.cap > 0 {
NonNull::new(
unsafe { platform::realloc(self.ptr.as_ptr().cast::<c_void>(), size) }.cast::<T>(),
)
.ok_or(AllocError)?
} else {
NonNull::new((unsafe { platform::alloc(size) }).cast::<T>()).ok_or(AllocError)?
};
self.ptr = ptr;
self.cap = cap;
Ok(())
}
unsafe fn drop_range(&mut self, start: usize, end: usize) {
let mut start = unsafe { self.ptr.as_ptr().add(start) };
let end = unsafe { self.ptr.as_ptr().add(end) };
while start < end {
unsafe { ptr::drop_in_place(start) };
start = unsafe { start.add(1) };
}
}
// Push stuff
pub fn reserve(&mut self, required: usize) -> Result<(), AllocError> {
let required_len = self
.len
.checked_add(required)
.ok_or(AllocError)
.and_then(Self::check_bounds)?;
if required_len > self.cap {
let new_cap = cmp::min(required_len.next_power_of_two(), isize::MAX as usize);
unsafe {
self.resize(new_cap)?;
}
}
Ok(())
}
pub fn push(&mut self, elem: T) -> Result<(), AllocError> {
self.reserve(1)?;
unsafe {
ptr::write(self.ptr.as_ptr().add(self.len), elem);
}
self.len += 1; // no need to bounds check, as new len <= cap
Ok(())
}
pub fn extend_from_slice(&mut self, elems: &[T]) -> Result<(), AllocError>
where
T: Copy,
{
self.reserve(elems.len())?;
unsafe {
ptr::copy_nonoverlapping(elems.as_ptr(), self.ptr.as_ptr().add(self.len), elems.len());
}
self.len += elems.len(); // no need to bounds check, as new len <= cap
Ok(())
}
pub fn append(&mut self, other: &mut Self) -> Result<(), AllocError> {
let len = other.len;
other.len = 0; // move
self.reserve(len)?;
unsafe {
ptr::copy_nonoverlapping(other.as_ptr(), self.ptr.as_ptr().add(self.len), len);
}
self.len += other.len(); // no need to bounds check, as new len <= cap
Ok(())
}
// Pop stuff
pub fn truncate(&mut self, len: usize) {
if len < self.len {
unsafe {
let old_len = self.len;
self.drop_range(len, old_len);
}
self.len = len;
}
}
pub fn shrink_to_fit(&mut self) -> Result<(), AllocError> {
if self.len < self.cap {
unsafe {
let new_cap = self.len;
self.resize(new_cap)?;
}
}
Ok(())
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
None
} else {
let elem = unsafe { ptr::read(self.as_ptr().add(self.len - 1)) };
self.len -= 1;
Some(elem)
}
}
// Misc stuff
pub fn capacity(&self) -> usize {
self.cap
}
pub fn as_ptr(&self) -> *const T {
self.ptr.as_ptr()
}
pub fn as_mut_ptr(&mut self) -> *mut T {
self.ptr.as_ptr()
}
/// Leaks the inner data. This is safe to drop from C!
pub fn leak(mut self) -> *mut T {
let ptr = self.as_mut_ptr();
mem::forget(self);
ptr
}
}
impl<T> Deref for CVec<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
}
}
impl<T> DerefMut for CVec<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
}
}
impl<T> Drop for CVec<T> {
fn drop(&mut self) {
unsafe {
let len = self.len;
self.drop_range(0, len);
}
}
}
impl<'a, T> IntoIterator for &'a CVec<T> {
type Item = <&'a [T] as IntoIterator>::Item;
type IntoIter = <&'a [T] as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
<&[T]>::into_iter(self)
}
}
impl<'a, T> IntoIterator for &'a mut CVec<T> {
type Item = <&'a mut [T] as IntoIterator>::Item;
type IntoIter = <&'a mut [T] as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
<&mut [T]>::into_iter(&mut *self)
}
}
impl Write for CVec<u8> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.extend_from_slice(buf).map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
"AllocStringWriter::write failed to allocate",
)
})?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl fmt::Write for CVec<u8> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write(s.as_bytes()).map_err(|_| fmt::Error)?;
Ok(())
}
}
impl WriteByte for CVec<u8> {
fn write_u8(&mut self, byte: u8) -> fmt::Result {
self.write(&[byte]).map_err(|_| fmt::Error)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::CVec;
#[test]
fn push_pop() {
let mut vec = CVec::new();
vec.push(1).unwrap();
vec.push(2).unwrap();
vec.push(3).unwrap();
assert_eq!(&vec[..], &[1, 2, 3]);
assert_eq!(vec.pop().unwrap(), 3);
assert_eq!(&vec[..], &[1, 2]);
}
#[test]
fn extend_from_slice() {
use crate::io::Write;
let mut vec = CVec::new();
vec.extend_from_slice(&[1, 2, 3]).unwrap();
vec.extend_from_slice(&[4, 5, 6]).unwrap();
assert_eq!(&vec[..], &[1, 2, 3, 4, 5, 6]);
assert_eq!(vec.write(&[7, 8, 9]).unwrap(), 3);
assert_eq!(&vec[..], &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
#[test]
fn dropped() {
use alloc::rc::Rc;
let counter = Rc::new(());
let mut vec = CVec::with_capacity(3).unwrap();
vec.push(Rc::clone(&counter)).unwrap();
vec.push(Rc::clone(&counter)).unwrap();
vec.push(Rc::clone(&counter)).unwrap();
assert_eq!(Rc::strong_count(&counter), 4);
let popped = vec.pop().unwrap();
assert_eq!(Rc::strong_count(&counter), 4);
drop(popped);
assert_eq!(Rc::strong_count(&counter), 3);
vec.push(Rc::clone(&counter)).unwrap();
vec.push(Rc::clone(&counter)).unwrap();
vec.push(Rc::clone(&counter)).unwrap();
assert_eq!(vec.len(), 5);
assert_eq!(Rc::strong_count(&counter), 6);
vec.truncate(1);
assert_eq!(Rc::strong_count(&counter), 2);
drop(vec);
assert_eq!(Rc::strong_count(&counter), 1);
}
}
-12
View File
@@ -1,12 +0,0 @@
[package]
name = "crt0"
version = "0.1.0"
authors = ["Jeremy Soller <jackpot51@gmail.com>"]
edition = "2024"
[lib]
name = "crt0"
crate-type = ["staticlib"]
[lints]
workspace = true
-105
View File
@@ -1,105 +0,0 @@
//! crt0
#![no_std]
#![feature(linkage)]
use core::{
arch::global_asm,
ffi::{c_char, c_int},
};
#[cfg(target_arch = "aarch64")]
global_asm!(
"
.globl _start
_start:
mov x0, sp
and sp, x0, #0xfffffffffffffff0 //align sp
bl relibc_crt0
"
);
#[cfg(target_arch = "x86")]
global_asm!(
"
.globl _start
.type _start, @function
_start:
sub esp, 8
mov DWORD PTR [esp], 0x00001F80
# ldmxcsr [esp]
mov WORD PTR [esp], 0x037F
fldcw [esp]
add esp, 8
push esp
call relibc_crt0
.size _start, . - _start
"
);
#[cfg(target_arch = "x86_64")]
global_asm!(
"
.globl _start
.type _start, @function
_start:
mov rdi, rsp
and rsp, 0xFFFFFFFFFFFFFFF0
sub rsp, 8
mov DWORD PTR [rsp], 0x00001F80
ldmxcsr [rsp]
mov WORD PTR [rsp], 0x037F
fldcw [rsp]
add rsp, 8
call relibc_crt0
.size _start, . - _start
"
);
#[cfg(target_arch = "riscv64")]
global_asm!(
"
.globl _start
_start:
mv a0, sp
la t0, relibc_crt0
jalr ra, t0
"
);
#[unsafe(no_mangle)]
pub unsafe extern "C" fn relibc_crt0(sp: usize) -> ! {
// This wrapper ensures a dynamic libc.so can access a hidden main function
//TODO: common definition of types
unsafe extern "C" {
fn main(argc: isize, argv: *mut *mut c_char, envp: *mut *mut c_char) -> c_int;
fn relibc_start_v1(
sp: usize,
main: unsafe extern "C" fn(
argc: isize,
argv: *mut *mut c_char,
envp: *mut *mut c_char,
) -> c_int,
) -> !;
}
unsafe { relibc_start_v1(sp, main) }
}
#[linkage = "weak"]
#[unsafe(no_mangle)]
pub extern "C" fn relibc_panic(_pi: &::core::panic::PanicInfo) -> ! {
loop {}
}
#[panic_handler]
#[linkage = "weak"]
pub unsafe fn rust_begin_unwind(pi: &::core::panic::PanicInfo) -> ! {
relibc_panic(pi)
}
-8
View File
@@ -1,8 +0,0 @@
[package]
name = "crti"
version = "0.1.0"
authors = ["jD91mZM2 <me@krake.one>"]
edition = "2024"
[lints]
workspace = true
-3
View File
@@ -1,3 +0,0 @@
#![no_std]
// we don't support _init/_fini functions, only init/fini arrays
-8
View File
@@ -1,8 +0,0 @@
[package]
name = "crtn"
version = "0.1.0"
authors = ["jD91mZM2 <me@krake.one>"]
edition = "2024"
[lints]
workspace = true
-3
View File
@@ -1,3 +0,0 @@
#![no_std]
// we don't support _init/_fini functions, only init/fini arrays
-103
View File
@@ -1,103 +0,0 @@
use crate::platform::types::{c_int, c_void};
use alloc::vec::Vec;
use core::cell::RefCell;
use spin::Mutex;
#[derive(Clone, Copy)]
struct CxaAtExitFunc {
func: extern "C" fn(*mut c_void),
arg: usize,
dso: usize,
}
#[derive(Clone, Copy)]
struct CxaThreadAtExitFunc {
func: extern "C" fn(*mut c_void),
obj: *mut c_void,
dso: *mut c_void,
}
static CXA_ATEXIT_FUNCS: Mutex<Vec<Option<CxaAtExitFunc>>> = Mutex::new(Vec::new());
#[thread_local]
static DTORS: RefCell<Vec<CxaThreadAtExitFunc>> = RefCell::new(Vec::new());
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __cxa_atexit(
func: Option<extern "C" fn(*mut c_void)>,
arg: *mut c_void,
dso: *mut c_void,
) -> c_int {
let Some(func) = func else {
return 0;
};
let entry = CxaAtExitFunc {
func,
arg: arg as usize,
dso: dso as usize,
};
let mut funcs = CXA_ATEXIT_FUNCS.lock();
for slot in funcs.iter_mut() {
if slot.is_none() {
*slot = Some(entry);
return 0;
}
}
// No empty slots
funcs.push(Some(entry));
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __cxa_finalize(dso: *mut c_void) {
let mut funcs = CXA_ATEXIT_FUNCS.lock();
let dso_usize = dso as usize;
for slot in funcs.iter_mut().rev() {
if let Some(entry) = slot.as_ref()
&& (dso.is_null() || entry.dso == dso_usize)
&& let Some(entry_to_run) = slot.take()
{
(entry_to_run.func)(entry_to_run.arg as *mut c_void);
}
}
// clean up remaining list
if dso.is_null() {
funcs.clear();
} else {
funcs.retain(|opt| opt.is_some());
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __cxa_thread_atexit_impl(
func: extern "C" fn(*mut c_void),
obj: *mut c_void,
dso: *mut c_void,
) {
let entry = CxaThreadAtExitFunc { func, obj, dso };
DTORS.borrow_mut().push(entry);
}
// called internally
pub unsafe fn __cxa_thread_finalize() {
let mut dtors = DTORS.borrow_mut();
while let Some(entry) = dtors.pop() {
(entry.func)(entry.obj);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn _ITM_deregisterTMCloneTable(_ptr: *mut c_void) {
// No-op
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn _ITM_registerTMCloneTable(_ptr: *mut c_void, _len: usize) {
// No-op
}
-51
View File
@@ -1,51 +0,0 @@
use alloc::{string::String, vec::Vec};
use crate::{
c_str::CStr,
fs::File,
header::fcntl,
io::{self, BufRead, BufReader},
};
pub enum Separator {
Character(char),
Whitespace,
}
pub struct Db<R: BufRead> {
reader: R,
separator: Separator,
}
impl<R: BufRead> Db<R> {
pub fn new(reader: R, separator: Separator) -> Self {
Db { reader, separator }
}
pub fn read(&mut self) -> io::Result<Option<Vec<String>>> {
let mut line = String::new();
if self.reader.read_line(&mut line)? == 0 {
return Ok(None);
}
let vec = if let Some(not_comment) = line.trim().split('#').next() {
match self.separator {
Separator::Character(c) => not_comment.split(c).map(String::from).collect(),
Separator::Whitespace => not_comment.split_whitespace().map(String::from).collect(),
}
} else {
Vec::new()
};
Ok(Some(vec))
}
}
pub type FileDb = Db<BufReader<File>>;
impl FileDb {
pub fn open(path: CStr, separator: Separator) -> io::Result<Self> {
let file = File::open(path, fcntl::O_RDONLY | fcntl::O_CLOEXEC)?;
Ok(Db::new(BufReader::new(file), separator))
}
}
-90
View File
@@ -1,90 +0,0 @@
use alloc::boxed::Box;
use crate::{header::errno::STR_ERROR, platform::types::c_int};
/// Positive error codes (EINVAL, not -EINVAL).
#[derive(Debug, Eq, PartialEq)]
// TODO: Move to a more generic place.
pub struct Errno(pub c_int);
impl Errno {
pub fn sync(self) -> Self {
crate::platform::ERRNO.set(self.0);
self
}
}
pub type Result<T, E = Errno> = core::result::Result<T, E>;
#[cfg(target_os = "redox")]
impl From<syscall::Error> for Errno {
#[inline]
fn from(value: syscall::Error) -> Self {
Errno(value.errno)
}
}
#[cfg(target_os = "redox")]
impl From<Errno> for syscall::Error {
#[inline]
fn from(value: Errno) -> Self {
syscall::Error::new(value.0)
}
}
impl From<Errno> for crate::io::Error {
#[inline]
fn from(Errno(errno): Errno) -> Self {
Self::from_raw_os_error(errno)
}
}
// TODO: core::error::Error
impl core::fmt::Display for Errno {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match usize::try_from(self.0).ok().and_then(|i| STR_ERROR.get(i)) {
Some(desc) => write!(f, "{desc}"),
None => write!(f, "unknown error ({})", self.0),
}
}
}
pub trait ResultExt<T> {
fn or_minus_one_errno(self) -> T;
}
impl<T: From<i8>> ResultExt<T> for Result<T, Errno> {
fn or_minus_one_errno(self) -> T {
match self {
Self::Ok(v) => v,
Self::Err(Errno(errno)) => {
crate::platform::ERRNO.set(errno);
T::from(-1)
}
}
}
}
pub trait ResultExtPtrMut<T> {
fn or_errno_null_mut(self) -> *mut T;
}
impl<T> ResultExtPtrMut<T> for Result<*mut T, Errno> {
fn or_errno_null_mut(self) -> *mut T {
match self {
Self::Ok(ptr) => ptr,
Self::Err(Errno(errno)) => {
crate::platform::ERRNO.set(errno);
core::ptr::null_mut()
}
}
}
}
impl<T> ResultExtPtrMut<T> for Result<Box<T>, Errno> {
fn or_errno_null_mut(self) -> *mut T {
match self {
Self::Ok(ptr) => Box::into_raw(ptr),
Self::Err(Errno(errno)) => {
crate::platform::ERRNO.set(errno);
core::ptr::null_mut()
}
}
}
}
-156
View File
@@ -1,156 +0,0 @@
use crate::{
c_str::CStr,
error::{Errno, ResultExt},
header::{
fcntl::O_CREAT,
sys_stat::stat,
unistd::{SEEK_CUR, SEEK_END, SEEK_SET},
},
io,
out::Out,
platform::{Pal, Sys, types::*},
};
use core::ops::Deref;
pub struct File {
pub fd: c_int,
/// To avoid self referential FILE struct that needs both a reader and a writer,
/// make "reference" files that share fd but don't close on drop.
pub reference: bool,
}
impl File {
pub fn new(fd: c_int) -> Self {
Self {
fd,
reference: false,
}
}
pub fn open(path: CStr, oflag: c_int) -> Result<Self, Errno> {
Sys::open(path, oflag, 0)
.map(Self::new)
.map_err(Errno::sync)
}
pub fn openat(dirfd: c_int, path: CStr, oflag: c_int) -> Result<Self, Errno> {
Sys::openat(dirfd, path, oflag, 0)
.map(Self::new)
.map_err(Errno::sync)
}
pub fn create(path: CStr, oflag: c_int, mode: mode_t) -> Result<Self, Errno> {
Sys::open(path, oflag | O_CREAT, mode)
.map(Self::new)
.map_err(Errno::sync)
}
pub fn createat(dirfd: c_int, path: CStr, oflag: c_int, mode: mode_t) -> Result<Self, Errno> {
Sys::openat(dirfd, path, oflag | O_CREAT, mode)
.map(Self::new)
.map_err(Errno::sync)
}
pub fn sync_all(&self) -> Result<(), Errno> {
Sys::fsync(self.fd).map_err(Errno::sync)
}
pub fn set_len(&self, size: u64) -> Result<(), Errno> {
Sys::ftruncate(self.fd, size as off_t).map_err(Errno::sync)
}
pub fn fstat(&self) -> Result<stat, Errno> {
let mut file_st = stat::default();
Sys::fstat(self.fd, Out::from_mut(&mut file_st)).map_err(Errno::sync)?;
Ok(file_st)
}
pub fn try_clone(&self) -> io::Result<Self> {
Ok(Self::new(Sys::dup(self.fd)?))
}
/// Create a new file pointing to the same underlying descriptor. This file
/// will know it's a "reference" and won't close the fd. It will, however,
/// not prevent the original file from closing the fd.
pub unsafe fn get_ref(&self) -> Self {
Self {
fd: self.fd,
reference: true,
}
}
}
impl io::Read for &File {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match Sys::read(self.fd, buf).map(|read| read as ssize_t).or_minus_one_errno() /* TODO */ {
-1 => Err(io::last_os_error()),
ok => Ok(ok as usize),
}
}
}
impl io::Write for &File {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match Sys::write(self.fd, buf)
.map(|read| read as ssize_t)
.or_minus_one_errno()
{
-1 => Err(io::last_os_error()),
ok => Ok(ok as usize),
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl io::Seek for &File {
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
let (offset, whence) = match pos {
io::SeekFrom::Start(start) => (start as off_t, SEEK_SET),
io::SeekFrom::Current(current) => (current as off_t, SEEK_CUR),
io::SeekFrom::End(end) => (end as off_t, SEEK_END),
};
Ok(Sys::lseek(self.fd, offset, whence)? as u64)
}
}
impl io::Read for File {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&mut &*self).read(buf)
}
}
impl io::Write for File {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&mut &*self).write(buf)
}
fn flush(&mut self) -> io::Result<()> {
(&mut &*self).flush()
}
}
impl io::Seek for File {
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
(&mut &*self).seek(pos)
}
}
impl Deref for File {
type Target = c_int;
fn deref(&self) -> &Self::Target {
&self.fd
}
}
impl Drop for File {
fn drop(&mut self) {
if !self.reference {
let _ = Sys::close(self.fd);
}
}
}
-61
View File
@@ -1,61 +0,0 @@
//! `X11/Xauth.h` — X11 authentication file format.
//!
//! Redox OS implements the X11 Xauthority file format for use by
//! X11 clients and servers (and by SDDM, which can write Xauthority
//! entries when launching a session). On Redox, the Xauthority
//! file lives at `/home/<user>/.Xauthority` (or wherever the
//! user's `XAUTHORITY` environment variable points); the in-memory
//! representation is parsed from this header.
//!
//! This header provides the constants and types that X11 client
//! libraries (libX11, libxcb) use to read and write the file.
//! The on-disk format is the standard X11 `.Xauthority` big-endian
//! binary format with entries: family, address length + bytes,
//! number length + bytes, name length + bytes, data length + bytes.
use crate::platform::types::{c_int, c_uchar, c_ushort};
pub const FamilyInternet: c_ushort = 0;
pub const FamilyDECnet: c_ushort = 1;
pub const FamilyChaos: c_ushort = 2;
pub const FamilyInternet6: c_ushort = 6;
pub const FamilyServerInterpreted: c_ushort = 5;
pub const FamilyLocal: c_ushort = 252;
pub const FamilyWild: c_ushort = 65535;
pub const FamilyNetname: c_ushort = 254;
pub const FamilyKrb5Principal: c_ushort = 253;
pub const FamilyLocalHost: c_ushort = 251;
pub const Family0: c_ushort = FamilyInternet;
pub const Family1: c_ushort = FamilyDECnet;
pub const Family2: c_ushort = FamilyChaos;
pub const Family6: c_ushort = FamilyInternet6;
pub const Family5: c_ushort = FamilyServerInterpreted;
pub const XauthFileVersion: c_int = 1;
#[repr(C)]
pub struct Xauth {
pub family: c_ushort,
pub address_length: c_ushort,
pub address: *mut c_uchar,
pub number_length: c_ushort,
pub number: *mut c_uchar,
pub name_length: c_ushort,
pub name: *mut c_uchar,
pub data_length: c_ushort,
pub data: *mut c_uchar,
pub next: *mut Xauth,
}
unsafe extern "C" {
pub fn XauFileName() -> *mut c_uchar;
pub fn XauReadAuth(filepath: *mut c_uchar) -> *mut Xauth;
pub fn XauLockAuth(filepath_a: *mut c_uchar, retries: c_int, timeout: c_int, dead: c_int) -> c_int;
pub fn XauUnlockAuth(filepath: *mut c_uchar);
pub fn XauWriteAuth(filepath: *mut c_uchar, auth: *mut Xauth) -> c_int;
pub fn XauGetAuthByName(name: *mut c_uchar, name_len: c_int) -> *mut Xauth;
pub fn XauGetBestAuthByAddr(family: c_ushort, addr_length: c_int, addr: *mut c_uchar, num_length: c_int, num: *mut c_uchar, types: c_int) -> *mut Xauth;
pub fn XauGetAuthByAddr(family: c_ushort, addr_length: c_ushort, addr: *mut c_uchar, num_length: c_ushort, num: *mut c_uchar) -> *mut Xauth;
pub fn XauDisposeAuth(auth: *mut Xauth);
}
-26
View File
@@ -1,26 +0,0 @@
# POSIX header spec: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/aio.h.html
#
# Spec quotations relating to includes:
# - "The <aio.h> header shall define the off_t, pthread_attr_t, size_t, and ssize_t types as described in <sys/types.h>."
# - "The <aio.h> header shall define the struct timespec structure as described in <time.h>."
# - "The <aio.h> header shall define the sigevent structure and sigval union as described in <signal.h>."
# - "Inclusion of the <aio.h> header may make visible symbols defined in the headers <fcntl.h>, <signal.h>, and <time.h>."
#
# signal.h brings in sigevent and sigval
# signal.h brings in bits/timespec.h for timespec from time.h
# signal.h brings in bits/pthread-t.h bringing in pthread_t from sys/types.h
# signal.h brings in bits/pthreadattr-t.h bringing in pthread_attr_t from sys/types.h
# signal.h brings in size_t from sys/types.h
sys_includes = ["signal.h"]
after_includes = """
#include <bits/off-t.h> // for off_t from sys/types.h
#include <bits/ssize-t.h> // for ssize_t from sys/types.h
"""
include_guard = "_RELIBC_AIO_H"
language = "C"
style = "Tag"
no_includes = true
cpp_compat = true
[enum]
prefix_with_name = true
-83
View File
@@ -1,83 +0,0 @@
//! `aio.h` implementation.
//!
//! See <https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/aio.h.html>.
use crate::{
header::{errno::ENOSYS, signal::sigevent, time::timespec},
platform::types::{c_int, c_void, size_t, ssize_t},
};
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/aio.h.html>.
pub struct aiocb {
pub aio_fildes: c_int,
pub aio_lio_opcode: c_int,
pub aio_reqprio: c_int,
pub aio_buf: *mut c_void,
pub aio_nbytes: size_t,
pub aio_sigevent: sigevent,
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_read.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_read(aiocbp: *mut aiocb) -> c_int {
let _ = aiocbp;
ENOSYS
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_write.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_write(aiocbp: *mut aiocb) -> c_int {
let _ = aiocbp;
ENOSYS
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/lio_listio.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn lio_listio(
mode: c_int,
list: *const *const aiocb,
nent: c_int,
sig: *mut sigevent,
) -> c_int {
let _ = (mode, list, nent, sig);
ENOSYS
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_error.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_error(aiocbp: *const aiocb) -> c_int {
let _ = aiocbp;
ENOSYS
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_return.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_return(aiocbp: *mut aiocb) -> ssize_t {
let _ = aiocbp;
-1
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_cancel.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_cancel(fildes: c_int, aiocbp: *mut aiocb) -> c_int {
let _ = (fildes, aiocbp);
ENOSYS
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_suspend.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_suspend(
list: *const *const aiocb,
nent: c_int,
timeout: *const timespec,
) -> c_int {
let _ = (list, nent, timeout);
ENOSYS
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/aio_fsync.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn aio_fsync(operation: c_int, aiocbp: *mut aiocb) -> c_int {
let _ = (operation, aiocbp);
ENOSYS
}
-17
View File
@@ -1,17 +0,0 @@
# POSIX header spec: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/fenv.h.html
#
# There are no spec quotations relating to includes
#
# TODO figure out what type to use for `fenv_t` and `fexcept_t`
# currently using `c_ulonglong` as it doesn't bring in
# stdint.h (which would be considered namespace pollution)
#
# NOTE this header is not currently exported as we are using openlibm
include_guard = "_RELIBC_FENV_H"
language = "C"
style = "Tag"
no_includes = true
cpp_compat = true
[enum]
prefix_with_name = true
-288
View File
@@ -1,288 +0,0 @@
//! `fenv.h` implementation.
//!
//! See <https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/fenv.h.html>.
//!
//! On x86/x86_64 the floating-point environment is split between the
//! x87 FPU control word (`fnstcw`/`fldcw`, 16-bit) and the SSE MXCSR
//! register (`stmxcsr`/`ldmxcsr`, 32-bit). The POSIX `FE_*` exception
//! constants are defined to match the MXCSR exception flag bits so
//! that `feclearexcept`/`fetestexcept` can operate via direct bitwise
//! AND/OR on a stored MXCSR value.
//!
//! Rounding mode uses MXCSR bits 13-14 (0=nearest, 1=down, 2=up,
//! 3=toward-zero), matching the POSIX `FE_TONEAREST`/`FE_DOWNWARD`/
//! `FE_UPWARD`/`FE_TOWARDZERO` values directly.
use crate::platform::types::{c_int, c_uint};
// --- Exception flag constants (match MXCSR bit positions) ---
pub const FE_INVALID: c_int = 0x01;
pub const FE_DIVBYZERO: c_int = 0x04;
pub const FE_OVERFLOW: c_int = 0x08;
pub const FE_UNDERFLOW: c_int = 0x10;
pub const FE_INEXACT: c_int = 0x20;
pub const FE_ALL_EXCEPT: c_int =
FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT;
// --- Rounding mode constants (match MXCSR bits 13-14) ---
pub const FE_TONEAREST: c_int = 0;
pub const FE_DOWNWARD: c_int = 1;
pub const FE_UPWARD: c_int = 2;
pub const FE_TOWARDZERO: c_int = 3;
/// Stored FP exception flags. On x86 this is a subset of the MXCSR
/// register containing the exception flag bits (bits 0-5).
pub type fexcept_t = c_uint;
/// Complete floating-point environment: x87 control word + SSE MXCSR.
/// The layout matches the structure used by `fegetenv`/`fesetenv` on
/// x86-64 Linux (glibc's `fenv_t` union stores the same two fields).
#[repr(C)]
pub struct fenv_t {
pub x87_cw: u16,
pub _reserved0: u16,
pub mxcsr: u32,
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn read_mxcsr() -> u32 {
let mut mxcsr: u32 = 0;
unsafe {
core::arch::asm!(
"stmxcsr [{addr}]",
addr = in(reg) core::ptr::addr_of_mut!(mxcsr),
options(nostack, preserves_flags),
);
}
mxcsr
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn write_mxcsr(mxcsr: u32) {
unsafe {
core::arch::asm!(
"ldmxcsr [{addr}]",
addr = in(reg) core::ptr::addr_of!(mxcsr),
options(nostack, preserves_flags),
);
}
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn read_x87_cw() -> u16 {
let mut cw: u16 = 0;
unsafe {
core::arch::asm!(
"fnstcw [{addr}]",
addr = in(reg) core::ptr::addr_of_mut!(cw),
options(nostack, preserves_flags),
);
}
cw
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn write_x87_cw(cw: u16) {
unsafe {
core::arch::asm!(
"fldcw [{addr}]",
addr = in(reg) core::ptr::addr_of!(cw),
options(nostack, preserves_flags),
);
}
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/feclearexcept.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn feclearexcept(excepts: c_int) -> c_int {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
let masked = excepts & FE_ALL_EXCEPT;
if masked != 0 {
let mxcsr = read_mxcsr();
write_mxcsr(mxcsr & !masked as u32);
}
}
let _ = excepts;
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fegetenv.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fegetenv(envp: *mut fenv_t) -> c_int {
if envp.is_null() {
return -1;
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
(*envp).x87_cw = read_x87_cw();
(*envp)._reserved0 = 0;
(*envp).mxcsr = read_mxcsr();
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
unsafe {
*envp = core::mem::zeroed();
}
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fegetexceptflag.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fegetexceptflag(flagp: *mut fexcept_t, excepts: c_int) -> c_int {
if flagp.is_null() {
return -1;
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
let mxcsr = read_mxcsr();
*flagp = (mxcsr as c_int & excepts & FE_ALL_EXCEPT) as c_uint;
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
unsafe {
*flagp = 0;
}
let _ = excepts;
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fegetround.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fegetround() -> c_int {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
let mxcsr = read_mxcsr();
((mxcsr >> 13) & 0x3) as c_int
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
{
FE_TONEAREST
}
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/feholdexcept.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn feholdexcept(envp: *mut fenv_t) -> c_int {
if envp.is_null() {
return -1;
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
// Save current environment.
(*envp).x87_cw = read_x87_cw();
(*envp)._reserved0 = 0;
(*envp).mxcsr = read_mxcsr();
// Clear all exception flags and mask all exceptions (non-stop mode).
let mxcsr = read_mxcsr();
write_mxcsr((mxcsr | FE_ALL_EXCEPT as u32 | (FE_ALL_EXCEPT as u32) << 7) & !(FE_ALL_EXCEPT as u32));
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
unsafe {
*envp = core::mem::zeroed();
}
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/feraiseexcept.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn feraiseexcept(excepts: c_int) -> c_int {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
let masked = excepts & FE_ALL_EXCEPT;
if masked != 0 {
let mxcsr = read_mxcsr();
// Set the exception flag bits. Unmask them first so the
// exception is actually raised (not just flagged).
write_mxcsr((mxcsr & !((masked as u32) << 7)) | masked as u32);
}
}
let _ = excepts;
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fesetenv.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fesetenv(envp: *const fenv_t) -> c_int {
if envp.is_null() {
return -1;
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
write_x87_cw((*envp).x87_cw);
write_mxcsr((*envp).mxcsr);
}
let _ = envp;
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fesetexceptflag.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fesetexceptflag(flagp: *const fexcept_t, excepts: c_int) -> c_int {
if flagp.is_null() {
return -1;
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
let masked = excepts & FE_ALL_EXCEPT;
if masked != 0 {
let mxcsr = read_mxcsr();
let new_flags = (*flagp as c_int) & masked;
write_mxcsr((mxcsr & !(masked as u32)) | new_flags as u32);
}
}
let _ = (flagp, excepts);
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fegetround.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fesetround(round: c_int) -> c_int {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
if !(0..=3).contains(&round) {
return -1;
}
let mxcsr = read_mxcsr();
write_mxcsr((mxcsr & !(0x3 << 13)) | ((round as u32) << 13));
}
let _ = round;
0
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/fetestexcept.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn fetestexcept(excepts: c_int) -> c_int {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
{
let mxcsr = read_mxcsr();
(mxcsr as c_int) & excepts & FE_ALL_EXCEPT
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
{
let _ = excepts;
0
}
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/feupdateenv.html>.
// #[unsafe(no_mangle)]
pub unsafe extern "C" fn feupdateenv(envp: *const fenv_t) -> c_int {
if envp.is_null() {
return -1;
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe {
// POSIX: save current exceptions, restore the environment, then
// re-raise the saved exceptions.
let current = read_mxcsr() as c_int & FE_ALL_EXCEPT;
write_x87_cw((*envp).x87_cw);
write_mxcsr((*envp).mxcsr);
if current != 0 {
let mxcsr = read_mxcsr();
write_mxcsr(mxcsr | current as u32);
}
}
let _ = envp;
0
}
-5
View File
@@ -1,5 +0,0 @@
include_guard = "_RELIBC_PATHS_H"
language = "C"
style = "Type"
no_includes = true
cpp_compat = true
-29
View File
@@ -1,29 +0,0 @@
//! Linux specific constants for paths.h.
//! Entirely borrowed from musl as there isn't a list of what to include.
pub const _PATH_DEFPATH: &str = "/usr/local/bin:/bin:/usr/bin";
pub const _PATH_STDPATH: &str = "/bin:/usr/bin:/sbin:/usr/sbin";
pub const _PATH_BSHELL: &str = "/bin/sh";
pub const _PATH_CONSOLE: &str = "/dev/console";
pub const _PATH_DEVNULL: &str = "/dev/null";
pub const _PATH_KLOG: &str = "/proc/kmsg";
pub const _PATH_LASTLOG: &str = "/var/log/lastlog";
pub const _PATH_MAILDIR: &str = "/var/mail";
pub const _PATH_MAN: &str = "/usr/share/man";
pub const _PATH_MNTTAB: &str = "/etc/fstab";
pub const _PATH_NOLOGIN: &str = "/etc/nologin";
pub const _PATH_SENDMAIL: &str = "/usr/sbin/sendmail";
pub const _PATH_SHADOW: &str = "/etc/shadow";
pub const _PATH_SHELLS: &str = "/etc/shells";
pub const _PATH_TTY: &str = "/dev/tty";
pub const _PATH_UTMP: &str = "/var/run/utmp";
pub const _PATH_WTMP: &str = "/var/log/wtmp";
pub const _PATH_VI: &str = "/usr/bin/vi";
// Trailing backslash intentional as these are dir paths.
pub const _PATH_DEV: &str = "/dev/";
pub const _PATH_TMP: &str = "/tmp/";
pub const _PATH_VARDB: &str = "/var/lib/misc/";
pub const _PATH_VARRUN: &str = "/var/run/";
pub const _PATH_VARTMP: &str = "/var/tmp/";
-11
View File
@@ -1,11 +0,0 @@
//! Implementation specific, non-standard path aliases
#[cfg(target_os = "linux")]
#[path = "linux.rs"]
mod sys;
#[cfg(target_os = "redox")]
#[path = "redox.rs"]
mod sys;
pub use sys::*;
-13
View File
@@ -1,13 +0,0 @@
//! Redox specific constants for paths.h.
// NOTE: Cross check that new entries correspond to files on Redox before adding.
pub const _PATH_BSHELL: &str = "/bin/sh";
pub const _PATH_DEVNULL: &str = "/dev/null";
pub const _PATH_MAN: &str = "/usr/share/man";
pub const _PATH_TTY: &str = "/dev/tty";
// Trailing backslash intentional as these are dir paths.
pub const _PATH_DEV: &str = "/dev/";
pub const _PATH_TMP: &str = "/tmp/";
pub const _PATH_VARTMP: &str = "/var/tmp/";
-9
View File
@@ -1,9 +0,0 @@
sys_includes = []
include_guard = "_RELIBC_TEMPLATE_H"
language = "C"
style = "Tag"
no_includes = true
cpp_compat = true
[enum]
prefix_with_name = true
-10
View File
@@ -1,10 +0,0 @@
//! template implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/template.h.html
use platform::types::*;
/*
#[unsafe(no_mangle)]
pub extern "C" fn func(args) -> c_int {
unimplemented!();
}
*/
@@ -1,16 +0,0 @@
sys_includes = []
include_guard = "_AARCH64_USER_H"
language = "C"
style = "Tag"
[enum]
prefix_with_name = true
[export]
include = [
"user_regs_struct",
"user_fpsimd_struct",
"elf_gregset_t",
"elf_greg_t",
"elf_fpregset_t"
]
-20
View File
@@ -1,20 +0,0 @@
use crate::platform::types::{c_double, c_uint, c_ulong, c_ulonglong};
#[repr(C)]
pub struct user_regs_struct {
pub regs: [c_ulonglong; 31],
pub sp: c_ulonglong,
pub pc: c_ulonglong,
pub pstate: c_ulonglong,
}
#[repr(C)]
pub struct user_fpsimd_struct {
pub vregs: [c_double; 32], // BUG: rust doesn't have f128 which is equivalent for long double
pub fpsr: c_uint,
pub fpcr: c_uint,
}
pub type elf_greg_t = c_ulong;
pub type elf_gregset_t = *mut [c_ulong; 34];
pub type elf_fpregset_t = user_fpsimd_struct;
@@ -1,16 +0,0 @@
sys_includes = []
include_guard = "_RISCV64_USER_H"
language = "C"
style = "Tag"
[enum]
prefix_with_name = true
[export]
include = [
"user_regs_struct",
"user_fpregs_struct",
"elf_gregset_t",
"elf_greg_t",
"elf_fpregset_t",
]
-29
View File
@@ -1,29 +0,0 @@
use crate::platform::types::{c_double, c_float, c_uint, c_ulong};
#[repr(C)]
pub struct user_regs_struct {
pub regs: [c_ulong; 31], // x1-x31
pub pc: c_ulong,
}
#[repr(C)]
pub struct user_fpregs_f_struct {
pub fpregs: [c_float; 32],
pub fcsr: c_uint,
}
#[repr(C)]
pub struct user_fpregs_g_struct {
pub fpregs: [c_double; 32],
pub fcsr: c_uint,
}
#[repr(C)]
pub struct user_fpregs_struct {
pub f_regs: user_fpregs_f_struct,
pub g_regs: user_fpregs_g_struct,
}
pub type elf_greg_t = c_ulong;
pub type elf_gregset_t = user_regs_struct;
pub type elf_fpregset_t = user_fpregs_struct;
-17
View File
@@ -1,17 +0,0 @@
sys_includes = []
include_guard = "_X64_USER_H"
language = "C"
style = "Tag"
[enum]
prefix_with_name = true
[export]
include = [
"user_fpregs_struct",
"user_regs_struct",
"user",
"elf_gregset_t",
"elf_greg_t",
"elf_fpregset_t"
]
-72
View File
@@ -1,72 +0,0 @@
//! A part of the ptrace compatibility for Redox OS
use crate::platform::types::{c_char, c_int, c_long, c_ulong};
#[repr(C)]
pub struct user_fpregs_struct {
pub cwd: u16,
pub swd: u16,
pub ftw: u16,
pub fop: u16,
pub rip: u64,
pub rdp: u64,
pub mxcsr: u32,
pub mxcr_mask: u32,
pub st_space: [u32; 32],
pub xmm_space: [u32; 64],
pub padding: [u32; 24],
}
#[repr(C)]
pub struct user_regs_struct {
pub r15: c_ulong,
pub r14: c_ulong,
pub r13: c_ulong,
pub r12: c_ulong,
pub rbp: c_ulong,
pub rbx: c_ulong,
pub r11: c_ulong,
pub r10: c_ulong,
pub r9: c_ulong,
pub r8: c_ulong,
pub rax: c_ulong,
pub rcx: c_ulong,
pub rdx: c_ulong,
pub rsi: c_ulong,
pub rdi: c_ulong,
pub orig_rax: c_ulong,
pub rip: c_ulong,
pub cs: c_ulong,
pub eflags: c_ulong,
pub rsp: c_ulong,
pub ss: c_ulong,
pub fs_base: c_ulong,
pub gs_base: c_ulong,
pub ds: c_ulong,
pub es: c_ulong,
pub fs: c_ulong,
pub gs: c_ulong,
}
pub type elf_greg_t = c_ulong;
pub type elf_gregset_t = *mut [c_ulong; 27];
pub type elf_fpregset_t = user_fpregs_struct;
#[repr(C)]
pub struct user {
pub regs: user_regs_struct,
pub u_fpvalid: c_int,
pub i387: user_fpregs_struct,
pub u_tsize: c_ulong,
pub u_dsize: c_ulong,
pub u_ssize: c_ulong,
pub start_code: c_ulong,
pub start_stack: c_ulong,
pub signal: c_long,
pub reserved: c_int,
pub u_ar0: *mut user_regs_struct,
pub u_fpstate: *mut user_fpregs_struct,
pub magic: c_ulong,
pub u_comm: [c_char; 32],
pub u_debugreg: [c_ulong; 8],
}
-30
View File
@@ -1,30 +0,0 @@
# POSIX header spec: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/arpa_inet.h.html
#
# Spec quotations relating to includes:
# - "The <arpa/inet.h> header shall define the in_port_t and in_addr_t types as described in <netinet/in.h> and the socklen_t type as defined in <sys/socket.h>."
# - "The <arpa/inet.h> header shall define the in_addr structure as described in <netinet/in.h>."
# - "The <arpa/inet.h> header shall define the INET_ADDRSTRLEN and INET6_ADDRSTRLEN macros as described in <netinet/in.h>."
# - "The <arpa/inet.h> header shall define the uint32_t and uint16_t types as described in <inttypes.h>."
# - "Inclusion of the <arpa/inet.h> header may also make visible all symbols from <netinet/in.h> and <inttypes.h>."
#
# Possible cycle between arpa/inet.h and netinet/in.h solved by:
# - including netinet/in.h in arpa/inet.h
# - splitting out functions (htonl, htons, ntohl, ntohs) into bits/arpainet.h
#
# bits/arpainet.h brings in inttypes.h
# features.h needed for deprecated annotation
sys_includes = ["netinet/in.h", "features.h"]
include_guard = "_RELIBC_ARPA_INET_H"
after_includes = """
#include <bits/arpainet.h> // for htonl, htons, ntohl, ntohs
#include <bits/socklen-t.h> // for socklen_t from sys/socket.h
"""
language = "C"
no_includes = true
cpp_compat = true
[enum]
prefix_with_name = true
[export.rename]
"in_addr" = "struct in_addr"
-577
View File
@@ -1,577 +0,0 @@
//! `arpa/inet.h` implementation.
//!
//! See <https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/arpa_inet.h.html>.
use core::{
ptr, slice,
str::{self, FromStr},
};
use crate::{
c_str::CStr,
header::{
bits_arpainet::ntohl,
errno::{EAFNOSUPPORT, ENOSPC},
netinet_in::{INADDR_NONE, in_addr, in_addr_t, in6_addr},
sys_socket::{
constants::{AF_INET, AF_INET6},
socklen_t,
},
},
io::Write,
platform::{
self,
types::{c_char, c_int, c_void},
},
raw_cell::RawCell,
};
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/inet_addr.html>.
///
/// Converts the string pointed to by `cp`, in the standard IPv4 dotted
/// decimal notation, to an integer value suitable for use as an Internet
/// address.
///
/// # Deprecated
/// The `inet_addr()` function was marked obsolescent in the Open Group Base
/// Specifications Issue 8.
///
/// Applications should prefer `inet_pton()` over `inet_addr()` for the
/// following reasons:
/// - The return value from `inet_addr()` when converting 255.255.255.255 is
/// indistinguishable from an error.
/// - The `inet_pton()` function supports multiple address families.
/// - The alternative textual representations supported by `inet_addr()` (but
/// not `inet_pton()`) are often used maliciously to confuse or mislead
/// users (e.g, for phishing).
#[deprecated]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn inet_addr(cp: *const c_char) -> in_addr_t {
let mut val: in_addr = in_addr { s_addr: 0 };
if unsafe { inet_aton(cp, &raw mut val) } > 0 {
val.s_addr
} else {
INADDR_NONE
}
}
/// Non-POSIX, see <https://www.man7.org/linux/man-pages/man3/inet_aton.3.html>.
///
/// Converts the Internet host address `cp` from the IPv4 numbers-and-dots
/// notation into binary form (in network byte order) and stores it in the
/// structure that `inp` points to.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn inet_aton(cp: *const c_char, inp: *mut in_addr) -> c_int {
let cp_cstr = unsafe { CStr::from_ptr(cp) };
let parts = unsafe { str::from_utf8_unchecked(cp_cstr.to_bytes()).split('.') };
let count = parts.clone().count();
if count > 4 {
return 0;
}
let mut result = 0;
let mut parts_iter = parts.peekable();
let mut index = 0u32;
while index < 4
&& let Some(part) = parts_iter.next()
{
if let Ok(parsed_value) = {
if let Some(hex_or_oct) = part.strip_prefix('0')
&& part.len() > 1
{
match hex_or_oct.bytes().next() {
Some(b'x' | b'X') => u32::from_str_radix(&hex_or_oct[1..], 16),
// While it is true that C2Y accepts 0o and 0O as octal prefixes, C17 doesn't
// The POSIX spec defers to C17
// see https://pubs.opengroup.org/onlinepubs/9799919799/functions/inet_addr.html
_ => u32::from_str_radix(hex_or_oct, 8),
}
} else {
part.parse::<u32>()
}
} {
if parts_iter.peek().is_some() {
// this is not the last part
if parsed_value > 0xff {
return 0;
}
result += parsed_value << (24 - index * 8);
} else {
// this is the last part
if index > 0 && parsed_value >= 1 << (32 - index * 8) {
return 0;
} else {
result += parsed_value;
}
}
} else {
return 0;
}
index += 1;
}
unsafe { (*inp.cast::<in_addr>()).s_addr = result.to_be() };
1
}
/// See <https://pubs.opengroup.org/onlinepubs/7908799/xns/inet_lnaof.html>.
///
/// Takes an Internet host address specified by `in` and extracts the local
/// network address part, in host byte order.
///
/// # Deprecation
/// The `inet_lnaof()` function was specified in Networking Services Issue 5,
/// but not in the Open Group Base Specifications Issue 6 and later.
#[deprecated]
#[unsafe(no_mangle)]
pub extern "C" fn inet_lnaof(r#in: in_addr) -> in_addr_t {
if r#in.s_addr >> 24 < 128 {
r#in.s_addr & 0xff_ffff
} else if r#in.s_addr >> 24 < 192 {
r#in.s_addr & 0xffff
} else {
r#in.s_addr & 0xff
}
}
/// See <https://pubs.opengroup.org/onlinepubs/7908799/xns/inet_makeaddr.html>.
///
/// Takes the Internet network number specified by `net` and the local network
/// address specified by `lna`, both in host byte order, and constructs an
/// Internet address from them.
///
/// # Deprecation
/// The `inet_makeaddr()` function was specified in Networking Services Issue
/// 5, but not in the Open Group Base Specifications Issue 6 and later.
#[deprecated]
#[unsafe(no_mangle)]
pub extern "C" fn inet_makeaddr(net: in_addr_t, lna: in_addr_t) -> in_addr {
let mut output: in_addr = in_addr { s_addr: 0 };
if net < 256 {
output.s_addr = lna | net << 24;
} else if net < 65536 {
output.s_addr = lna | net << 16;
} else {
output.s_addr = lna | net << 8;
}
output
}
/// See <https://pubs.opengroup.org/onlinepubs/7908799/xns/inet_netof.html>.
///
/// Takes an Internet host address specified by `in` and extracts the network
/// number part, in host byte order.
///
/// # Deprecation
/// The `inet_netof()` function was specified in Networking Services Issue 5,
/// but not in the Open Group Base Specifications Issue 6 and later.
#[deprecated]
#[unsafe(no_mangle)]
pub extern "C" fn inet_netof(r#in: in_addr) -> in_addr_t {
if r#in.s_addr >> 24 < 128 {
r#in.s_addr & 0xff_ffff
} else if r#in.s_addr >> 24 < 192 {
r#in.s_addr & 0xffff
} else {
r#in.s_addr & 0xff
}
}
/// See <https://pubs.opengroup.org/onlinepubs/7908799/xns/inet_network.html>.
///
/// Converts the string pointed to by `cp`, in the Internet standard dot
/// notation, to an integer value suitable for use as an Internet network
/// number.
///
/// # Deprecation
/// The `inet_network()` function was specified in Networking Services Issue 5,
/// but not in the Open Group Base Specifications Issue 6 and later.
#[deprecated]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn inet_network(cp: *const c_char) -> in_addr_t {
ntohl(unsafe {
#[allow(deprecated)]
inet_addr(cp)
})
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/inet_addr.html>.
///
/// Converts the Internet host address specified by `in` to a string in the
/// Internet standard dot notation.
///
/// # Deprecation
/// The `inet_ntoa()` function was marked obsolescent in the Open Group Base
/// Specifications Issue 8.
///
/// Applications should prefer `inet_ntop()` over `inet_ntoa()` as it supports
/// multiple address families and is thread-safe.
#[deprecated]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn inet_ntoa(r#in: in_addr) -> *mut c_char {
static NTOA_ADDR: RawCell<[c_char; 16]> = RawCell::new([0; 16]);
unsafe {
let ptr = inet_ntop(
AF_INET,
ptr::from_ref::<in_addr>(&r#in).cast::<c_void>(),
NTOA_ADDR.unsafe_mut().as_mut_ptr(),
NTOA_ADDR.unsafe_ref().len() as socklen_t,
);
// Mutable pointer is required, inet_ntop returns destination as const pointer
ptr.cast_mut()
}
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/inet_ntop.html>.
///
/// Converts a numeric address into a text string suitable for presentation.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn inet_ntop(
af: c_int,
src: *const c_void,
dst: *mut c_char,
size: socklen_t,
) -> *const c_char {
if af == AF_INET {
if (size as usize) < 16 {
platform::ERRNO.set(ENOSPC);
return ptr::null();
}
let s_addr = unsafe {
slice::from_raw_parts(
ptr::from_ref(&(*(src.cast::<in_addr>())).s_addr).cast::<u8>(),
4,
)
};
let mut w = platform::StringWriter(dst, size as usize);
let _ = write!(
w,
"{}.{}.{}.{}\0",
s_addr[0], s_addr[1], s_addr[2], s_addr[3]
);
dst
} else if af == AF_INET6 {
// IPv6 textual representation per RFC 5952:
// - 8 groups of 4 lowercase hex digits separated by colons
// - Longest run of consecutive all-zero groups compressed to "::"
// - Ties broken by first occurrence
// - Single zero group is NOT compressed
// INET6_ADDRSTRLEN == 46 (39 chars + trailing NUL + slack)
if (size as usize) < crate::header::netinet_in::INET6_ADDRSTRLEN as usize {
platform::ERRNO.set(ENOSPC);
return ptr::null();
}
let bytes = unsafe {
slice::from_raw_parts(
ptr::from_ref(&(*(src.cast::<in6_addr>())).s6_addr).cast::<u8>(),
16,
)
};
let mut groups = [0u16; 8];
for (i, g) in groups.iter_mut().enumerate() {
*g = u16::from_be_bytes([bytes[i * 2], bytes[i * 2 + 1]]);
}
let mut best_start = usize::MAX;
let mut best_len = 0usize;
let mut cur_start = usize::MAX;
let mut cur_len = 0usize;
for i in 0..8 {
if groups[i] == 0 {
if cur_start == usize::MAX {
cur_start = i;
cur_len = 1;
} else {
cur_len += 1;
}
if cur_len > best_len {
best_len = cur_len;
best_start = cur_start;
}
} else {
cur_start = usize::MAX;
cur_len = 0;
}
}
if best_len < 2 {
best_start = usize::MAX;
}
let mut w = platform::StringWriter(dst, size as usize);
let mut i = 0usize;
let mut after_ellipsis = false;
while i < 8 {
if i == best_start {
let _ = write!(w, "::");
after_ellipsis = true;
i += best_len;
continue;
}
if !after_ellipsis && i > 0 {
let _ = write!(w, ":");
}
let _ = write!(w, "{:x}", groups[i]);
after_ellipsis = false;
i += 1;
}
let _ = write!(w, "\0");
dst
} else {
platform::ERRNO.set(EAFNOSUPPORT);
ptr::null()
}
}
/// See <https://pubs.opengroup.org/onlinepubs/9799919799/functions/inet_ntop.html>.
///
/// Converts an address in its standard text presentation form into its
/// numeric binary form.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn inet_pton(af: c_int, src: *const c_char, dst: *mut c_void) -> c_int {
if af == AF_INET {
let s_addr = unsafe {
slice::from_raw_parts_mut(
ptr::from_mut(&mut (*dst.cast::<in_addr>()).s_addr).cast::<u8>(),
4,
)
};
let src_cstr = unsafe { CStr::from_ptr(src) };
let mut octets = unsafe { str::from_utf8_unchecked(src_cstr.to_bytes()).split('.') };
for part in s_addr.iter_mut().take(4) {
if let Some(n) = octets
.next()
.filter(|x| x.len() <= 3)
.and_then(|x| u8::from_str(x).ok())
{
*part = n;
} else {
return 0;
}
}
if octets.next().is_none() {
1 // Success
} else {
0
}
} else if af == AF_INET6 {
let src_str = unsafe { str::from_utf8_unchecked(CStr::from_ptr(src).to_bytes()) };
let mut chunks = vec![src_str];
let colons = src_str.bytes().filter(|&c| c == b':').count();
if !(2..=7).contains(&colons) {
return 0;
}
let dots = src_str.bytes().filter(|&c| c == b'.').count();
if dots != 0 && dots != 3 {
return 0;
}
let double_colon = src_str.find("::");
if colons < 2
|| double_colon.is_some() && ((dots == 0 && colons > 7) || (dots == 3 && colons > 6))
|| double_colon.is_none() && ((dots == 0 && colons != 7) || (dots == 3 && colons != 6))
{
return 0;
}
if dots == 3
&& let Some(first_dot) = src_str.find('.')
&& let Some(last_colon) = src_str.find(':')
&& last_colon > first_dot
{
return 0;
}
if let Some(first) = src_str.find("::")
&& let Some(last) = src_str.rfind("::")
{
// :: is allowed only once
if first != last {
return 0;
}
chunks = vec![&src_str[..first], &src_str[(first + 2)..]]
}
let s6_addr = unsafe {
slice::from_raw_parts_mut(
ptr::from_mut(&mut (*dst.cast::<in6_addr>()).s6_addr).cast::<u16>(),
8,
)
};
s6_addr.iter_mut().for_each(|w| *w = 0);
for (count, &chunk) in chunks
.iter()
.enumerate()
.filter(|&(_, &chunk)| !chunk.is_empty())
{
let mut parts = s6_addr
.iter_mut()
.skip(count * (8 - chunk.split(':').count() - dots / 3));
let mut words = chunk.split(':');
while let Some(word) = words.next()
&& let Some(part) = parts.next()
{
if word.is_empty() {
break;
} else if word.len() <= 4
&& let Some(n) = u16::from_str_radix(word, 16).ok()
{
*part = n.to_be();
} else if word.contains('.') {
let bytes =
unsafe { slice::from_raw_parts_mut(ptr::from_mut(part).cast::<u8>(), 4) };
let mut octets = word.split('.');
for byte in bytes {
if let Some(octet) = octets.next() {
if octet.len() > 1 && octet.starts_with('0') {
return 0;
}
if let Ok(value) = u8::from_str(octet) {
*byte = value
} else {
return 0;
}
}
}
} else {
return 0;
}
}
}
1 // Success
} else {
platform::ERRNO.set(EAFNOSUPPORT);
-1
}
}
#[cfg(test)]
mod tests {
use super::*;
fn format_v6(bytes: [u8; 16]) -> Option<alloc::string::String> {
let addr = in6_addr { s6_addr: bytes };
let mut buf = [0u8; 64];
let ret = unsafe {
inet_ntop(
AF_INET6,
ptr::from_ref(&addr).cast::<c_void>(),
buf.as_mut_ptr().cast::<c_char>(),
buf.len() as socklen_t,
)
};
if ret.is_null() {
None
} else {
let nul = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
core::str::from_utf8(&buf[..nul])
.ok()
.map(|s| alloc::string::String::from(s))
}
}
#[test]
fn inet_ntop_v6_unspecified() {
assert_eq!(format_v6([0u8; 16]).as_deref(), Some("::"));
}
#[test]
fn inet_ntop_v6_loopback() {
let mut bytes = [0u8; 16];
bytes[15] = 1;
assert_eq!(format_v6(bytes).as_deref(), Some("::1"));
}
#[test]
fn inet_ntop_v6_routable() {
let mut bytes = [0u8; 16];
bytes[0] = 0x20;
bytes[1] = 0x01;
bytes[2] = 0x0d;
bytes[3] = 0xb8;
bytes[15] = 0x01;
assert_eq!(format_v6(bytes).as_deref(), Some("2001:db8::1"));
}
#[test]
fn inet_ntop_v6_link_local() {
let mut bytes = [0u8; 16];
bytes[0] = 0xfe;
bytes[1] = 0x80;
bytes[15] = 0x01;
assert_eq!(format_v6(bytes).as_deref(), Some("fe80::1"));
}
#[test]
fn inet_ntop_v6_no_compression_single_zero() {
let bytes = [
0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04,
0x00, 0x05,
];
assert_eq!(format_v6(bytes).as_deref(), Some("2001:db8:0:1:2:3:4:5"));
}
#[test]
fn inet_ntop_v6_tie_break_first_wins() {
let bytes = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,
];
assert_eq!(format_v6(bytes).as_deref(), Some("::1:0:0:1"));
}
#[test]
fn inet_ntop_v6_trailing_run() {
let bytes = [
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
];
assert_eq!(format_v6(bytes).as_deref(), Some("1::"));
}
#[test]
fn inet_ntop_v4_loopback() {
let addr = in_addr {
s_addr: 0x7f000001u32.to_be(),
};
let mut buf = [0u8; 32];
let ret = unsafe {
inet_ntop(
AF_INET,
ptr::from_ref(&addr).cast::<c_void>(),
buf.as_mut_ptr().cast::<c_char>(),
buf.len() as socklen_t,
)
};
assert!(!ret.is_null());
let nul = buf.iter().position(|&b| b == 0).unwrap();
assert_eq!(core::str::from_utf8(&buf[..nul]).unwrap(), "127.0.0.1");
}
#[test]
fn inet_ntop_unsupported_family() {
let mut buf = [0u8; 32];
let ret = unsafe {
inet_ntop(
9999,
ptr::null(),
buf.as_mut_ptr().cast::<c_char>(),
buf.len() as socklen_t,
)
};
assert!(ret.is_null());
}
#[test]
fn inet_ntop_v6_size_too_small() {
let addr = in6_addr { s6_addr: [0u8; 16] };
let mut buf = [0u8; 4];
let ret = unsafe {
inet_ntop(
AF_INET6,
ptr::from_ref(&addr).cast::<c_void>(),
buf.as_mut_ptr().cast::<c_char>(),
buf.len() as socklen_t,
)
};
assert!(ret.is_null());
}
}
-34
View File
@@ -1,34 +0,0 @@
# POSIX header spec: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/assert.h.html
#
# There are no spec quotations relating to includes
#
# features.h included for Rust never type (no return)
sys_includes = ["features.h"]
include_guard = "_RELIBC_ASSERT_H"
# trailer is placed outside include_guard
trailer = """
// Do not use include guard, to ensure assert is always defined
#ifdef assert
#undef assert
#endif
// _Static_assert in C23 (202311L) is considered deprecated but kept for comaptibility.
// static_assert in C23 is considered a key word.
#if __STDC_VERSION__ >= 201112L && !defined(__cplusplus)
#define static_assert _Static_assert
#endif
#ifdef NDEBUG
# define assert(cond) (void) 0
#else
# define assert(cond) \
((void)((cond) || (__assert_fail(__func__, __FILE__, __LINE__, #cond), 0)))
#endif
"""
language = "C"
style = "Tag"
no_includes = true
cpp_compat = true
[enum]
prefix_with_name = true

Some files were not shown because too many files have changed in this diff Show More