├── .github └── workflows │ └── main.yml ├── .gitignore ├── .rustfmt.toml ├── CODE_OF_CONDUCT.md ├── COPYRIGHT ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-Apache-2.0_WITH_LLVM-exception ├── LICENSE-MIT ├── ORG_CODE_OF_CONDUCT.md ├── README.md ├── build.rs ├── ci ├── aarch64-o-largefile.patch ├── getsockopt-timeouts.patch ├── more-sockopts.patch ├── pidfd-open.patch ├── s390x-stat-have-nsec.patch ├── select-setsize.patch ├── tcgets2-tcsets2.patch ├── tiocgsid.patch └── translate-errno.patch ├── example-crates ├── all-from-source │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── extern-crate-eyra-optional-example │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── extern-crate-hello-world │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── eyra-libc-example │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── eyra-optional-example │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── eyra-panic-example │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── hello-world-lto │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── hello-world-small │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs ├── hello-world │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ │ └── main.rs └── no-std │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ └── src │ └── main.rs ├── examples ├── empty.rs ├── hello.rs ├── rust-by-example-threads.rs ├── test-args.rs ├── test-ctor.rs ├── test-environ.rs ├── test-simd.rs ├── test-tls-dtors.rs ├── test-tls.rs └── test-workdir.rs ├── rust-toolchain.toml ├── src └── lib.rs └── tests ├── example_crates.rs ├── examples.rs ├── stdtests.rs └── stdtests ├── common └── mod.rs ├── env.rs ├── fs.rs ├── integration_create_dir_all_bare.rs ├── integration_env.rs ├── integration_thread.rs ├── kernel_copy.rs ├── lazy.rs ├── net ├── mod.rs └── test.rs ├── net_addr.rs ├── net_ip.rs ├── net_tcp.rs ├── net_udp.rs ├── panic.rs ├── process.rs ├── process_common.rs ├── process_unix.rs ├── sync_barrier.rs ├── sync_condvar.rs ├── sync_lazy_lock.rs ├── sync_mpsc.rs ├── sync_mpsc_sync.rs ├── sync_mutex.rs ├── sync_once.rs ├── sync_once_lock.rs ├── sync_rwlock.rs ├── sys_common ├── io.rs └── mod.rs ├── thread.rs ├── thread_local.rs └── time.rs /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | rustfmt: 11 | name: Rustfmt 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - run: rustup update --no-self-update 16 | - run: cargo fmt --all -- --check 17 | 18 | test: 19 | name: Test 20 | runs-on: ${{ matrix.os }} 21 | env: 22 | QEMU_BUILD_VERSION: 8.1.0 23 | strategy: 24 | matrix: 25 | build: [ubuntu, i686-linux, aarch64-linux, riscv64-linux] 26 | include: 27 | - build: ubuntu 28 | os: ubuntu-latest 29 | host_target: x86_64-unknown-linux-gnu 30 | - build: i686-linux 31 | os: ubuntu-latest 32 | target: i686-unknown-linux-gnu 33 | gcc_package: gcc-i686-linux-gnu 34 | gcc: i686-linux-gnu-gcc 35 | libc_package: libc-dev-i386-cross 36 | host_target: i686-unknown-linux-gnu 37 | - build: aarch64-linux 38 | os: ubuntu-latest 39 | target: aarch64-unknown-linux-gnu 40 | gcc_package: gcc-aarch64-linux-gnu 41 | gcc: aarch64-linux-gnu-gcc 42 | qemu: qemu-aarch64 -L /usr/aarch64-linux-gnu 43 | qemu_target: aarch64-linux-user 44 | host_target: aarch64-unknown-linux-gnu 45 | - build: riscv64-linux 46 | os: ubuntu-latest 47 | target: riscv64gc-unknown-linux-gnu 48 | gcc_package: gcc-riscv64-linux-gnu 49 | gcc: riscv64-linux-gnu-gcc 50 | qemu: qemu-riscv64 -L /usr/riscv64-linux-gnu 51 | qemu_target: riscv64-linux-user 52 | host_target: riscv64gc-unknown-linux-gnu 53 | steps: 54 | - uses: actions/checkout@v4 55 | - name: Configure Cargo target 56 | run: | 57 | echo CARGO_BUILD_TARGET=${{ matrix.target }} >> $GITHUB_ENV 58 | rustup target add ${{ matrix.target }} 59 | if: matrix.target != '' 60 | 61 | - uses: actions/cache@v4 62 | with: 63 | path: ${{ runner.tool_cache }}/qemu 64 | key: qemu-${{ matrix.target }}-${{ env.QEMU_BUILD_VERSION }}-patched 65 | if: matrix.target != '' && matrix.os == 'ubuntu-latest' 66 | 67 | - name: Install cross-compilation tools 68 | run: | 69 | set -ex 70 | sudo apt-get update 71 | sudo apt-get install -y ${{ matrix.gcc_package }} ninja-build libglib2.0-dev 72 | upcase=$(echo ${{ matrix.host_target }} | awk '{ print toupper($0) }' | sed 's/-/_/g') 73 | echo CARGO_TARGET_${upcase}_LINKER=${{ matrix.gcc }} >> $GITHUB_ENV 74 | echo CC_${{ matrix.target }}=${{ matrix.gcc }} >> $GITHUB_ENV 75 | if: matrix.gcc_package != '' && matrix.os == 'ubuntu-latest' 76 | 77 | - name: Install cross-compilation libraries 78 | run: | 79 | set -ex 80 | sudo apt-get update 81 | sudo apt-get install -y ${{ matrix.libc_package }} 82 | if: matrix.libc_package != '' && matrix.os == 'ubuntu-latest' 83 | 84 | - name: Install qemu 85 | run: | 86 | set -ex 87 | 88 | # Configure Cargo for cross compilation and tell it how it can run 89 | # cross executables 90 | upcase=$(echo ${{ matrix.host_target }} | awk '{ print toupper($0) }' | sed 's/-/_/g') 91 | echo CARGO_TARGET_${upcase}_RUNNER=${{ runner.tool_cache }}/qemu/bin/${{ matrix.qemu }} >> $GITHUB_ENV 92 | 93 | # See if qemu is already in the cache 94 | if [ -f ${{ runner.tool_cache }}/qemu/bin/${{ matrix.qemu }} ]; then 95 | exit 0 96 | fi 97 | 98 | # Download and build qemu from source since the most recent release is 99 | # way faster at arm emulation than the current version github actions' 100 | # ubuntu image uses. Disable as much as we can to get it to build 101 | # quickly. 102 | cd 103 | curl https://download.qemu.org/qemu-$QEMU_BUILD_VERSION.tar.xz | tar xJf - 104 | cd qemu-$QEMU_BUILD_VERSION 105 | patch -p1 < $GITHUB_WORKSPACE/ci/translate-errno.patch 106 | patch -p1 < $GITHUB_WORKSPACE/ci/getsockopt-timeouts.patch 107 | patch -p1 < $GITHUB_WORKSPACE/ci/s390x-stat-have-nsec.patch 108 | patch -p1 < $GITHUB_WORKSPACE/ci/aarch64-o-largefile.patch 109 | patch -p1 < $GITHUB_WORKSPACE/ci/tcgets2-tcsets2.patch 110 | patch -p1 < $GITHUB_WORKSPACE/ci/tiocgsid.patch 111 | patch -p1 < $GITHUB_WORKSPACE/ci/more-sockopts.patch 112 | patch -p1 < $GITHUB_WORKSPACE/ci/pidfd-open.patch 113 | patch -p1 < $GITHUB_WORKSPACE/ci/select-setsize.patch 114 | ./configure --target-list=${{ matrix.qemu_target }} --prefix=${{ runner.tool_cache }}/qemu --disable-tools --disable-slirp --disable-fdt --disable-capstone --disable-docs 115 | ninja -C build install 116 | if: matrix.qemu != '' && matrix.os == 'ubuntu-latest' 117 | 118 | - name: cargo test 119 | run: | 120 | cargo test 121 | env: 122 | RUST_BACKTRACE: 1 123 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # This file tells tools we use rustfmt. We use the default settings. 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | *Note*: this Code of Conduct pertains to individuals' behavior. Please also see the [Organizational Code of Conduct][OCoC]. 4 | 5 | ## Our Pledge 6 | 7 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to creating a positive environment include: 12 | 13 | * Using welcoming and inclusive language 14 | * Being respectful of differing viewpoints and experiences 15 | * Gracefully accepting constructive criticism 16 | * Focusing on what is best for the community 17 | * Showing empathy towards other community members 18 | 19 | Examples of unacceptable behavior by participants include: 20 | 21 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 22 | * Trolling, insulting/derogatory comments, and personal or political attacks 23 | * Public or private harassment 24 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 25 | * Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Our Responsibilities 28 | 29 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 30 | 31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the Bytecode Alliance CoC team at [report@bytecodealliance.org](mailto:report@bytecodealliance.org). The CoC team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The CoC team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 40 | 41 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the Bytecode Alliance's leadership. 42 | 43 | ## Attribution 44 | 45 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 46 | 47 | [OCoC]: https://github.com/sunfishcode/eyra/blob/main/ORG_CODE_OF_CONDUCT.md 48 | [homepage]: https://www.contributor-covenant.org 49 | [version]: https://www.contributor-covenant.org/version/1/4/ 50 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Short version for non-lawyers: 2 | 3 | `eyra` is triple-licensed under Apache 2.0 with the LLVM Exception, 4 | Apache 2.0, and MIT terms. 5 | 6 | 7 | Longer version: 8 | 9 | Copyrights in the `eyra` project are retained by their contributors. 10 | No copyright assignment is required to contribute to the `eyra` 11 | project. 12 | 13 | Some files include code derived from Rust's `libstd`; see the comments in 14 | the code for details. 15 | 16 | Except as otherwise noted (below and/or in individual files), `eyra` 17 | is licensed under: 18 | 19 | - the Apache License, Version 2.0, with the LLVM Exception 20 | or 21 | 22 | - the Apache License, Version 2.0 23 | or 24 | , 25 | - or the MIT license 26 | or 27 | , 28 | 29 | at your option. 30 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eyra" 3 | version = "0.22.0" 4 | authors = [ 5 | "Dan Gohman ", 6 | ] 7 | description = "Rust programs written entirely in Rust" 8 | documentation = "https://docs.rs/eyra" 9 | license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" 10 | repository = "https://github.com/sunfishcode/eyra" 11 | edition = "2021" 12 | exclude = ["/.github", "ci"] 13 | keywords = ["linux"] 14 | 15 | [dependencies] 16 | c-gull = { version = "0.22.1", default-features = false, features = ["eyra"] } 17 | 18 | [dev-dependencies] 19 | assert_cmd = "2.0.12" 20 | similar-asserts = "1.1.0" 21 | rand = "0.9.0" 22 | libc = "0.2.151" 23 | cfg-if = "1.0.0" 24 | rand_xorshift = "0.4.0" 25 | 26 | # Test that the ctor crate works under eyra. 27 | ctor = "0.4.0" 28 | 29 | # Check if rustup is installed for tests 30 | which = "7.0.0" 31 | 32 | # Test that the core_simd crate works under eyra. 33 | # TODO: Reenable this when the crate compiles on nightly. Currently it gets: 34 | # - error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: simd_shuffle index must be a SIMD vector of `u32`, got `[u32; 4]` 35 | #core_simd = { git = "https://github.com/rust-lang/portable-simd" } 36 | 37 | # When generating documentation for docs.rs, don't enable "be-std", since we 38 | # don't need to duplicate std's documentation. 39 | [package.metadata.docs.rs] 40 | no-default-features = true 41 | 42 | [features] 43 | default = ["be-std", "threadsafe-setenv"] 44 | 45 | # Enable features that depend on std. Disable this for `no_std`. 46 | std = ["c-gull/std"] 47 | 48 | # This makes `setenv` and friends thread-safe by leaking memory. 49 | threadsafe-setenv = ["c-gull/threadsafe-setenv"] 50 | 51 | # Enable logging of program and thread startup and shutdown. 52 | log = ["c-gull/log"] 53 | 54 | # Install `atomic_dbg::log` as a logger. 55 | atomic-dbg-logger = ["c-gull/atomic-dbg-logger"] 56 | 57 | # Install the `env_logger` crate as a logger. 58 | env_logger = ["c-gull/env_logger", "std"] 59 | 60 | # Disable logging. 61 | max_level_off = ["c-gull/max_level_off"] 62 | 63 | # Enable experimental support for performing startup-time relocations, needed 64 | # to support statically-linked PIE executables. 65 | experimental-relocate = ["c-gull/experimental-relocate"] 66 | 67 | # Have eyra do `use std::*;` so that it can be used as `std`. 68 | be-std = ["std"] 69 | 70 | # This extends the `syscall` function with suppport for more syscalls. This is 71 | # not enabled by default because it increases the code size of `syscall` by 72 | # several kibibytes and isn't needed by most Rust programs. 73 | extra-syscalls = ["c-gull/extra-syscalls"] 74 | 75 | # Enable `todo!()` stubs for unimplemented functions. 76 | todo = ["c-gull/todo"] 77 | 78 | # Enable `unimplemented!()` stubs for deprecated functions. 79 | deprecated-and-unimplemented = ["c-gull/deprecated-and-unimplemented"] 80 | 81 | # Provide a `#[lang = eh_personality]` function suitable for unwinding (for 82 | # no-std). 83 | # 84 | # If you know your program never unwinds and want smaller code size, use 85 | # "eh-personality-continue" instead. 86 | # 87 | # This is only needed in no-std builds, as std provides a personality. See 88 | # [the "personality" feature of the unwinding crate] for more details. 89 | # 90 | # [the "personality" feature of the unwinding crate]: https://crates.io/crates/unwinding#personality-and-other-utilities 91 | eh-personality = ["c-gull/eh-personality"] 92 | 93 | # Provide a `#[lang = eh_personality]` function that just returns 94 | # `CONTINUE_UNWIND` (for no-std). Use this if you know your program will never 95 | # unwind and don't want any extra code. 96 | eh-personality-continue = ["c-gull/eh-personality-continue"] 97 | 98 | # Provide a `#[panic_handler]` function suitable for unwinding (for no-std). 99 | # 100 | # If you know your program never panics and want smaller code size, use 101 | # "panic-handler-trap" instead. 102 | # 103 | # This is only needed in no-std builds, as std provides a panic handler. See 104 | # [the "panic-handler" feature of the unwinding crate] for more details. 105 | # 106 | # [the "panic-handler" feature of the unwinding crate]: https://crates.io/crates/unwinding#personality-and-other-utilities 107 | panic-handler = ["c-gull/panic-handler"] 108 | 109 | # Provide a `#[panic_handler]` function that just traps (for no-std). Use this 110 | # if you know your program will never panic and don't want any extra code. 111 | panic-handler-trap = ["c-gull/panic-handler-trap"] 112 | 113 | # Provide a `#[global_allocator]` function (for no-std). 114 | # 115 | # This is only needed in no-std builds, as std provides a global allocator. 116 | # Alternatively, you can define the global allocator manually; see the 117 | # example-crates/custom-allocator example. 118 | global-allocator = ["c-gull/global-allocator"] 119 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /ORG_CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Bytecode Alliance Organizational Code of Conduct (OCoC) 2 | 3 | *Note*: this Code of Conduct pertains to organizations' behavior. Please also see the [Individual Code of Conduct](CODE_OF_CONDUCT.md). 4 | 5 | ## Preamble 6 | 7 | The Bytecode Alliance (BA) welcomes involvement from organizations, 8 | including commercial organizations. This document is an 9 | *organizational* code of conduct, intended particularly to provide 10 | guidance to commercial organizations. It is distinct from the 11 | [Individual Code of Conduct (ICoC)](CODE_OF_CONDUCT.md), and does not 12 | replace the ICoC. This OCoC applies to any group of people acting in 13 | concert as a BA member or as a participant in BA activities, whether 14 | or not that group is formally incorporated in some jurisdiction. 15 | 16 | The code of conduct described below is not a set of rigid rules, and 17 | we did not write it to encompass every conceivable scenario that might 18 | arise. For example, it is theoretically possible there would be times 19 | when asserting patents is in the best interest of the BA community as 20 | a whole. In such instances, consult with the BA, strive for 21 | consensus, and interpret these rules with an intent that is generous 22 | to the community the BA serves. 23 | 24 | While we may revise these guidelines from time to time based on 25 | real-world experience, overall they are based on a simple principle: 26 | 27 | *Bytecode Alliance members should observe the distinction between 28 | public community functions and private functions — especially 29 | commercial ones — and should ensure that the latter support, or at 30 | least do not harm, the former.* 31 | 32 | ## Guidelines 33 | 34 | * **Do not cause confusion about Wasm standards or interoperability.** 35 | 36 | Having an interoperable WebAssembly core is a high priority for 37 | the BA, and members should strive to preserve that core. It is fine 38 | to develop additional non-standard features or APIs, but they 39 | should always be clearly distinguished from the core interoperable 40 | Wasm. 41 | 42 | Treat the WebAssembly name and any BA-associated names with 43 | respect, and follow BA trademark and branding guidelines. If you 44 | distribute a customized version of software originally produced by 45 | the BA, or if you build a product or service using BA-derived 46 | software, use names that clearly distinguish your work from the 47 | original. (You should still provide proper attribution to the 48 | original, of course, wherever such attribution would normally be 49 | given.) 50 | 51 | Further, do not use the WebAssembly name or BA-associated names in 52 | other public namespaces in ways that could cause confusion, e.g., 53 | in company names, names of commercial service offerings, domain 54 | names, publicly-visible social media accounts or online service 55 | accounts, etc. It may sometimes be reasonable, however, to 56 | register such a name in a new namespace and then immediately donate 57 | control of that account to the BA, because that would help the project 58 | maintain its identity. 59 | 60 | For further guidance, see the BA Trademark and Branding Policy 61 | [TODO: create policy, then insert link]. 62 | 63 | * **Do not restrict contributors.** If your company requires 64 | employees or contractors to sign non-compete agreements, those 65 | agreements must not prevent people from participating in the BA or 66 | contributing to related projects. 67 | 68 | This does not mean that all non-compete agreements are incompatible 69 | with this code of conduct. For example, a company may restrict an 70 | employee's ability to solicit the company's customers. However, an 71 | agreement must not block any form of technical or social 72 | participation in BA activities, including but not limited to the 73 | implementation of particular features. 74 | 75 | The accumulation of experience and expertise in individual persons, 76 | who are ultimately free to direct their energy and attention as 77 | they decide, is one of the most important drivers of progress in 78 | open source projects. A company that limits this freedom may hinder 79 | the success of the BA's efforts. 80 | 81 | * **Do not use patents as offensive weapons.** If any BA participant 82 | prevents the adoption or development of BA technologies by 83 | asserting its patents, that undermines the purpose of the 84 | coalition. The collaboration fostered by the BA cannot include 85 | members who act to undermine its work. 86 | 87 | * **Practice responsible disclosure** for security vulnerabilities. 88 | Use designated, non-public reporting channels to disclose technical 89 | vulnerabilities, and give the project a reasonable period to 90 | respond, remediate, and patch. [TODO: optionally include the 91 | security vulnerability reporting URL here.] 92 | 93 | Vulnerability reporters may patch their company's own offerings, as 94 | long as that patching does not significantly delay the reporting of 95 | the vulnerability. Vulnerability information should never be used 96 | for unilateral commercial advantage. Vendors may legitimately 97 | compete on the speed and reliability with which they deploy 98 | security fixes, but withholding vulnerability information damages 99 | everyone in the long run by risking harm to the BA project's 100 | reputation and to the security of all users. 101 | 102 | * **Respect the letter and spirit of open source practice.** While 103 | there is not space to list here all possible aspects of standard 104 | open source practice, some examples will help show what we mean: 105 | 106 | * Abide by all applicable open source license terms. Do not engage 107 | in copyright violation or misattribution of any kind. 108 | 109 | * Do not claim others' ideas or designs as your own. 110 | 111 | * When others engage in publicly visible work (e.g., an upcoming 112 | demo that is coordinated in a public issue tracker), do not 113 | unilaterally announce early releases or early demonstrations of 114 | that work ahead of their schedule in order to secure private 115 | advantage (such as marketplace advantage) for yourself. 116 | 117 | The BA reserves the right to determine what constitutes good open 118 | source practices and to take action as it deems appropriate to 119 | encourage, and if necessary enforce, such practices. 120 | 121 | ## Enforcement 122 | 123 | Instances of organizational behavior in violation of the OCoC may 124 | be reported by contacting the Bytecode Alliance CoC team at 125 | [report@bytecodealliance.org](mailto:report@bytecodealliance.org). The 126 | CoC team will review and investigate all complaints, and will respond 127 | in a way that it deems appropriate to the circumstances. The CoC team 128 | is obligated to maintain confidentiality with regard to the reporter of 129 | an incident. Further details of specific enforcement policies may be 130 | posted separately. 131 | 132 | When the BA deems an organization in violation of this OCoC, the BA 133 | will, at its sole discretion, determine what action to take. The BA 134 | will decide what type, degree, and duration of corrective action is 135 | needed, if any, before a violating organization can be considered for 136 | membership (if it was not already a member) or can have its membership 137 | reinstated (if it was a member and the BA canceled its membership due 138 | to the violation). 139 | 140 | In practice, the BA's first approach will be to start a conversation, 141 | with punitive enforcement used only as a last resort. Violations 142 | often turn out to be unintentional and swiftly correctable with all 143 | parties acting in good faith. 144 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /ci/aarch64-o-largefile.patch: -------------------------------------------------------------------------------- 1 | From Dan Gohman 2 | Subject: [PATCH] Correct the definition of `O_LARGEFILE` on aarch64 3 | 4 | This fixes `fcntl` with `F_GETFL` from spuriously returning `O_NOFOLLOW` 5 | on hosts such as x86_64. 6 | 7 | diff -ur a/linux-user/aarch64/target_fcntl.h b/linux-user/aarch64/target_fcntl.h 8 | --- a/linux-user/aarch64/target_fcntl.h 9 | +++ b/linux-user/aarch64/target_fcntl.h 10 | @@ -11,6 +11,7 @@ 11 | #define TARGET_O_DIRECTORY 040000 /* must be a directory */ 12 | #define TARGET_O_NOFOLLOW 0100000 /* don't follow links */ 13 | #define TARGET_O_DIRECT 0200000 /* direct disk access hint */ 14 | +#define TARGET_O_LARGEFILE 0400000 15 | 16 | #include "../generic/fcntl.h" 17 | #endif 18 | -------------------------------------------------------------------------------- /ci/getsockopt-timeouts.patch: -------------------------------------------------------------------------------- 1 | From: Dan Gohman 2 | Subject: [PATCH] Avoid storing unexpected values for `SO_RCVTIMEO_NEW` etc. 3 | 4 | This issue is reported upstream [here]. 5 | 6 | [here]: https://gitlab.com/qemu-project/qemu/-/issues/885 7 | 8 | --- 9 | linux-user/generic/sockbits.h | 2 ++ 10 | linux-user/mips/sockbits.h | 2 ++ 11 | linux-user/sparc/sockbits.h | 2 ++ 12 | linux-user/syscall.c | 6 ++++++ 13 | 4 files changed, 12 insertions(+) 14 | 15 | diff --git a/linux-user/generic/sockbits.h b/linux-user/generic/sockbits.h 16 | index b3b4a8e44c..f95747e3cc 100644 17 | --- a/linux-user/generic/sockbits.h 18 | +++ b/linux-user/generic/sockbits.h 19 | @@ -36,6 +36,8 @@ 20 | #define TARGET_SO_SNDLOWAT 19 21 | #define TARGET_SO_RCVTIMEO 20 22 | #define TARGET_SO_SNDTIMEO 21 23 | +#define TARGET_SO_RCVTIMEO_NEW 66 24 | +#define TARGET_SO_SNDTIMEO_NEW 67 25 | 26 | /* Security levels - as per NRL IPv6 - don't actually do anything */ 27 | #define TARGET_SO_SECURITY_AUTHENTICATION 22 28 | diff --git a/linux-user/mips/sockbits.h b/linux-user/mips/sockbits.h 29 | index 562cad88e2..4d411f7b61 100644 30 | --- a/linux-user/mips/sockbits.h 31 | +++ b/linux-user/mips/sockbits.h 32 | @@ -39,6 +39,8 @@ 33 | #define TARGET_SO_RCVLOWAT 0x1004 /* receive low-water mark */ 34 | #define TARGET_SO_SNDTIMEO 0x1005 /* send timeout */ 35 | #define TARGET_SO_RCVTIMEO 0x1006 /* receive timeout */ 36 | +#define TARGET_SO_RCVTIMEO_NEW 66 37 | +#define TARGET_SO_SNDTIMEO_NEW 67 38 | #define TARGET_SO_ACCEPTCONN 0x1009 39 | #define TARGET_SO_PROTOCOL 0x1028 /* protocol type */ 40 | #define TARGET_SO_DOMAIN 0x1029 /* domain/socket family */ 41 | diff --git a/linux-user/sparc/sockbits.h b/linux-user/sparc/sockbits.h 42 | index 0a822e3e1f..8420ef9953 100644 43 | --- a/linux-user/sparc/sockbits.h 44 | +++ b/linux-user/sparc/sockbits.h 45 | @@ -26,6 +26,8 @@ 46 | #define TARGET_SO_SNDLOWAT 0x1000 47 | #define TARGET_SO_RCVTIMEO 0x2000 48 | #define TARGET_SO_SNDTIMEO 0x4000 49 | +#define TARGET_SO_RCVTIMEO_NEW 68 50 | +#define TARGET_SO_SNDTIMEO_NEW 69 51 | #define TARGET_SO_ACCEPTCONN 0x8000 52 | 53 | #define TARGET_SO_SNDBUF 0x1001 54 | diff --git a/linux-user/syscall.c b/linux-user/syscall.c 55 | index a8eae3c4ac..8326e03a19 100644 56 | --- a/linux-user/syscall.c 57 | +++ b/linux-user/syscall.c 58 | @@ -2348,6 +2348,9 @@ set_timeout: 59 | case TARGET_SO_SNDTIMEO: 60 | optname = SO_SNDTIMEO; 61 | goto set_timeout; 62 | + case TARGET_SO_RCVTIMEO_NEW: 63 | + case TARGET_SO_SNDTIMEO_NEW: 64 | + return -TARGET_ENOPROTOOPT; 65 | case TARGET_SO_ATTACH_FILTER: 66 | { 67 | struct target_sock_fprog *tfprog; 68 | @@ -2595,6 +2598,9 @@ get_timeout: 69 | case TARGET_SO_SNDTIMEO: 70 | optname = SO_SNDTIMEO; 71 | goto get_timeout; 72 | + case TARGET_SO_RCVTIMEO_NEW: 73 | + case TARGET_SO_SNDTIMEO_NEW: 74 | + return -TARGET_ENOPROTOOPT; 75 | case TARGET_SO_PEERCRED: { 76 | struct ucred cr; 77 | socklen_t crlen; 78 | -- 79 | 2.32.0 80 | 81 | -------------------------------------------------------------------------------- /ci/more-sockopts.patch: -------------------------------------------------------------------------------- 1 | From Dan Gohman 2 | Subject: [PATCH] Implement various socket options. 3 | 4 | This implements the `SO_INCOMING_CPU`, `SO_COOKIE`, and `SO_PROTOCOL` 5 | socket options. 6 | 7 | diff -ur -x roms -x build a/linux-user/generic/sockbits.h b/linux-user/generic/sockbits.h 8 | --- a/linux-user/generic/sockbits.h 9 | +++ b/linux-user/generic/sockbits.h 10 | @@ -60,4 +60,10 @@ 11 | 12 | #define TARGET_SO_PROTOCOL 38 13 | #define TARGET_SO_DOMAIN 39 14 | +#ifndef TARGET_SO_INCOMING_CPU 15 | +#define TARGET_SO_INCOMING_CPU 49 16 | +#endif 17 | +#ifndef TARGET_SO_COOKIE 18 | +#define TARGET_SO_COOKIE 57 19 | +#endif 20 | #endif 21 | diff -ur -x roms -x build a/linux-user/mips/sockbits.h b/linux-user/mips/sockbits.h 22 | --- a/linux-user/mips/sockbits.h 23 | +++ b/linux-user/mips/sockbits.h 24 | @@ -73,6 +73,9 @@ 25 | #define TARGET_SO_RCVBUFFORCE 33 26 | #define TARGET_SO_PASSSEC 34 27 | 28 | +#define TARGET_SO_INCOMING_CPU 49 29 | +#define TARGET_SO_COOKIE 57 30 | + 31 | /** sock_type - Socket types 32 | * 33 | * Please notice that for binary compat reasons MIPS has to 34 | diff -ur -x roms -x build a/linux-user/syscall.c b/linux-user/syscall.c 35 | --- a/linux-user/syscall.c 36 | +++ b/linux-user/syscall.c 37 | @@ -2476,6 +2476,9 @@ 38 | case TARGET_SO_RCVLOWAT: 39 | optname = SO_RCVLOWAT; 40 | break; 41 | + case TARGET_SO_INCOMING_CPU: 42 | + optname = SO_INCOMING_CPU; 43 | + break; 44 | default: 45 | goto unimplemented; 46 | } 47 | @@ -2534,6 +2537,7 @@ 48 | { 49 | abi_long ret; 50 | int len, val; 51 | + int64_t val64; 52 | socklen_t lv; 53 | 54 | switch(level) { 55 | @@ -2733,6 +2737,27 @@ 56 | case TARGET_SO_DOMAIN: 57 | optname = SO_DOMAIN; 58 | goto int_case; 59 | + case TARGET_SO_INCOMING_CPU: 60 | + optname = SO_INCOMING_CPU; 61 | + goto int_case; 62 | + case TARGET_SO_COOKIE: 63 | + optname = SO_COOKIE; 64 | + if (get_user_u32(len, optlen)) 65 | + return -TARGET_EFAULT; 66 | + if (len < 0) 67 | + return -TARGET_EINVAL; 68 | + lv = sizeof(val64); 69 | + ret = get_errno(getsockopt(sockfd, level, optname, &val64, &lv)); 70 | + if (ret < 0) 71 | + return ret; 72 | + if (len > lv) 73 | + len = lv; 74 | + assert(len == 8); 75 | + if (put_user_u64(val64, optval_addr)) 76 | + return -TARGET_EFAULT; 77 | + if (put_user_u32(len, optlen)) 78 | + return -TARGET_EFAULT; 79 | + break; 80 | default: 81 | goto int_case; 82 | } 83 | @@ -2756,6 +2781,9 @@ 84 | case SO_ERROR: 85 | val = host_to_target_errno(val); 86 | break; 87 | + case SO_PROTOCOL: 88 | + val = host_to_target_errno(val); 89 | + break; 90 | } 91 | if (level == SOL_SOCKET && optname == SO_ERROR) { 92 | val = host_to_target_errno(val); 93 | -------------------------------------------------------------------------------- /ci/pidfd-open.patch: -------------------------------------------------------------------------------- 1 | From Dan Gohman 2 | Subject: [PATCH] Fix the flags argument of `pidfd_open`. 3 | 4 | This corrects the flags value of `pidfd_open` to avoid passing 5 | target flags to the host. Currently the only flag is `PIDFD_NONBLOCK` 6 | so we use the `fcntl_flags_tbl` to translate it. 7 | 8 | --- a/linux-user/syscall.c 9 | +++ b/linux-user/syscall.c 10 | @@ -9477,7 +9477,8 @@ 11 | #endif 12 | #if defined(__NR_pidfd_open) && defined(TARGET_NR_pidfd_open) 13 | case TARGET_NR_pidfd_open: 14 | - return get_errno(pidfd_open(arg1, arg2)); 15 | + return get_errno(pidfd_open(arg1, 16 | + target_to_host_bitmask(arg2, fcntl_flags_tbl))); 17 | #endif 18 | #if defined(__NR_pidfd_send_signal) && defined(TARGET_NR_pidfd_send_signal) 19 | case TARGET_NR_pidfd_send_signal: 20 | -------------------------------------------------------------------------------- /ci/s390x-stat-have-nsec.patch: -------------------------------------------------------------------------------- 1 | From: Dan Gohman 2 | Subject: [PATCH] Define `TARGET_STAT_HAVE_NSEC` for s390x 3 | 4 | Without this, The `fstat` syscall sets `st_mtime_nsec` and the other `_nsec` 5 | fields to 0. Libc `fstat` will sometimes use the `fstatat` or `fstat64` 6 | syscalls instead, which aren't affected, but the libc `fstat` on ubuntu-20.04 7 | on Github Actions appears to be affected. 8 | 9 | This can be seen in the `st_mtime_nsec` assert in tests/fs/futimens.rs. 10 | 11 | It's not yet known why upstream qemu doesn't define this. 12 | 13 | --- 14 | linux-user/generic/sockbits.h | 1 + 15 | 1 files changed, 1 insertions(+) 16 | 17 | diff -ur a/linux-user/syscall_defs.h b/linux-user/syscall_defs.h 18 | --- a/linux-user/syscall_defs.h 2021-08-24 10:35:41.000000000 -0700 19 | +++ b/linux-user/syscall_defs.h 2022-04-12 13:23:25.291064887 -0700 20 | @@ -2040,6 +2040,7 @@ 21 | abi_long __unused[3]; 22 | }; 23 | #elif defined(TARGET_S390X) 24 | +#define TARGET_STAT_HAVE_NSEC 25 | struct target_stat { 26 | abi_ulong st_dev; 27 | abi_ulong st_ino; 28 | -------------------------------------------------------------------------------- /ci/select-setsize.patch: -------------------------------------------------------------------------------- 1 | From Dan Gohman 2 | Subject: [PATCH] Remove the `FD_SETSIZE` limitation in `select` 3 | 4 | The `fd_set` type is limited to a fixed `FD_SETSIZE` number of file 5 | descriptors, however Linux's `select has no such limitation. Change 6 | the `select` implementation to using manual bit-vector logic to better 7 | implement the Linux semantics. 8 | 9 | diff -ur a/linux-user/syscall.c b/linux-user/syscall.c 10 | --- a/linux-user/syscall.c 11 | +++ b/linux-user/syscall.c 12 | @@ -664,8 +664,9 @@ 13 | char **, argv, char **, envp, int, flags) 14 | #if defined(TARGET_NR_select) || defined(TARGET_NR__newselect) || \ 15 | defined(TARGET_NR_pselect6) || defined(TARGET_NR_pselect6_time64) 16 | -safe_syscall6(int, pselect6, int, nfds, fd_set *, readfds, fd_set *, writefds, \ 17 | - fd_set *, exceptfds, struct timespec *, timeout, void *, sig) 18 | +safe_syscall6(int, pselect6, int, nfds, unsigned long *, readfds, \ 19 | + unsigned long *, writefds, unsigned long *, exceptfds, \ 20 | + struct timespec *, timeout, void *, sig) 21 | #endif 22 | #if defined(TARGET_NR_ppoll) || defined(TARGET_NR_ppoll_time64) 23 | safe_syscall5(int, ppoll, struct pollfd *, ufds, unsigned int, nfds, 24 | @@ -861,7 +862,7 @@ 25 | 26 | #if defined(TARGET_NR_select) || defined(TARGET_NR__newselect) || \ 27 | defined(TARGET_NR_pselect6) || defined(TARGET_NR_pselect6_time64) 28 | -static inline abi_long copy_from_user_fdset(fd_set *fds, 29 | +static inline abi_long copy_from_user_fdset(unsigned long *fds, 30 | abi_ulong target_fds_addr, 31 | int n) 32 | { 33 | @@ -875,7 +876,8 @@ 34 | 1))) 35 | return -TARGET_EFAULT; 36 | 37 | - FD_ZERO(fds); 38 | + memset(fds, 0, DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 39 | + sizeof(unsigned long)); 40 | k = 0; 41 | for (i = 0; i < nw; i++) { 42 | /* grab the abi_ulong */ 43 | @@ -883,7 +885,8 @@ 44 | for (j = 0; j < TARGET_ABI_BITS; j++) { 45 | /* check the bit inside the abi_ulong */ 46 | if ((b >> j) & 1) 47 | - FD_SET(k, fds); 48 | + fds[k / (sizeof(unsigned long) * 8)] |= 49 | + 1ul << (k % (sizeof(unsigned long) * 8)); 50 | k++; 51 | } 52 | } 53 | @@ -893,7 +896,8 @@ 54 | return 0; 55 | } 56 | 57 | -static inline abi_ulong copy_from_user_fdset_ptr(fd_set *fds, fd_set **fds_ptr, 58 | +static inline abi_ulong copy_from_user_fdset_ptr(unsigned long *fds, 59 | + unsigned long **fds_ptr, 60 | abi_ulong target_fds_addr, 61 | int n) 62 | { 63 | @@ -908,7 +912,7 @@ 64 | } 65 | 66 | static inline abi_long copy_to_user_fdset(abi_ulong target_fds_addr, 67 | - const fd_set *fds, 68 | + const unsigned long *fds, 69 | int n) 70 | { 71 | int i, nw, j, k; 72 | @@ -926,7 +930,10 @@ 73 | for (i = 0; i < nw; i++) { 74 | v = 0; 75 | for (j = 0; j < TARGET_ABI_BITS; j++) { 76 | - v |= ((abi_ulong)(FD_ISSET(k, fds) != 0) << j); 77 | + bool set = 78 | + (fds[k / (sizeof(unsigned long) * 8)] & 79 | + (1ul << (k % (sizeof(unsigned long) * 8)))) != 0; 80 | + v |= ((abi_ulong)set << j); 81 | k++; 82 | } 83 | __put_user(v, &target_fds[i]); 84 | @@ -1295,28 +1302,40 @@ 85 | abi_ulong rfd_addr, abi_ulong wfd_addr, 86 | abi_ulong efd_addr, abi_ulong target_tv_addr) 87 | { 88 | - fd_set rfds, wfds, efds; 89 | - fd_set *rfds_ptr, *wfds_ptr, *efds_ptr; 90 | + unsigned long *rfds, *wfds, *efds; 91 | + unsigned long *rfds_ptr, *wfds_ptr, *efds_ptr; 92 | struct timeval tv; 93 | struct timespec ts, *ts_ptr; 94 | abi_long ret; 95 | 96 | - ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n); 97 | + rfds = malloc(DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 98 | + sizeof(unsigned long)); 99 | + wfds = malloc(DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 100 | + sizeof(unsigned long)); 101 | + efds = malloc(DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 102 | + sizeof(unsigned long)); 103 | + 104 | + ret = copy_from_user_fdset_ptr(rfds, &rfds_ptr, rfd_addr, n); 105 | if (ret) { 106 | + free(rfds); free(wfds); free(efds); 107 | return ret; 108 | } 109 | - ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n); 110 | + ret = copy_from_user_fdset_ptr(wfds, &wfds_ptr, wfd_addr, n); 111 | if (ret) { 112 | + free(rfds); free(wfds); free(efds); 113 | return ret; 114 | } 115 | - ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n); 116 | + ret = copy_from_user_fdset_ptr(efds, &efds_ptr, efd_addr, n); 117 | if (ret) { 118 | + free(rfds); free(wfds); free(efds); 119 | return ret; 120 | } 121 | 122 | if (target_tv_addr) { 123 | - if (copy_from_user_timeval(&tv, target_tv_addr)) 124 | + if (copy_from_user_timeval(&tv, target_tv_addr)) { 125 | + free(rfds); free(wfds); free(efds); 126 | return -TARGET_EFAULT; 127 | + } 128 | ts.tv_sec = tv.tv_sec; 129 | ts.tv_nsec = tv.tv_usec * 1000; 130 | ts_ptr = &ts; 131 | @@ -1328,22 +1347,30 @@ 132 | ts_ptr, NULL)); 133 | 134 | if (!is_error(ret)) { 135 | - if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n)) 136 | + if (rfd_addr && copy_to_user_fdset(rfd_addr, rfds, n)) { 137 | + free(rfds); free(wfds); free(efds); 138 | return -TARGET_EFAULT; 139 | - if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n)) 140 | + } 141 | + if (wfd_addr && copy_to_user_fdset(wfd_addr, wfds, n)) { 142 | + free(rfds); free(wfds); free(efds); 143 | return -TARGET_EFAULT; 144 | - if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n)) 145 | + } 146 | + if (efd_addr && copy_to_user_fdset(efd_addr, efds, n)) { 147 | + free(rfds); free(wfds); free(efds); 148 | return -TARGET_EFAULT; 149 | + } 150 | 151 | if (target_tv_addr) { 152 | tv.tv_sec = ts.tv_sec; 153 | tv.tv_usec = ts.tv_nsec / 1000; 154 | if (copy_to_user_timeval(target_tv_addr, &tv)) { 155 | + free(rfds); free(wfds); free(efds); 156 | return -TARGET_EFAULT; 157 | } 158 | } 159 | } 160 | 161 | + free(rfds); free(wfds); free(efds); 162 | return ret; 163 | } 164 | 165 | @@ -1377,8 +1404,8 @@ 166 | bool time64) 167 | { 168 | abi_long rfd_addr, wfd_addr, efd_addr, n, ts_addr; 169 | - fd_set rfds, wfds, efds; 170 | - fd_set *rfds_ptr, *wfds_ptr, *efds_ptr; 171 | + unsigned long *rfds, *wfds, *efds; 172 | + unsigned long *rfds_ptr, *wfds_ptr, *efds_ptr; 173 | struct timespec ts, *ts_ptr; 174 | abi_long ret; 175 | 176 | @@ -1399,16 +1426,26 @@ 177 | efd_addr = arg4; 178 | ts_addr = arg5; 179 | 180 | - ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n); 181 | + rfds = malloc(DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 182 | + sizeof(unsigned long)); 183 | + wfds = malloc(DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 184 | + sizeof(unsigned long)); 185 | + efds = malloc(DIV_ROUND_UP(n, sizeof(unsigned long) * 8) * 186 | + sizeof(unsigned long)); 187 | + 188 | + ret = copy_from_user_fdset_ptr(rfds, &rfds_ptr, rfd_addr, n); 189 | if (ret) { 190 | + free(rfds); free(wfds); free(efds); 191 | return ret; 192 | } 193 | - ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n); 194 | + ret = copy_from_user_fdset_ptr(wfds, &wfds_ptr, wfd_addr, n); 195 | if (ret) { 196 | + free(rfds); free(wfds); free(efds); 197 | return ret; 198 | } 199 | - ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n); 200 | + ret = copy_from_user_fdset_ptr(efds, &efds_ptr, efd_addr, n); 201 | if (ret) { 202 | + free(rfds); free(wfds); free(efds); 203 | return ret; 204 | } 205 | 206 | @@ -1419,10 +1456,12 @@ 207 | if (ts_addr) { 208 | if (time64) { 209 | if (target_to_host_timespec64(&ts, ts_addr)) { 210 | + free(rfds); free(wfds); free(efds); 211 | return -TARGET_EFAULT; 212 | } 213 | } else { 214 | if (target_to_host_timespec(&ts, ts_addr)) { 215 | + free(rfds); free(wfds); free(efds); 216 | return -TARGET_EFAULT; 217 | } 218 | } 219 | @@ -1436,6 +1475,7 @@ 220 | if (arg6) { 221 | arg7 = lock_user(VERIFY_READ, arg6, sizeof(*arg7) * 2, 1); 222 | if (!arg7) { 223 | + free(rfds); free(wfds); free(efds); 224 | return -TARGET_EFAULT; 225 | } 226 | arg_sigset = tswapal(arg7[0]); 227 | @@ -1445,6 +1485,7 @@ 228 | if (arg_sigset) { 229 | ret = process_sigsuspend_mask(&sig.set, arg_sigset, arg_sigsize); 230 | if (ret != 0) { 231 | + free(rfds); free(wfds); free(efds); 232 | return ret; 233 | } 234 | sig_ptr = &sig; 235 | @@ -1460,25 +1501,31 @@ 236 | } 237 | 238 | if (!is_error(ret)) { 239 | - if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n)) { 240 | + if (rfd_addr && copy_to_user_fdset(rfd_addr, rfds, n)) { 241 | + free(rfds); free(wfds); free(efds); 242 | return -TARGET_EFAULT; 243 | } 244 | - if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n)) { 245 | + if (wfd_addr && copy_to_user_fdset(wfd_addr, wfds, n)) { 246 | + free(rfds); free(wfds); free(efds); 247 | return -TARGET_EFAULT; 248 | } 249 | - if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n)) { 250 | + if (efd_addr && copy_to_user_fdset(efd_addr, efds, n)) { 251 | + free(rfds); free(wfds); free(efds); 252 | return -TARGET_EFAULT; 253 | } 254 | if (time64) { 255 | if (ts_addr && host_to_target_timespec64(ts_addr, &ts)) { 256 | + free(rfds); free(wfds); free(efds); 257 | return -TARGET_EFAULT; 258 | } 259 | } else { 260 | if (ts_addr && host_to_target_timespec(ts_addr, &ts)) { 261 | + free(rfds); free(wfds); free(efds); 262 | return -TARGET_EFAULT; 263 | } 264 | } 265 | } 266 | + free(rfds); free(wfds); free(efds); 267 | return ret; 268 | } 269 | #endif 270 | -------------------------------------------------------------------------------- /ci/tiocgsid.patch: -------------------------------------------------------------------------------- 1 | From Dan Gohman 2 | Subject: [PATCH] Fix the definition of `TIOCGSID`. 3 | 4 | This corrects the value of `TIOCGSID`. 5 | 6 | diff -ur a/linux-user/ioctls.h b/linux-user/ioctls.h 7 | --- a/linux-user/ioctls.h 8 | +++ b/linux-user/ioctls.h 9 | @@ -22,7 +28,7 @@ 10 | IOCTL(TIOCSCTTY, 0, TYPE_INT) 11 | IOCTL(TIOCGPGRP, IOC_R, MK_PTR(TYPE_INT)) 12 | IOCTL(TIOCSPGRP, IOC_W, MK_PTR(TYPE_INT)) 13 | - IOCTL(TIOCGSID, IOC_W, MK_PTR(TYPE_INT)) 14 | + IOCTL(TIOCGSID, IOC_R, MK_PTR(TYPE_INT)) 15 | IOCTL(TIOCOUTQ, IOC_R, MK_PTR(TYPE_INT)) 16 | IOCTL(TIOCSTI, IOC_W, MK_PTR(TYPE_INT)) 17 | IOCTL(TIOCMGET, IOC_R, MK_PTR(TYPE_INT)) 18 | -------------------------------------------------------------------------------- /ci/translate-errno.patch: -------------------------------------------------------------------------------- 1 | From: Dan Gohman 2 | Subject: [PATCH] Translate errno codes from host to target for `SO_ERROR`. 3 | 4 | This issue is reported upstream [here]. 5 | 6 | [here]: https://gitlab.com/qemu-project/qemu/-/issues/872 7 | 8 | --- 9 | linux-user/syscall.c | 3 +++ 10 | 1 file changed, 3 insertions(+) 11 | 12 | diff --git a/linux-user/syscall.c b/linux-user/syscall.c 13 | index b9b18a7eaf..a8eae3c4ac 100644 14 | --- a/linux-user/syscall.c 15 | +++ b/linux-user/syscall.c 16 | @@ -2767,6 +2767,9 @@ get_timeout: 17 | if (optname == SO_TYPE) { 18 | val = host_to_target_sock_type(val); 19 | } 20 | + if (level == SOL_SOCKET && optname == SO_ERROR) { 21 | + val = host_to_target_errno(val); 22 | + } 23 | if (len > lv) 24 | len = lv; 25 | if (len == 4) { 26 | -- 27 | 2.32.0 28 | 29 | -------------------------------------------------------------------------------- /example-crates/all-from-source/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/all-from-source/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "all-from-source" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | eyra = { path = "../..", default-features = false, features = ["be-std", "threadsafe-setenv"] } 9 | 10 | [profile.release] 11 | lto = true 12 | codegen-units = 1 13 | 14 | # This is just an example crate, and not part of the eyra workspace. 15 | [workspace] 16 | -------------------------------------------------------------------------------- /example-crates/all-from-source/README.md: -------------------------------------------------------------------------------- 1 | This example demonstrates building a program completely from source, without 2 | using any prebuilt libraries, if built with `-Zbuild-std`. 3 | 4 | For example, use `cargo rustc` to build the LLVM IR file and test that it has 5 | no external function declarations (other than LLVM intrinsics). 6 | 7 | ``` 8 | $ cargo +nightly rustc -Zbuild-std --release --target=x86_64-unknown-linux-gnu -- --emit=llvm-ir 9 | [...] 10 | $ grep ^declare ./target/x86_64-unknown-linux-gnu/release/deps/all_from_source-*.ll | grep -v '@llvm' 11 | $ 12 | ``` 13 | -------------------------------------------------------------------------------- /example-crates/all-from-source/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/all-from-source/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | println!("Hello, world!"); 5 | } 6 | -------------------------------------------------------------------------------- /example-crates/extern-crate-eyra-optional-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/extern-crate-eyra-optional-example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eyra-optional-example" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | # Depend on Eyra... optionally! 9 | eyra = { path = "../..", optional = true } 10 | 11 | # This is just an example crate, and not part of the eyra workspace. 12 | [workspace] 13 | -------------------------------------------------------------------------------- /example-crates/extern-crate-eyra-optional-example/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra as an optional dependency. 2 | 3 | By default, it looks like a normal hello world program. When compiled 4 | with `--feature=eyra`, it's a hello world program that uses Eyra. 5 | 6 | And when compiled with `--features=eyra,eyra/log,eyra/env_logger`, it's 7 | a hello world program that uses Eyra and can log program startup and 8 | shutdown: 9 | 10 | ```console 11 | $ RUST_LOG=trace cargo +nightly run --quiet --features=eyra,eyra/log,eyra/env_logger 12 | [TRACE origin::program] Program started 13 | [TRACE origin::thread] Main Thread[91601] initialized 14 | [TRACE origin::program] Calling `.init_array`-registered function `0x559006f43500(1, 0x7ffd7e5bacd8, 0x7ffd7e5bace8)` 15 | [TRACE origin::program] Calling `origin_main(1, 0x7ffd7e5bacd8, 0x7ffd7e5bace8)` 16 | Hello, world! 17 | [TRACE origin::program] `origin_main` returned `0` 18 | [TRACE origin::thread] Thread[91601] calling `at_thread_exit`-registered function 19 | [TRACE origin::thread] Thread[91601] calling `at_thread_exit`-registered function 20 | [TRACE origin::program] Program exiting 21 | ``` 22 | -------------------------------------------------------------------------------- /example-crates/extern-crate-eyra-optional-example/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker, when Eyra is enabled. 3 | if std::env::var("CARGO_FEATURE_EYRA").is_ok() { 4 | println!("cargo:rustc-link-arg=-nostartfiles"); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example-crates/extern-crate-eyra-optional-example/src/main.rs: -------------------------------------------------------------------------------- 1 | // Pull in Eyra libraries... optionally! 2 | #[cfg(feature = "eyra")] 3 | extern crate eyra; 4 | 5 | fn main() { 6 | println!("Hello, world!"); 7 | } 8 | -------------------------------------------------------------------------------- /example-crates/extern-crate-hello-world/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/extern-crate-hello-world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | eyra = { path = "../.." } 9 | 10 | # This is just an example crate, and not part of the eyra workspace. 11 | [workspace] 12 | -------------------------------------------------------------------------------- /example-crates/extern-crate-hello-world/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra. 2 | 3 | See the [detailed walkthrough] for a list of how this hello world 4 | example crate works. 5 | 6 | [detailed walkthrough]: https://github.com/sunfishcode/eyra#in-detail 7 | -------------------------------------------------------------------------------- /example-crates/extern-crate-hello-world/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/extern-crate-hello-world/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | println!("Hello, world!"); 5 | } 6 | -------------------------------------------------------------------------------- /example-crates/eyra-libc-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/eyra-libc-example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eyra-libc-example" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | std = { package = "eyra", path = "../.." } 9 | libc = "0.2.148" 10 | 11 | # This is just an example crate, and not part of the eyra workspace. 12 | [workspace] 13 | -------------------------------------------------------------------------------- /example-crates/eyra-libc-example/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra. 2 | 3 | This is similar to [hello-world], but additionally demonstrates the 4 | use of `libc` APIs by saying "Hello, world!" using the libc `printf` 5 | interface. 6 | 7 | The `printf` implementation is provided by [c-gull]. 8 | 9 | [hello-world]: https://github.com/sunfishcode/eyra/tree/main/example-crates/hello-world/ 10 | [c-gull]: https://github.com/sunfishcode/c-ward/tree/main/c-gull 11 | -------------------------------------------------------------------------------- /example-crates/eyra-libc-example/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/eyra-libc-example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello world using Rust `println!`!"); 3 | unsafe { libc::printf("Hello world using libc `printf`!\n\0".as_ptr().cast()); } 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/eyra-optional-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/eyra-optional-example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eyra-optional-example" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | # Depend on Eyra... optionally! 9 | std = { package = "eyra", path = "../..", optional = true } 10 | 11 | [features] 12 | eyra = ["dep:std"] 13 | 14 | # This is just an example crate, and not part of the eyra workspace. 15 | [workspace] 16 | -------------------------------------------------------------------------------- /example-crates/eyra-optional-example/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra as an optional dependency. 2 | 3 | By default, it looks like a normal hello world program. When compiled 4 | with `--feature=eyra`, it's a hello world program that uses Eyra. 5 | 6 | And when compiled with `--features=eyra,eyra/log,eyra/env_logger`, it's 7 | a hello world program that uses Eyra and can log program startup and 8 | shutdown: 9 | 10 | ```console 11 | $ RUST_LOG=trace cargo +nightly run --quiet --features=eyra,eyra/log,eyra/env_logger 12 | [TRACE origin::program] Program started 13 | [TRACE origin::thread] Main Thread[91601] initialized 14 | [TRACE origin::program] Calling `.init_array`-registered function `0x559006f43500(1, 0x7ffd7e5bacd8, 0x7ffd7e5bace8)` 15 | [TRACE origin::program] Calling `origin_main(1, 0x7ffd7e5bacd8, 0x7ffd7e5bace8)` 16 | Hello, world! 17 | [TRACE origin::program] `origin_main` returned `0` 18 | [TRACE origin::thread] Thread[91601] calling `at_thread_exit`-registered function 19 | [TRACE origin::thread] Thread[91601] calling `at_thread_exit`-registered function 20 | [TRACE origin::program] Program exiting 21 | ``` 22 | -------------------------------------------------------------------------------- /example-crates/eyra-optional-example/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker, when Eyra is enabled. 3 | if std::env::var("CARGO_FEATURE_EYRA").is_ok() { 4 | println!("cargo:rustc-link-arg=-nostartfiles"); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example-crates/eyra-optional-example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /example-crates/eyra-panic-example/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/eyra-panic-example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eyra-panic-example" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | std = { package = "eyra", path = "../.." } 9 | 10 | # This is just an example crate, and not part of the eyra workspace. 11 | [workspace] 12 | -------------------------------------------------------------------------------- /example-crates/eyra-panic-example/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the `panic!` mechanism with Eyra. 2 | 3 | This is similar to [hello-world], but does a `panic!` instead of a 4 | `println!`. 5 | 6 | [hello-world]: https://github.com/sunfishcode/eyra/tree/main/example-crates/hello-world/ 7 | -------------------------------------------------------------------------------- /example-crates/eyra-panic-example/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/eyra-panic-example/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | panic!("Uh oh!"); 3 | } 4 | -------------------------------------------------------------------------------- /example-crates/hello-world-lto/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/hello-world-lto/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world-lto" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | std = { package = "eyra", path = "../.." } 9 | 10 | # Enable LTO. 11 | [profile.release] 12 | lto = true 13 | 14 | # This is just an example crate, and not part of the eyra workspace. 15 | [workspace] 16 | -------------------------------------------------------------------------------- /example-crates/hello-world-lto/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra with LTO! 2 | 3 | This is the same as the [hello-world] example, but enables LTO. 4 | 5 | [hello-world]: https://github.com/sunfishcode/eyra/tree/main/example-crates/hello-world/ 6 | -------------------------------------------------------------------------------- /example-crates/hello-world-lto/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/hello-world-lto/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /example-crates/hello-world-small/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/hello-world-small/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world-small" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | eyra = { path = "../.." } 9 | 10 | [profile.release] 11 | # Enable options from min-sized-rust: 12 | strip = true # Automatically strip symbols from the binary. 13 | opt-level = "z" # Optimize for size. 14 | lto = true 15 | codegen-units = 1 16 | panic = "abort" 17 | 18 | # This is just an example crate, and not part of the eyra workspace. 19 | [workspace] 20 | -------------------------------------------------------------------------------- /example-crates/hello-world-small/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra with a smaller binary size! 2 | 3 | This is the same as the [hello-world] example, but enables some options 4 | described in [min-sized-rust] to reduce the size of the final binary. 5 | 6 | It uses the [workaround to support -Zbuild-std], and can be built with 7 | a command like this: 8 | 9 | ```console 10 | $ RUSTFLAGS="-Z location-detail=none -Zfmt-debug=none -C relocation-model=static -Ctarget-feature=+crt-static" cargo +nightly run -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort,optimize_for_size --target x86_64-unknown-linux-gnu --release 11 | ``` 12 | 13 | This applies all the techniques described on the [min-sized-rust] page 14 | before [Remove `core::fmt` with `no_main` and Careful Usage of `libstd`]. 15 | 16 | As of this writing, this compiles to 24,616 bytes. For comparison, using all 17 | these same optimizations without Eyra, and using `x86_64-unknown-linux-musl` 18 | (which produces smaller statically-linked binaries than 19 | `x86_64-unknown-linux-gnu`), compiles to 30,288 bytes. 20 | 21 | If you're interested in going further down the `#![no_main]`/`#![no_std]` 22 | path, consider [using Origin directly] which can get down to 408 bytes. Or, 23 | consider using [Origin Studio] if you want to go there but still have 24 | `println!`. 25 | 26 | [hello-world]: https://github.com/sunfishcode/eyra/tree/main/example-crates/hello-world/ 27 | [min-sized-rust]: https://github.com/johnthagen/min-sized-rust 28 | [workaround to support -Zbuild-std]: https://github.com/sunfishcode/eyra/blob/main/README.md#compatibility-with--zbuild-std 29 | [Remove `core::fmt` with `no_main` and Careful Usage of `libstd`]: https://github.com/johnthagen/min-sized-rust#remove-corefmt-with-no_main-and-careful-usage-of-libstd 30 | [using Origin directly]: https://github.com/sunfishcode/origin/tree/main/example-crates/tiny 31 | [Origin Studio]: https://github.com/sunfishcode/origin-studio 32 | -------------------------------------------------------------------------------- /example-crates/hello-world-small/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/hello-world-small/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | println!("Hello, world!"); 5 | } 6 | -------------------------------------------------------------------------------- /example-crates/hello-world/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/hello-world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | std = { package = "eyra", path = "../.." } 9 | 10 | # This is just an example crate, and not part of the eyra workspace. 11 | [workspace] 12 | -------------------------------------------------------------------------------- /example-crates/hello-world/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra. 2 | 3 | See the [detailed walkthrough] for a list of how this hello world 4 | example crate works. 5 | 6 | [detailed walkthrough]: https://github.com/sunfishcode/eyra#in-detail 7 | -------------------------------------------------------------------------------- /example-crates/hello-world/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/hello-world/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /example-crates/no-std/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /example-crates/no-std/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "no-std" 3 | version = "0.0.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | [dependencies] 8 | eyra = { path = "../..", default-features = false, features = ["global-allocator", "panic-handler-trap", "eh-personality-continue"] } 9 | rustix-dlmalloc = { version = "0.1.0", features = ["global"] } 10 | 11 | # This is just an example crate, and not part of the eyra workspace. 12 | [workspace] 13 | -------------------------------------------------------------------------------- /example-crates/no-std/README.md: -------------------------------------------------------------------------------- 1 | This crate demonstrates the use of Eyra in no-std mode. 2 | 3 | This mode supports fewer features, but supports `no_std`. 4 | -------------------------------------------------------------------------------- /example-crates/no-std/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Pass -nostartfiles to the linker. 3 | println!("cargo:rustc-link-arg=-nostartfiles"); 4 | } 5 | -------------------------------------------------------------------------------- /example-crates/no-std/src/main.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | 4 | extern crate eyra; 5 | 6 | #[no_mangle] 7 | pub extern "C" fn main(_argc: i32, _argv: *const *const u8) -> i32 { 8 | 0 9 | } 10 | -------------------------------------------------------------------------------- /examples/empty.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() {} 4 | -------------------------------------------------------------------------------- /examples/hello.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | println!("Hello, world!"); 5 | } 6 | -------------------------------------------------------------------------------- /examples/rust-by-example-threads.rs: -------------------------------------------------------------------------------- 1 | //! A very simple example using threads. 2 | //! 3 | //! This is [Rust by Example's threads example]. 4 | //! 5 | //! [Rust by Example's threads example]: https://doc.rust-lang.org/rust-by-example/std_misc/threads.html 6 | 7 | extern crate eyra; 8 | 9 | use std::thread; 10 | 11 | const NTHREADS: u32 = 10; 12 | 13 | // This is the `main` thread 14 | fn main() { 15 | // Make a vector to hold the children which are spawned. 16 | let mut children = vec![]; 17 | 18 | for i in 0..NTHREADS { 19 | // Spin up another thread 20 | children.push(thread::spawn(move || { 21 | println!("this is thread number {}", i); 22 | })); 23 | } 24 | 25 | for child in children { 26 | // Wait for the thread to finish. Returns a result. 27 | let _ = child.join(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /examples/test-args.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | let mut args = std::env::args_os(); 5 | assert!(!args.next().is_none(), "we should receive an argv[0]"); 6 | assert!( 7 | args.next().is_none(), 8 | "we aren't expecting any further arguments" 9 | ); 10 | } 11 | -------------------------------------------------------------------------------- /examples/test-ctor.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | use std::ffi::{CStr, OsStr, OsString}; 4 | use std::os::raw::{c_char, c_int}; 5 | use std::os::unix::ffi::OsStrExt; 6 | use std::slice; 7 | use std::sync::atomic::{AtomicBool, Ordering}; 8 | 9 | static EARLY_CTOR_INITIALIZED: AtomicBool = AtomicBool::new(false); 10 | static CTOR_INITIALIZED: AtomicBool = AtomicBool::new(false); 11 | static MANUAL_CTOR_INITIALIZED: AtomicBool = AtomicBool::new(false); 12 | static DTOR_PERFORMED: AtomicBool = AtomicBool::new(false); 13 | 14 | #[ctor::ctor] 15 | fn ctor() { 16 | assert!(EARLY_CTOR_INITIALIZED.load(Ordering::Relaxed)); 17 | CTOR_INITIALIZED.store(true, Ordering::Relaxed); 18 | } 19 | 20 | fn main() { 21 | assert!(EARLY_CTOR_INITIALIZED.load(Ordering::Relaxed)); 22 | assert!(CTOR_INITIALIZED.load(Ordering::Relaxed)); 23 | assert!(MANUAL_CTOR_INITIALIZED.load(Ordering::Relaxed)); 24 | } 25 | 26 | #[ctor::dtor] 27 | fn dtor() { 28 | DTOR_PERFORMED.store(true, Ordering::Relaxed); 29 | } 30 | 31 | #[link_section = ".init_array"] 32 | #[used] 33 | static INIT_ARRAY: unsafe extern "C" fn(c_int, *mut *mut c_char, *mut *mut c_char) = { 34 | unsafe extern "C" fn function(argc: c_int, argv: *mut *mut c_char, envp: *mut *mut c_char) { 35 | assert_eq!(argc as usize, std::env::args_os().len()); 36 | 37 | assert_eq!( 38 | slice::from_raw_parts(argv, argc as usize) 39 | .iter() 40 | .map(|arg| OsStr::from_bytes(CStr::from_ptr(*arg).to_bytes()).to_owned()) 41 | .collect::>(), 42 | std::env::args_os().collect::>() 43 | ); 44 | assert_eq!(*argv.add(argc as usize), core::ptr::null_mut()); 45 | 46 | assert_ne!(envp, core::ptr::null_mut()); 47 | 48 | let mut ptr = envp; 49 | let mut num_env = 0; 50 | loop { 51 | let env = *ptr; 52 | if env.is_null() { 53 | break; 54 | } 55 | 56 | let bytes = CStr::from_ptr(env).to_bytes(); 57 | let mut parts = bytes.splitn(2, |byte| *byte == b'='); 58 | let key = parts.next().unwrap(); 59 | let value = parts.next().unwrap(); 60 | assert_eq!( 61 | std::env::var_os(OsStr::from_bytes(key)).expect("missing environment variable"), 62 | OsStr::from_bytes(value) 63 | ); 64 | 65 | num_env += 1; 66 | ptr = ptr.add(1); 67 | } 68 | assert_eq!(num_env, std::env::vars_os().count()); 69 | 70 | MANUAL_CTOR_INITIALIZED.store(true, Ordering::Relaxed); 71 | } 72 | function 73 | }; 74 | 75 | #[link_section = ".init_array.00000"] 76 | #[used] 77 | static EARLY_INIT_ARRAY: unsafe extern "C" fn(c_int, *mut *mut c_char, *mut *mut c_char) = { 78 | unsafe extern "C" fn function(_argc: c_int, _argv: *mut *mut c_char, _envp: *mut *mut c_char) { 79 | EARLY_CTOR_INITIALIZED.store(true, Ordering::Relaxed); 80 | assert!(!CTOR_INITIALIZED.load(Ordering::Relaxed)); 81 | assert!(!MANUAL_CTOR_INITIALIZED.load(Ordering::Relaxed)); 82 | } 83 | function 84 | }; 85 | 86 | #[link_section = ".fini_array.00000"] 87 | #[used] 88 | static LATE_FINI_ARRAY: unsafe extern "C" fn(c_int, *mut *mut c_char, *mut *mut c_char) = { 89 | unsafe extern "C" fn function(_argc: c_int, _argv: *mut *mut c_char, _envp: *mut *mut c_char) { 90 | assert!(DTOR_PERFORMED.load(Ordering::Relaxed)); 91 | } 92 | function 93 | }; 94 | -------------------------------------------------------------------------------- /examples/test-environ.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | // We expect to be passed some environment variables. 5 | assert!( 6 | !std::env::vars_os().next().is_none(), 7 | "the environment shouldn't be empty" 8 | ); 9 | let _path = std::env::var_os("PATH").expect("PATH should be present in the environment"); 10 | } 11 | -------------------------------------------------------------------------------- /examples/test-simd.rs: -------------------------------------------------------------------------------- 1 | #![feature(portable_simd)] 2 | 3 | extern crate eyra; 4 | 5 | //use core::arch::asm; 6 | 7 | fn main() { 8 | // TODO: Reenable this when the crate compiles on nightly. 9 | /* 10 | use core_simd::simd::*; 11 | let mut a = f32x4::splat(2.0); 12 | unsafe { asm!("# {}", in(reg) &mut a) }; 13 | assert_eq!(a, f32x4::splat(2.0)); 14 | assert_eq!(&a as *const _ as usize & 0xf, 0); 15 | */ 16 | } 17 | -------------------------------------------------------------------------------- /examples/test-tls-dtors.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | use std::cell::RefCell; 4 | use std::thread; 5 | 6 | fn main() { 7 | TLS.with_borrow_mut(|f| { 8 | assert_eq!(f.0, 1); 9 | *f = Thing(2); 10 | }); 11 | let t = thread::spawn(move || { 12 | TLS.with_borrow_mut(|f| { 13 | assert_eq!(f.0, 1); 14 | *f = Thing(3); 15 | }); 16 | }); 17 | t.join().unwrap(); 18 | 19 | TLS.with_borrow_mut(|f| { 20 | assert_eq!(f.0, 2); 21 | }); 22 | eprintln!("main exiting"); 23 | } 24 | 25 | struct Thing(i32); 26 | 27 | impl Drop for Thing { 28 | fn drop(&mut self) { 29 | eprintln!("Thing being dropped!"); 30 | } 31 | } 32 | 33 | thread_local!(static TLS: RefCell = RefCell::new(Thing(1))); 34 | -------------------------------------------------------------------------------- /examples/test-tls.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | use std::cell::Cell; 4 | use std::thread; 5 | 6 | fn main() { 7 | TLS.with(|f| { 8 | assert_eq!(f.get(), 1); 9 | f.set(2); 10 | }); 11 | let t = thread::spawn(move || { 12 | TLS.with(|f| { 13 | assert_eq!(f.get(), 1); 14 | f.set(3); 15 | }); 16 | }); 17 | t.join().unwrap(); 18 | 19 | TLS.with(|f| { 20 | assert_eq!(f.get(), 2); 21 | }); 22 | } 23 | 24 | thread_local!(static TLS: Cell = Cell::new(1)); 25 | -------------------------------------------------------------------------------- /examples/test-workdir.rs: -------------------------------------------------------------------------------- 1 | extern crate eyra; 2 | 3 | fn main() { 4 | let _cwd = std::env::current_dir().expect("current directory should exist and be accessible"); 5 | let home = std::env::var_os("HOME").expect("HOME should be present in the environment"); 6 | std::env::set_current_dir(&home).expect("should be able to change to home directory"); 7 | let cwd = std::env::current_dir().expect("home directory should exist and be accessible"); 8 | assert_eq!( 9 | cwd, home, 10 | "should be in home directory after set_current_dir" 11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2025-04-28" 3 | components = ["rustc", "cargo", "rust-std", "rust-src", "rustfmt"] 4 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_extern_crates)] 2 | #![doc = include_str!("../README.md")] 3 | #![cfg_attr(not(feature = "std"), no_std)] 4 | 5 | // If enabled, re-export `std` so that we can be used as `std` to avoid the 6 | // `extern crate eyra;`. 7 | #[cfg(feature = "be-std")] 8 | pub use std::*; 9 | 10 | /// All the functionality of Eyra is factored out into separate libraries. This 11 | /// `extern crate` line is needed to ensure that libraries that intercept C 12 | /// library symbols get linked in. 13 | extern crate c_gull; 14 | -------------------------------------------------------------------------------- /tests/example_crates.rs: -------------------------------------------------------------------------------- 1 | //! Run the programs in the `example-crates` directory and compare their 2 | //! outputs with expected outputs. 3 | 4 | extern crate eyra; 5 | 6 | fn test_crate( 7 | name: &str, 8 | args: &[&str], 9 | envs: &[(&str, &str)], 10 | stdout: &'static str, 11 | stderr: &'static str, 12 | code: Option, 13 | ) { 14 | use assert_cmd::Command; 15 | 16 | #[cfg(target_arch = "x86_64")] 17 | let arch = "x86_64"; 18 | #[cfg(target_arch = "aarch64")] 19 | let arch = "aarch64"; 20 | #[cfg(target_arch = "riscv64")] 21 | let arch = "riscv64gc"; 22 | #[cfg(target_arch = "x86")] 23 | let arch = "i686"; 24 | #[cfg(target_arch = "arm")] 25 | let arch = "armv5te"; 26 | #[cfg(target_env = "gnueabi")] 27 | let env = "gnueabi"; 28 | #[cfg(all(target_env = "gnu", target_abi = "eabi"))] 29 | let env = "gnueabi"; 30 | #[cfg(all(target_env = "gnu", not(target_abi = "eabi")))] 31 | let env = "gnu"; 32 | 33 | let mut command = Command::new("cargo"); 34 | command.arg("run").arg("--quiet"); 35 | command.arg(&format!("--target={}-unknown-linux-{}", arch, env)); 36 | command.args(args); 37 | 38 | // Special-case "eyra-panic-example" to disable "RUST_BACKTRACE", so that 39 | // the stderr message is reproducible. 40 | if name == "eyra-panic-example" { 41 | command.env_remove("RUST_BACKTRACE"); 42 | } 43 | 44 | command.envs(envs.iter().cloned()); 45 | command.current_dir(format!("example-crates/{}", name)); 46 | let assert = command.assert(); 47 | let assert = assert.stdout(stdout).stderr(stderr); 48 | if let Some(code) = code { 49 | assert.code(code); 50 | } else { 51 | assert.success(); 52 | } 53 | } 54 | 55 | #[test] 56 | fn example_crate_hello_world() { 57 | test_crate("hello-world", &[], &[], "Hello, world!\n", "", None); 58 | } 59 | 60 | #[test] 61 | fn example_crate_hello_world_lto() { 62 | test_crate( 63 | "hello-world-lto", 64 | &["--release"], 65 | &[], 66 | "Hello, world!\n", 67 | "", 68 | None, 69 | ); 70 | } 71 | 72 | #[test] 73 | fn example_crate_hello_world_small() { 74 | test_crate( 75 | "hello-world-small", 76 | &[ 77 | "--release", 78 | "-Zbuild-std=std,panic_abort", 79 | "-Zbuild-std-features=panic_immediate_abort,optimize_for_size", 80 | ], 81 | &[( 82 | "RUSTFLAGS", 83 | "-Zlocation-detail=none -Zfmt-debug=none -Crelocation-model=static -Ctarget-feature=+crt-static", 84 | )], 85 | "Hello, world!\n", 86 | "", 87 | None, 88 | ); 89 | } 90 | 91 | #[test] 92 | fn example_crate_extern_crate_hello_world() { 93 | test_crate( 94 | "extern-crate-hello-world", 95 | &[], 96 | &[], 97 | "Hello, world!\n", 98 | "", 99 | None, 100 | ); 101 | } 102 | 103 | /// Like `example_crate_extern_crate_hello_world` but uses `-Zbuild-std`. This 104 | /// doesn't work with `example_crate_hello_world` because of the `std` trick, 105 | /// but it does work with the `extern crate eyra;` trick. 106 | #[test] 107 | fn example_crate_extern_crate_hello_world_z_build_std() { 108 | test_crate( 109 | "extern-crate-hello-world", 110 | &["-Zbuild-std"], 111 | &[], 112 | "Hello, world!\n", 113 | "", 114 | None, 115 | ); 116 | } 117 | 118 | #[test] 119 | fn example_crate_eyra_libc_example() { 120 | test_crate( 121 | "eyra-libc-example", 122 | &[], 123 | &[], 124 | "Hello world using Rust `println!`!\nHello world using libc `printf`!\n", 125 | "", 126 | None, 127 | ); 128 | } 129 | 130 | #[test] 131 | fn example_crate_eyra_panic_example() { 132 | test_crate( 133 | "eyra-panic-example", 134 | &[], 135 | &[], 136 | "", 137 | "\nthread 'main' panicked at src/main.rs:2:5:\nUh oh!\nnote: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n", 138 | Some(101) 139 | ); 140 | } 141 | 142 | #[test] 143 | fn example_crate_eyra_optional_example() { 144 | // Test the crate in non-Eyra mode. 145 | test_crate( 146 | "eyra-optional-example", 147 | &[], 148 | &[], 149 | "Hello, world!\n", 150 | "", 151 | None, 152 | ); 153 | 154 | // Test the crate in Eyra mode. 155 | test_crate( 156 | "eyra-optional-example", 157 | &["--features=eyra"], 158 | &[], 159 | "Hello, world!\n", 160 | "", 161 | None, 162 | ); 163 | } 164 | 165 | #[test] 166 | fn example_crate_extern_crate_eyra_optional_example() { 167 | // Test the crate in non-Eyra mode. 168 | test_crate( 169 | "extern-crate-eyra-optional-example", 170 | &[], 171 | &[], 172 | "Hello, world!\n", 173 | "", 174 | None, 175 | ); 176 | 177 | // Test the crate in Eyra mode. 178 | test_crate( 179 | "eyra-optional-example", 180 | &["--features=eyra"], 181 | &[], 182 | "Hello, world!\n", 183 | "", 184 | None, 185 | ); 186 | } 187 | 188 | #[test] 189 | fn example_crate_no_std() { 190 | test_crate("no-std", &[], &[], "", "", None); 191 | } 192 | -------------------------------------------------------------------------------- /tests/examples.rs: -------------------------------------------------------------------------------- 1 | //! Run the programs in the `examples` directory and compare their outputs with 2 | //! expected outputs. 3 | 4 | extern crate eyra; 5 | 6 | use similar_asserts::assert_eq; 7 | 8 | macro_rules! assert_eq_str { 9 | ($a:expr, $b:expr) => {{ 10 | assert_eq!(String::from_utf8_lossy($a).lines().collect::>(), String::from_utf8_lossy($b).lines().collect::>()); 11 | assert_eq!($a, $b); 12 | }}; 13 | 14 | ($a:expr, $b:expr, $($arg:tt)+) => {{ 15 | assert_eq!(String::from_utf8_lossy($a).lines().collect::>(), String::from_utf8_lossy($b).lines().collect::>(), $($arg)+); 16 | assert_eq!($a, $b, $($arg)+); 17 | }}; 18 | } 19 | 20 | fn test_example(name: &str, features: &str, stdout: &str, stderr: &str) { 21 | use std::process::Command; 22 | 23 | #[cfg(target_arch = "x86_64")] 24 | let arch = "x86_64"; 25 | #[cfg(target_arch = "aarch64")] 26 | let arch = "aarch64"; 27 | #[cfg(target_arch = "riscv64")] 28 | let arch = "riscv64gc"; 29 | #[cfg(target_arch = "x86")] 30 | let arch = "i686"; 31 | #[cfg(target_arch = "arm")] 32 | let arch = "armv5te"; 33 | #[cfg(target_env = "gnueabi")] 34 | let env = "gnueabi"; 35 | #[cfg(all(target_env = "gnu", target_abi = "eabi"))] 36 | let env = "gnueabi"; 37 | #[cfg(all(target_env = "gnu", not(target_abi = "eabi")))] 38 | let env = "gnu"; 39 | 40 | let mut command = Command::new("cargo"); 41 | if which::which("rustup").is_ok() { 42 | command.arg("+nightly-2025-04-28"); 43 | } 44 | command.arg("run").arg("--quiet"); 45 | if !features.is_empty() { 46 | command 47 | .arg("--no-default-features") 48 | .arg("--features") 49 | .arg(features); 50 | } 51 | command 52 | .arg(&format!("--target={}-unknown-linux-{}", arch, env)) 53 | .arg("--example") 54 | .arg(name); 55 | let output = command.output().unwrap(); 56 | 57 | assert_eq_str!( 58 | stderr.as_bytes(), 59 | &output.stderr, 60 | "example {} had unexpected stderr, with {:?}", 61 | name, 62 | output 63 | ); 64 | 65 | assert_eq_str!( 66 | stdout.as_bytes(), 67 | &output.stdout, 68 | "example {} had unexpected stdout, with {:?}", 69 | name, 70 | output 71 | ); 72 | assert!( 73 | output.status.success(), 74 | "example {} failed with {:?}", 75 | name, 76 | output 77 | ); 78 | 79 | // Check nm output for any unexpected undefined symbols. 80 | let output = Command::new("nm") 81 | .arg("-u") 82 | .arg(&format!( 83 | "target/{}-unknown-linux-{}/debug/examples/{}", 84 | arch, env, name 85 | )) 86 | .output() 87 | .unwrap(); 88 | let stdout = String::from_utf8_lossy(&output.stdout); 89 | // Allow `__rustc_debug_gdb_scripts_section` because it shows up in some 90 | // builds and it's a weak external that Rust uses, rather than a reference 91 | // to a libc symbol. 92 | assert!( 93 | stdout == " v __rustc_debug_gdb_scripts_section__\n" || stdout == "", 94 | "example {} had unexpected undefined symbols:\n{}", 95 | name, 96 | stdout 97 | ); 98 | 99 | let output = Command::new("readelf") 100 | .arg("-d") 101 | .arg(&format!( 102 | "target/{}-unknown-linux-{}/debug/examples/{}", 103 | arch, env, name 104 | )) 105 | .output() 106 | .unwrap(); 107 | for line in String::from_utf8_lossy(&output.stdout).lines() { 108 | assert!( 109 | !line.contains("NEEDED"), 110 | "example {} had unexpected dynamic library dependencies: {}", 111 | name, 112 | line 113 | ); 114 | } 115 | } 116 | 117 | #[test] 118 | fn test_examples() { 119 | test_example("empty", "", "", ""); 120 | test_example("hello", "", "Hello, world!\n", ""); 121 | test_example("test-args", "", "", ""); 122 | test_example("test-ctor", "", "", ""); 123 | test_example("test-environ", "", "", ""); 124 | test_example("test-workdir", "", "", ""); 125 | test_example("test-simd", "", "", ""); 126 | test_example("test-tls", "", "", ""); 127 | } 128 | -------------------------------------------------------------------------------- /tests/stdtests.rs: -------------------------------------------------------------------------------- 1 | #![feature(cfg_target_has_atomic)] 2 | #![feature(core_io_borrowed_buf)] 3 | #![feature(duration_constants)] 4 | #![feature(io_error_uncategorized)] 5 | #![feature(ip)] 6 | #![feature(maybe_uninit_uninit_array_transpose)] 7 | #![feature(once_cell_try)] 8 | #![feature(read_buf)] 9 | #![feature(tcp_linger)] 10 | #![feature(try_blocks)] 11 | 12 | extern crate eyra; 13 | 14 | mod stdtests { 15 | mod common; 16 | mod net; 17 | mod sys_common; 18 | 19 | mod env; 20 | mod fs; 21 | mod integration_create_dir_all_bare; 22 | mod integration_env; 23 | mod integration_thread; 24 | mod kernel_copy; 25 | mod lazy; 26 | mod net_addr; 27 | mod net_ip; 28 | mod net_tcp; 29 | mod net_udp; 30 | mod panic; 31 | mod process; 32 | mod process_common; 33 | mod process_unix; 34 | mod sync_barrier; 35 | mod sync_condvar; 36 | mod sync_lazy_lock; 37 | mod sync_mpsc; 38 | mod sync_mpsc_sync; 39 | mod sync_mutex; 40 | mod sync_once; 41 | mod sync_once_lock; 42 | mod sync_rwlock; 43 | mod thread; 44 | mod thread_local; 45 | mod time; 46 | } 47 | -------------------------------------------------------------------------------- /tests/stdtests/common/mod.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/tests/common/mod.rs at revision 3 | //! 9b18b4440a8d8b052ef454dba9fdb95be99485e7. 4 | 5 | #![allow(unused)] 6 | 7 | use rand::RngCore; 8 | use std::env; 9 | use std::fs; 10 | use std::path::{Path, PathBuf}; 11 | use std::thread; 12 | 13 | /// Copied from `std::test_helpers::test_rng`, since these tests rely on the 14 | /// seed not being the same for every RNG invocation too. 15 | #[track_caller] 16 | pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng { 17 | use core::hash::{BuildHasher, Hash, Hasher}; 18 | let mut hasher = std::collections::hash_map::RandomState::new().build_hasher(); 19 | core::panic::Location::caller().hash(&mut hasher); 20 | let hc64 = hasher.finish(); 21 | let seed_vec = hc64 22 | .to_le_bytes() 23 | .into_iter() 24 | .chain(0u8..8) 25 | .collect::>(); 26 | let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap(); 27 | rand::SeedableRng::from_seed(seed) 28 | } 29 | 30 | // Copied from std::sys_common::io 31 | pub struct TempDir(PathBuf); 32 | 33 | impl TempDir { 34 | pub fn join(&self, path: &str) -> PathBuf { 35 | let TempDir(ref p) = *self; 36 | p.join(path) 37 | } 38 | 39 | pub fn path(&self) -> &Path { 40 | let TempDir(ref p) = *self; 41 | p 42 | } 43 | } 44 | 45 | impl Drop for TempDir { 46 | fn drop(&mut self) { 47 | // Gee, seeing how we're testing the fs module I sure hope that we 48 | // at least implement this correctly! 49 | let TempDir(ref p) = *self; 50 | let result = fs::remove_dir_all(p); 51 | // Avoid panicking while panicking as this causes the process to 52 | // immediately abort, without displaying test results. 53 | if !thread::panicking() { 54 | result.unwrap(); 55 | } 56 | } 57 | } 58 | 59 | #[track_caller] // for `test_rng` 60 | pub fn tmpdir() -> TempDir { 61 | let p = env::temp_dir(); 62 | let mut r = test_rng(); 63 | let ret = p.join(&format!("rust-{}", r.next_u32())); 64 | fs::create_dir(&ret).unwrap(); 65 | TempDir(ret) 66 | } 67 | -------------------------------------------------------------------------------- /tests/stdtests/env.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/env/tests.rs at revision 3 | //! 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | use std::env::*; 6 | 7 | use std::path::Path; 8 | 9 | #[test] 10 | #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)] 11 | fn test_self_exe_path() { 12 | let path = current_exe(); 13 | assert!(path.is_ok()); 14 | let path = path.unwrap(); 15 | 16 | // Hard to test this function 17 | assert!(path.is_absolute()); 18 | } 19 | 20 | #[test] 21 | fn test() { 22 | assert!((!Path::new("test-path").is_absolute())); 23 | 24 | #[cfg(not(target_env = "sgx"))] 25 | current_dir().unwrap(); 26 | } 27 | 28 | #[test] 29 | #[cfg(windows)] 30 | fn split_paths_windows() { 31 | use std::path::PathBuf; 32 | 33 | fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { 34 | split_paths(unparsed).collect::>() 35 | == parsed.iter().map(|s| PathBuf::from(*s)).collect::>() 36 | } 37 | 38 | assert!(check_parse("", &mut [""])); 39 | assert!(check_parse(r#""""#, &mut [""])); 40 | assert!(check_parse(";;", &mut ["", "", ""])); 41 | assert!(check_parse(r"c:\", &mut [r"c:\"])); 42 | assert!(check_parse(r"c:\;", &mut [r"c:\", ""])); 43 | assert!(check_parse( 44 | r"c:\;c:\Program Files\", 45 | &mut [r"c:\", r"c:\Program Files\"] 46 | )); 47 | assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"])); 48 | assert!(check_parse( 49 | r#"c:\;c:\"foo;bar"\;c:\baz"#, 50 | &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"] 51 | )); 52 | } 53 | 54 | #[test] 55 | #[cfg(unix)] 56 | fn split_paths_unix() { 57 | use std::path::PathBuf; 58 | 59 | fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { 60 | split_paths(unparsed).collect::>() 61 | == parsed.iter().map(|s| PathBuf::from(*s)).collect::>() 62 | } 63 | 64 | assert!(check_parse("", &mut [""])); 65 | assert!(check_parse("::", &mut ["", "", ""])); 66 | assert!(check_parse("/", &mut ["/"])); 67 | assert!(check_parse("/:", &mut ["/", ""])); 68 | assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"])); 69 | } 70 | 71 | #[test] 72 | #[cfg(unix)] 73 | fn join_paths_unix() { 74 | use std::ffi::OsStr; 75 | 76 | fn test_eq(input: &[&str], output: &str) -> bool { 77 | &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) 78 | } 79 | 80 | assert!(test_eq(&[], "")); 81 | assert!(test_eq( 82 | &["/bin", "/usr/bin", "/usr/local/bin"], 83 | "/bin:/usr/bin:/usr/local/bin" 84 | )); 85 | assert!(test_eq( 86 | &["", "/bin", "", "", "/usr/bin", ""], 87 | ":/bin:::/usr/bin:" 88 | )); 89 | assert!(join_paths(["/te:st"].iter().cloned()).is_err()); 90 | } 91 | 92 | #[test] 93 | #[cfg(windows)] 94 | fn join_paths_windows() { 95 | use std::ffi::OsStr; 96 | 97 | fn test_eq(input: &[&str], output: &str) -> bool { 98 | &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) 99 | } 100 | 101 | assert!(test_eq(&[], "")); 102 | assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\")); 103 | assert!(test_eq( 104 | &["", r"c:\windows", "", "", r"c:\", ""], 105 | r";c:\windows;;;c:\;" 106 | )); 107 | assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#)); 108 | assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err()); 109 | } 110 | 111 | #[test] 112 | fn args_debug() { 113 | assert_eq!( 114 | format!("Args {{ inner: {:?} }}", args().collect::>()), 115 | format!("{:?}", args()) 116 | ); 117 | assert_eq!( 118 | format!("ArgsOs {{ inner: {:?} }}", args_os().collect::>()), 119 | format!("{:?}", args_os()) 120 | ); 121 | } 122 | -------------------------------------------------------------------------------- /tests/stdtests/integration_create_dir_all_bare.rs: -------------------------------------------------------------------------------- 1 | #![cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))] 2 | 3 | //! The following is derived from Rust's 4 | //! library/std/tests/create_dir_all_bare.rs at revision 5 | //! 9b18b4440a8d8b052ef454dba9fdb95be99485e7. 6 | //! 7 | //! Note that this test changes the current directory so 8 | //! should not be in the same process as other tests. 9 | 10 | use std::env; 11 | use std::fs; 12 | use std::path::{Path, PathBuf}; 13 | 14 | use super::common; 15 | 16 | // On some platforms, setting the current directory will prevent deleting it. 17 | // So this helper ensures the current directory is reset. 18 | struct CurrentDir(PathBuf); 19 | impl CurrentDir { 20 | fn new() -> Self { 21 | Self(env::current_dir().unwrap()) 22 | } 23 | fn set(&self, path: &Path) { 24 | env::set_current_dir(path).unwrap(); 25 | } 26 | fn with(path: &Path, f: impl FnOnce()) { 27 | let current_dir = Self::new(); 28 | current_dir.set(path); 29 | f(); 30 | } 31 | } 32 | impl Drop for CurrentDir { 33 | fn drop(&mut self) { 34 | env::set_current_dir(&self.0).unwrap(); 35 | } 36 | } 37 | 38 | #[test] 39 | fn create_dir_all_bare() { 40 | let tmpdir = common::tmpdir(); 41 | CurrentDir::with(tmpdir.path(), || { 42 | fs::create_dir_all("create-dir-all-bare").unwrap(); 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /tests/stdtests/integration_env.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/tests/env.rs at revision 3 | //! 9b18b4440a8d8b052ef454dba9fdb95be99485e7. 4 | 5 | use std::env::*; 6 | use std::ffi::{OsStr, OsString}; 7 | 8 | use rand::distr::{Alphanumeric, SampleString}; 9 | 10 | use super::common::test_rng; 11 | 12 | #[track_caller] 13 | fn make_rand_name() -> OsString { 14 | let n = format!("TEST{}", Alphanumeric.sample_string(&mut test_rng(), 10)); 15 | let n = OsString::from(n); 16 | assert!(var_os(&n).is_none()); 17 | n 18 | } 19 | 20 | fn eq(a: Option, b: Option<&str>) { 21 | assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s)); 22 | } 23 | 24 | #[test] 25 | fn test_set_var() { 26 | let n = make_rand_name(); 27 | set_var(&n, "VALUE"); 28 | eq(var_os(&n), Some("VALUE")); 29 | } 30 | 31 | #[test] 32 | fn test_remove_var() { 33 | let n = make_rand_name(); 34 | set_var(&n, "VALUE"); 35 | remove_var(&n); 36 | eq(var_os(&n), None); 37 | } 38 | 39 | #[test] 40 | fn test_set_var_overwrite() { 41 | let n = make_rand_name(); 42 | set_var(&n, "1"); 43 | set_var(&n, "2"); 44 | eq(var_os(&n), Some("2")); 45 | set_var(&n, ""); 46 | eq(var_os(&n), Some("")); 47 | } 48 | 49 | #[test] 50 | #[cfg_attr(target_os = "emscripten", ignore)] 51 | fn test_var_big() { 52 | let mut s = "".to_string(); 53 | let mut i = 0; 54 | while i < 100 { 55 | s.push_str("aaaaaaaaaa"); 56 | i += 1; 57 | } 58 | let n = make_rand_name(); 59 | set_var(&n, &s); 60 | eq(var_os(&n), Some(&s)); 61 | } 62 | 63 | #[test] 64 | #[cfg_attr(target_os = "emscripten", ignore)] 65 | fn test_env_set_get_huge() { 66 | let n = make_rand_name(); 67 | let s = "x".repeat(10000); 68 | set_var(&n, &s); 69 | eq(var_os(&n), Some(&s)); 70 | remove_var(&n); 71 | eq(var_os(&n), None); 72 | } 73 | 74 | #[test] 75 | fn test_env_set_var() { 76 | let n = make_rand_name(); 77 | 78 | let mut e = vars_os(); 79 | set_var(&n, "VALUE"); 80 | assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); 81 | 82 | assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); 83 | } 84 | 85 | #[test] 86 | #[cfg_attr(not(any(unix, windows)), ignore, allow(unused))] 87 | #[allow(deprecated)] 88 | fn env_home_dir() { 89 | use std::path::PathBuf; 90 | 91 | fn var_to_os_string(var: Result) -> Option { 92 | match var { 93 | Ok(var) => Some(OsString::from(var)), 94 | Err(VarError::NotUnicode(var)) => Some(var), 95 | _ => None, 96 | } 97 | } 98 | 99 | cfg_if::cfg_if! { 100 | if #[cfg(unix)] { 101 | let oldhome = var_to_os_string(var("HOME")); 102 | 103 | set_var("HOME", "/home/MountainView"); 104 | assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); 105 | 106 | remove_var("HOME"); 107 | if cfg!(target_os = "android") { 108 | assert!(home_dir().is_none()); 109 | } else { 110 | // When HOME is not set, some platforms return `None`, 111 | // but others return `Some` with a default. 112 | // Just check that it is not "/home/MountainView". 113 | assert_ne!(home_dir(), Some(PathBuf::from("/home/MountainView"))); 114 | } 115 | 116 | if let Some(oldhome) = oldhome { set_var("HOME", oldhome); } 117 | } else if #[cfg(windows)] { 118 | let oldhome = var_to_os_string(var("HOME")); 119 | let olduserprofile = var_to_os_string(var("USERPROFILE")); 120 | 121 | remove_var("HOME"); 122 | remove_var("USERPROFILE"); 123 | 124 | assert!(home_dir().is_some()); 125 | 126 | set_var("HOME", "/home/MountainView"); 127 | assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); 128 | 129 | remove_var("HOME"); 130 | 131 | set_var("USERPROFILE", "/home/MountainView"); 132 | assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); 133 | 134 | set_var("HOME", "/home/MountainView"); 135 | set_var("USERPROFILE", "/home/PaloAlto"); 136 | assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); 137 | 138 | remove_var("HOME"); 139 | remove_var("USERPROFILE"); 140 | 141 | if let Some(oldhome) = oldhome { set_var("HOME", oldhome); } 142 | if let Some(olduserprofile) = olduserprofile { set_var("USERPROFILE", olduserprofile); } 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /tests/stdtests/integration_thread.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/tests/thread.rs at revision 3 | //! 9b18b4440a8d8b052ef454dba9fdb95be99485e7. 4 | 5 | use std::sync::{Arc, Mutex}; 6 | use std::thread; 7 | use std::time::Duration; 8 | 9 | #[test] 10 | #[cfg_attr(target_os = "emscripten", ignore)] 11 | fn sleep() { 12 | let finished = Arc::new(Mutex::new(false)); 13 | let t_finished = finished.clone(); 14 | thread::spawn(move || { 15 | thread::sleep(Duration::new(u64::MAX, 0)); 16 | *t_finished.lock().unwrap() = true; 17 | }); 18 | thread::sleep(Duration::from_millis(100)); 19 | assert_eq!(*finished.lock().unwrap(), false); 20 | } 21 | -------------------------------------------------------------------------------- /tests/stdtests/kernel_copy.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sys/unix/kernel_copy/tests.rs at revision 3 | //! 5c0d76dbe1669c96f1959d7b0b1d4de7e9a47c43. 4 | 5 | use super::sys_common::io::test::tmpdir; 6 | use std::fs::OpenOptions; 7 | #[cfg(feature = "bench")] 8 | use std::io; 9 | use std::io::Result; 10 | use std::io::SeekFrom; 11 | use std::io::{BufRead, Read, Seek, Write}; 12 | #[cfg(feature = "bench")] 13 | use std::os::unix::io::AsRawFd; 14 | 15 | #[test] 16 | fn copy_specialization() -> Result<()> { 17 | use std::io::{BufReader, BufWriter}; 18 | 19 | let tmp_path = tmpdir(); 20 | let source_path = tmp_path.join("copy-spec.source"); 21 | let sink_path = tmp_path.join("copy-spec.sink"); 22 | 23 | let result: Result<()> = try { 24 | let mut source = std::fs::OpenOptions::new() 25 | .read(true) 26 | .write(true) 27 | .create(true) 28 | .truncate(true) 29 | .open(&source_path)?; 30 | source.write_all(b"abcdefghiklmnopqr")?; 31 | source.seek(SeekFrom::Start(8))?; 32 | let mut source = BufReader::with_capacity(8, source.take(5)); 33 | source.fill_buf()?; 34 | assert_eq!(source.buffer(), b"iklmn"); 35 | source.get_mut().set_limit(6); 36 | source.get_mut().get_mut().seek(SeekFrom::Start(1))?; // "bcdefg" 37 | let mut source = source.take(10); // "iklmnbcdef" 38 | 39 | let mut sink = std::fs::OpenOptions::new() 40 | .read(true) 41 | .write(true) 42 | .create(true) 43 | .truncate(true) 44 | .open(&sink_path)?; 45 | sink.write_all(b"000000")?; 46 | let mut sink = BufWriter::with_capacity(5, sink); 47 | sink.write_all(b"wxyz")?; 48 | assert_eq!(sink.buffer(), b"wxyz"); 49 | 50 | let copied = std::io::copy(&mut source, &mut sink)?; 51 | assert_eq!(copied, 10, "copy obeyed limit imposed by Take"); 52 | assert_eq!(sink.buffer().len(), 0, "sink buffer was flushed"); 53 | assert_eq!(source.limit(), 0, "outer Take was exhausted"); 54 | assert_eq!( 55 | source.get_ref().buffer().len(), 56 | 0, 57 | "source buffer should be drained" 58 | ); 59 | assert_eq!( 60 | source.get_ref().get_ref().limit(), 61 | 1, 62 | "inner Take allowed reading beyond end of file, some bytes should be left" 63 | ); 64 | 65 | let mut sink = sink.into_inner()?; 66 | sink.seek(SeekFrom::Start(0))?; 67 | let mut copied = Vec::new(); 68 | sink.read_to_end(&mut copied)?; 69 | assert_eq!(&copied, b"000000wxyziklmnbcdef"); 70 | }; 71 | 72 | let rm1 = std::fs::remove_file(source_path); 73 | let rm2 = std::fs::remove_file(sink_path); 74 | 75 | result.and(rm1).and(rm2) 76 | } 77 | 78 | #[test] 79 | fn copies_append_mode_sink() -> Result<()> { 80 | let tmp_path = tmpdir(); 81 | let source_path = tmp_path.join("copies_append_mode.source"); 82 | let sink_path = tmp_path.join("copies_append_mode.sink"); 83 | let mut source = OpenOptions::new() 84 | .create(true) 85 | .truncate(true) 86 | .write(true) 87 | .read(true) 88 | .open(&source_path)?; 89 | write!(source, "not empty")?; 90 | source.seek(SeekFrom::Start(0))?; 91 | let mut sink = OpenOptions::new() 92 | .create(true) 93 | .append(true) 94 | .open(&sink_path)?; 95 | 96 | let copied = std::io::copy(&mut source, &mut sink)?; 97 | 98 | assert_eq!(copied, 9); 99 | 100 | Ok(()) 101 | } 102 | 103 | #[cfg(feature = "bench")] 104 | #[bench] 105 | fn bench_file_to_file_copy(b: &mut test::Bencher) { 106 | const BYTES: usize = 128 * 1024; 107 | let temp_path = tmpdir(); 108 | let src_path = temp_path.join("file-copy-bench-src"); 109 | let mut src = std::fs::OpenOptions::new() 110 | .create(true) 111 | .truncate(true) 112 | .read(true) 113 | .write(true) 114 | .open(src_path) 115 | .unwrap(); 116 | src.write(&vec![0u8; BYTES]).unwrap(); 117 | 118 | let sink_path = temp_path.join("file-copy-bench-sink"); 119 | let mut sink = std::fs::OpenOptions::new() 120 | .create(true) 121 | .truncate(true) 122 | .write(true) 123 | .open(sink_path) 124 | .unwrap(); 125 | 126 | b.bytes = BYTES as u64; 127 | b.iter(|| { 128 | src.seek(SeekFrom::Start(0)).unwrap(); 129 | sink.seek(SeekFrom::Start(0)).unwrap(); 130 | assert_eq!(BYTES as u64, io::copy(&mut src, &mut sink).unwrap()); 131 | }); 132 | } 133 | 134 | #[cfg(feature = "bench")] 135 | #[bench] 136 | fn bench_file_to_socket_copy(b: &mut test::Bencher) { 137 | const BYTES: usize = 128 * 1024; 138 | let temp_path = tmpdir(); 139 | let src_path = temp_path.join("pipe-copy-bench-src"); 140 | let mut src = OpenOptions::new() 141 | .create(true) 142 | .truncate(true) 143 | .read(true) 144 | .write(true) 145 | .open(src_path) 146 | .unwrap(); 147 | src.write(&vec![0u8; BYTES]).unwrap(); 148 | 149 | let sink_drainer = std::net::TcpListener::bind("localhost:0").unwrap(); 150 | let mut sink = std::net::TcpStream::connect(sink_drainer.local_addr().unwrap()).unwrap(); 151 | let mut sink_drainer = sink_drainer.accept().unwrap().0; 152 | 153 | std::thread::spawn(move || { 154 | let mut sink_buf = vec![0u8; 1024 * 1024]; 155 | loop { 156 | sink_drainer.read(&mut sink_buf[..]).unwrap(); 157 | } 158 | }); 159 | 160 | b.bytes = BYTES as u64; 161 | b.iter(|| { 162 | src.seek(SeekFrom::Start(0)).unwrap(); 163 | assert_eq!(BYTES as u64, io::copy(&mut src, &mut sink).unwrap()); 164 | }); 165 | } 166 | 167 | #[cfg(feature = "bench")] 168 | #[bench] 169 | fn bench_file_to_uds_copy(b: &mut test::Bencher) { 170 | const BYTES: usize = 128 * 1024; 171 | let temp_path = tmpdir(); 172 | let src_path = temp_path.join("uds-copy-bench-src"); 173 | let mut src = OpenOptions::new() 174 | .create(true) 175 | .truncate(true) 176 | .read(true) 177 | .write(true) 178 | .open(src_path) 179 | .unwrap(); 180 | src.write(&vec![0u8; BYTES]).unwrap(); 181 | 182 | let (mut sink, mut sink_drainer) = std::os::unix::net::UnixStream::pair().unwrap(); 183 | 184 | std::thread::spawn(move || { 185 | let mut sink_buf = vec![0u8; 1024 * 1024]; 186 | loop { 187 | sink_drainer.read(&mut sink_buf[..]).unwrap(); 188 | } 189 | }); 190 | 191 | b.bytes = BYTES as u64; 192 | b.iter(|| { 193 | src.seek(SeekFrom::Start(0)).unwrap(); 194 | assert_eq!(BYTES as u64, io::copy(&mut src, &mut sink).unwrap()); 195 | }); 196 | } 197 | 198 | #[cfg(any(target_os = "linux", target_os = "android"))] 199 | #[cfg(feature = "bench")] 200 | #[bench] 201 | fn bench_socket_pipe_socket_copy(b: &mut test::Bencher) { 202 | use super::CopyResult; 203 | use std::io::ErrorKind; 204 | use std::process::{ChildStdin, ChildStdout}; 205 | use std::sys_common::FromInner; 206 | 207 | let (read_end, write_end) = std::sys::pipe::anon_pipe().unwrap(); 208 | 209 | let mut read_end = ChildStdout::from_inner(read_end); 210 | let write_end = ChildStdin::from_inner(write_end); 211 | 212 | let acceptor = std::net::TcpListener::bind("localhost:0").unwrap(); 213 | let mut remote_end = std::net::TcpStream::connect(acceptor.local_addr().unwrap()).unwrap(); 214 | 215 | let local_end = std::sync::Arc::new(acceptor.accept().unwrap().0); 216 | 217 | // the data flow in this benchmark: 218 | // 219 | // socket(tx) local_source 220 | // remote_end (write) +--------> (splice to) 221 | // write_end 222 | // + 223 | // | 224 | // | pipe 225 | // v 226 | // read_end 227 | // remote_end (read) <---------+ (splice to) * 228 | // socket(rx) local_end 229 | // 230 | // * benchmark loop using io::copy 231 | 232 | std::thread::spawn(move || { 233 | let mut sink_buf = vec![0u8; 1024 * 1024]; 234 | remote_end.set_nonblocking(true).unwrap(); 235 | loop { 236 | match remote_end.write(&mut sink_buf[..]) { 237 | Err(err) if err.kind() == ErrorKind::WouldBlock => {} 238 | Ok(_) => {} 239 | err => { 240 | err.expect("write failed"); 241 | } 242 | }; 243 | match remote_end.read(&mut sink_buf[..]) { 244 | Err(err) if err.kind() == ErrorKind::WouldBlock => {} 245 | Ok(_) => {} 246 | err => { 247 | err.expect("read failed"); 248 | } 249 | }; 250 | } 251 | }); 252 | 253 | // check that splice works, otherwise the benchmark would hang 254 | let probe = super::sendfile_splice( 255 | super::SpliceMode::Splice, 256 | local_end.as_raw_fd(), 257 | write_end.as_raw_fd(), 258 | 1, 259 | ); 260 | 261 | match probe { 262 | CopyResult::Ended(1) => { 263 | // splice works 264 | } 265 | _ => { 266 | eprintln!("splice failed, skipping benchmark"); 267 | return; 268 | } 269 | } 270 | 271 | let local_source = local_end.clone(); 272 | std::thread::spawn(move || loop { 273 | super::sendfile_splice( 274 | super::SpliceMode::Splice, 275 | local_source.as_raw_fd(), 276 | write_end.as_raw_fd(), 277 | u64::MAX, 278 | ); 279 | }); 280 | 281 | const BYTES: usize = 128 * 1024; 282 | b.bytes = BYTES as u64; 283 | b.iter(|| { 284 | assert_eq!( 285 | BYTES as u64, 286 | io::copy(&mut (&mut read_end).take(BYTES as u64), &mut &*local_end).unwrap() 287 | ); 288 | }); 289 | } 290 | -------------------------------------------------------------------------------- /tests/stdtests/lazy.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/lazy/tests.rs at revision 3 | //! 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | use std::{ 6 | cell::LazyCell, 7 | panic, 8 | sync::{ 9 | atomic::{AtomicUsize, Ordering::SeqCst}, 10 | mpsc::channel, 11 | Mutex, 12 | }, 13 | sync::{LazyLock, OnceLock}, 14 | thread, 15 | }; 16 | 17 | #[test] 18 | fn lazy_default() { 19 | static CALLED: AtomicUsize = AtomicUsize::new(0); 20 | 21 | struct Foo(u8); 22 | impl Default for Foo { 23 | fn default() -> Self { 24 | CALLED.fetch_add(1, SeqCst); 25 | Foo(42) 26 | } 27 | } 28 | 29 | let lazy: LazyCell> = <_>::default(); 30 | 31 | assert_eq!(CALLED.load(SeqCst), 0); 32 | 33 | assert_eq!(lazy.lock().unwrap().0, 42); 34 | assert_eq!(CALLED.load(SeqCst), 1); 35 | 36 | lazy.lock().unwrap().0 = 21; 37 | 38 | assert_eq!(lazy.lock().unwrap().0, 21); 39 | assert_eq!(CALLED.load(SeqCst), 1); 40 | } 41 | 42 | #[test] 43 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 44 | fn lazy_poisoning() { 45 | let x: LazyCell = LazyCell::new(|| panic!("kaboom")); 46 | for _ in 0..2 { 47 | let res = panic::catch_unwind(panic::AssertUnwindSafe(|| x.len())); 48 | assert!(res.is_err()); 49 | } 50 | } 51 | 52 | fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { 53 | thread::spawn(f).join().unwrap() 54 | } 55 | 56 | #[test] 57 | #[cfg_attr(target_os = "emscripten", ignore)] 58 | fn sync_once_cell() { 59 | static ONCE_CELL: OnceLock = OnceLock::new(); 60 | 61 | assert!(ONCE_CELL.get().is_none()); 62 | 63 | spawn_and_wait(|| { 64 | ONCE_CELL.get_or_init(|| 92); 65 | assert_eq!(ONCE_CELL.get(), Some(&92)); 66 | }); 67 | 68 | ONCE_CELL.get_or_init(|| panic!("Kabom!")); 69 | assert_eq!(ONCE_CELL.get(), Some(&92)); 70 | } 71 | 72 | #[test] 73 | fn sync_once_cell_get_mut() { 74 | let mut c = OnceLock::new(); 75 | assert!(c.get_mut().is_none()); 76 | c.set(90).unwrap(); 77 | *c.get_mut().unwrap() += 2; 78 | assert_eq!(c.get_mut(), Some(&mut 92)); 79 | } 80 | 81 | #[test] 82 | #[cfg(feature = "private")] 83 | fn sync_once_cell_get_unchecked() { 84 | let c = OnceLock::new(); 85 | c.set(92).unwrap(); 86 | unsafe { 87 | assert_eq!(c.get_unchecked(), &92); 88 | } 89 | } 90 | 91 | #[test] 92 | #[cfg_attr(target_os = "emscripten", ignore)] 93 | fn sync_once_cell_drop() { 94 | static DROP_CNT: AtomicUsize = AtomicUsize::new(0); 95 | struct Dropper; 96 | impl Drop for Dropper { 97 | fn drop(&mut self) { 98 | DROP_CNT.fetch_add(1, SeqCst); 99 | } 100 | } 101 | 102 | let x = OnceLock::new(); 103 | spawn_and_wait(move || { 104 | x.get_or_init(|| Dropper); 105 | assert_eq!(DROP_CNT.load(SeqCst), 0); 106 | drop(x); 107 | }); 108 | 109 | assert_eq!(DROP_CNT.load(SeqCst), 1); 110 | } 111 | 112 | #[test] 113 | fn sync_once_cell_drop_empty() { 114 | let x = OnceLock::::new(); 115 | drop(x); 116 | } 117 | 118 | #[test] 119 | fn clone() { 120 | let s = OnceLock::new(); 121 | let c = s.clone(); 122 | assert!(c.get().is_none()); 123 | 124 | s.set("hello".to_string()).unwrap(); 125 | let c = s.clone(); 126 | assert_eq!(c.get().map(String::as_str), Some("hello")); 127 | } 128 | 129 | #[test] 130 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 131 | fn get_or_try_init() { 132 | let cell: OnceLock = OnceLock::new(); 133 | assert!(cell.get().is_none()); 134 | 135 | let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() })); 136 | assert!(res.is_err()); 137 | #[cfg(feature = "private")] 138 | assert!(!cell.is_initialized()); 139 | assert!(cell.get().is_none()); 140 | 141 | assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); 142 | 143 | assert_eq!( 144 | cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())), 145 | Ok(&"hello".to_string()) 146 | ); 147 | assert_eq!(cell.get(), Some(&"hello".to_string())); 148 | } 149 | 150 | #[test] 151 | fn from_impl() { 152 | assert_eq!(OnceLock::from("value").get(), Some(&"value")); 153 | assert_ne!(OnceLock::from("foo").get(), Some(&"bar")); 154 | } 155 | 156 | #[test] 157 | fn partialeq_impl() { 158 | assert!(OnceLock::from("value") == OnceLock::from("value")); 159 | assert!(OnceLock::from("foo") != OnceLock::from("bar")); 160 | 161 | assert!(OnceLock::::new() == OnceLock::new()); 162 | assert!(OnceLock::::new() != OnceLock::from("value".to_owned())); 163 | } 164 | 165 | #[test] 166 | fn into_inner() { 167 | let cell: OnceLock = OnceLock::new(); 168 | assert_eq!(cell.into_inner(), None); 169 | let cell = OnceLock::new(); 170 | cell.set("hello".to_string()).unwrap(); 171 | assert_eq!(cell.into_inner(), Some("hello".to_string())); 172 | } 173 | 174 | #[test] 175 | #[cfg_attr(target_os = "emscripten", ignore)] 176 | fn sync_lazy_new() { 177 | static CALLED: AtomicUsize = AtomicUsize::new(0); 178 | static SYNC_LAZY: LazyLock = LazyLock::new(|| { 179 | CALLED.fetch_add(1, SeqCst); 180 | 92 181 | }); 182 | 183 | assert_eq!(CALLED.load(SeqCst), 0); 184 | 185 | spawn_and_wait(|| { 186 | let y = *SYNC_LAZY - 30; 187 | assert_eq!(y, 62); 188 | assert_eq!(CALLED.load(SeqCst), 1); 189 | }); 190 | 191 | let y = *SYNC_LAZY - 30; 192 | assert_eq!(y, 62); 193 | assert_eq!(CALLED.load(SeqCst), 1); 194 | } 195 | 196 | #[test] 197 | fn sync_lazy_default() { 198 | static CALLED: AtomicUsize = AtomicUsize::new(0); 199 | 200 | struct Foo(u8); 201 | impl Default for Foo { 202 | fn default() -> Self { 203 | CALLED.fetch_add(1, SeqCst); 204 | Foo(42) 205 | } 206 | } 207 | 208 | let lazy: LazyLock> = <_>::default(); 209 | 210 | assert_eq!(CALLED.load(SeqCst), 0); 211 | 212 | assert_eq!(lazy.lock().unwrap().0, 42); 213 | assert_eq!(CALLED.load(SeqCst), 1); 214 | 215 | lazy.lock().unwrap().0 = 21; 216 | 217 | assert_eq!(lazy.lock().unwrap().0, 21); 218 | assert_eq!(CALLED.load(SeqCst), 1); 219 | } 220 | 221 | #[test] 222 | #[cfg_attr(target_os = "emscripten", ignore)] 223 | fn static_sync_lazy() { 224 | static XS: LazyLock> = LazyLock::new(|| { 225 | let mut xs = Vec::new(); 226 | xs.push(1); 227 | xs.push(2); 228 | xs.push(3); 229 | xs 230 | }); 231 | 232 | spawn_and_wait(|| { 233 | assert_eq!(&*XS, &vec![1, 2, 3]); 234 | }); 235 | 236 | assert_eq!(&*XS, &vec![1, 2, 3]); 237 | } 238 | 239 | #[test] 240 | fn static_sync_lazy_via_fn() { 241 | fn xs() -> &'static Vec { 242 | static XS: OnceLock> = OnceLock::new(); 243 | XS.get_or_init(|| { 244 | let mut xs = Vec::new(); 245 | xs.push(1); 246 | xs.push(2); 247 | xs.push(3); 248 | xs 249 | }) 250 | } 251 | assert_eq!(xs(), &vec![1, 2, 3]); 252 | } 253 | 254 | #[test] 255 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 256 | fn sync_lazy_poisoning() { 257 | let x: LazyLock = LazyLock::new(|| panic!("kaboom")); 258 | for _ in 0..2 { 259 | let res = panic::catch_unwind(|| x.len()); 260 | assert!(res.is_err()); 261 | } 262 | } 263 | 264 | #[test] 265 | fn is_sync_send() { 266 | fn assert_traits() {} 267 | assert_traits::>(); 268 | assert_traits::>(); 269 | } 270 | 271 | #[test] 272 | fn eval_once_macro() { 273 | macro_rules! eval_once { 274 | (|| -> $ty:ty { 275 | $($body:tt)* 276 | }) => {{ 277 | static ONCE_CELL: OnceLock<$ty> = OnceLock::new(); 278 | fn init() -> $ty { 279 | $($body)* 280 | } 281 | ONCE_CELL.get_or_init(init) 282 | }}; 283 | } 284 | 285 | let fib: &'static Vec = eval_once! { 286 | || -> Vec { 287 | let mut res = vec![1, 1]; 288 | for i in 0..10 { 289 | let next = res[i] + res[i + 1]; 290 | res.push(next); 291 | } 292 | res 293 | } 294 | }; 295 | assert_eq!(fib[5], 8) 296 | } 297 | 298 | #[test] 299 | #[cfg_attr(target_os = "emscripten", ignore)] 300 | fn sync_once_cell_does_not_leak_partially_constructed_boxes() { 301 | static ONCE_CELL: OnceLock = OnceLock::new(); 302 | 303 | let n_readers = 10; 304 | let n_writers = 3; 305 | const MSG: &str = "Hello, World"; 306 | 307 | let (tx, rx) = channel(); 308 | 309 | for _ in 0..n_readers { 310 | let tx = tx.clone(); 311 | thread::spawn(move || loop { 312 | if let Some(msg) = ONCE_CELL.get() { 313 | tx.send(msg).unwrap(); 314 | break; 315 | } 316 | #[cfg(target_env = "sgx")] 317 | std::thread::yield_now(); 318 | }); 319 | } 320 | for _ in 0..n_writers { 321 | thread::spawn(move || { 322 | let _ = ONCE_CELL.set(MSG.to_owned()); 323 | }); 324 | } 325 | 326 | for _ in 0..n_readers { 327 | let msg = rx.recv().unwrap(); 328 | assert_eq!(msg, MSG); 329 | } 330 | } 331 | 332 | #[test] 333 | fn dropck() { 334 | let cell = OnceLock::new(); 335 | { 336 | let s = String::new(); 337 | cell.set(&s).unwrap(); 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /tests/stdtests/net/mod.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod test; 2 | -------------------------------------------------------------------------------- /tests/stdtests/net/test.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/net/tests.rs at revision 3 | //! 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | #![allow(warnings)] // not used on emscripten 6 | 7 | use std::env; 8 | use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; 9 | use std::sync::atomic::{AtomicUsize, Ordering}; 10 | 11 | static PORT: AtomicUsize = AtomicUsize::new(0); 12 | 13 | pub fn next_test_ip4() -> SocketAddr { 14 | let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port(); 15 | SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port)) 16 | } 17 | 18 | pub fn next_test_ip6() -> SocketAddr { 19 | let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port(); 20 | SocketAddr::V6(SocketAddrV6::new( 21 | Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 22 | port, 23 | 0, 24 | 0, 25 | )) 26 | } 27 | 28 | pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr { 29 | SocketAddr::V4(SocketAddrV4::new(a, p)) 30 | } 31 | 32 | pub fn sa6(a: Ipv6Addr, p: u16) -> SocketAddr { 33 | SocketAddr::V6(SocketAddrV6::new(a, p, 0, 0)) 34 | } 35 | 36 | pub fn tsa(a: A) -> Result, String> { 37 | match a.to_socket_addrs() { 38 | Ok(a) => Ok(a.collect()), 39 | Err(e) => Err(e.to_string()), 40 | } 41 | } 42 | 43 | // The bots run multiple builds at the same time, and these builds 44 | // all want to use ports. This function figures out which workspace 45 | // it is running in and assigns a port range based on it. 46 | fn base_port() -> u16 { 47 | let cwd = if cfg!(target_env = "sgx") { 48 | String::from("sgx") 49 | } else { 50 | env::current_dir() 51 | .unwrap() 52 | .into_os_string() 53 | .into_string() 54 | .unwrap() 55 | }; 56 | let dirs = [ 57 | "32-opt", 58 | "32-nopt", 59 | "musl-64-opt", 60 | "cross-opt", 61 | "64-opt", 62 | "64-nopt", 63 | "64-opt-vg", 64 | "64-debug-opt", 65 | "all-opt", 66 | "snap3", 67 | "dist", 68 | "sgx", 69 | ]; 70 | dirs.iter() 71 | .enumerate() 72 | .find(|&(_, dir)| cwd.contains(dir)) 73 | .map(|p| p.0) 74 | .unwrap_or(0) as u16 75 | * 1000 76 | + 19600 77 | } 78 | -------------------------------------------------------------------------------- /tests/stdtests/net_addr.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/net/addr/tests.rs at revision 3 | //! 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | use super::net::test::{sa4, sa6, tsa}; 6 | use std::net::*; 7 | 8 | #[test] 9 | fn to_socket_addr_ipaddr_u16() { 10 | let a = Ipv4Addr::new(77, 88, 21, 11); 11 | let p = 12345; 12 | let e = SocketAddr::V4(SocketAddrV4::new(a, p)); 13 | assert_eq!(Ok(vec![e]), tsa((a, p))); 14 | } 15 | 16 | #[test] 17 | fn to_socket_addr_str_u16() { 18 | let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352); 19 | assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352))); 20 | 21 | let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53); 22 | assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53))); 23 | 24 | let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924); 25 | #[cfg(not(target_env = "sgx"))] 26 | assert!(tsa(("localhost", 23924)).unwrap().contains(&a)); 27 | #[cfg(target_env = "sgx")] 28 | let _ = a; 29 | } 30 | 31 | #[test] 32 | fn to_socket_addr_str() { 33 | let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352); 34 | assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352")); 35 | 36 | let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53); 37 | assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53")); 38 | 39 | let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924); 40 | #[cfg(not(target_env = "sgx"))] 41 | assert!(tsa("localhost:23924").unwrap().contains(&a)); 42 | #[cfg(target_env = "sgx")] 43 | let _ = a; 44 | } 45 | 46 | #[test] 47 | fn to_socket_addr_string() { 48 | let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352); 49 | assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352"))); 50 | assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352"))); 51 | assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352"))); 52 | 53 | let s = format!("{}:{}", "77.88.21.11", "24352"); 54 | assert_eq!(Ok(vec![a]), tsa(s)); 55 | // s has been moved into the tsa call 56 | } 57 | 58 | #[test] 59 | fn bind_udp_socket_bad() { 60 | // rust-lang/rust#53957: This is a regression test for a parsing problem 61 | // discovered as part of issue rust-lang/rust#23076, where we were 62 | // incorrectly parsing invalid input and then that would result in a 63 | // successful `UdpSocket` binding when we would expect failure. 64 | // 65 | // At one time, this test was written as a call to `tsa` with 66 | // INPUT_23076. However, that structure yields an unreliable test, 67 | // because it ends up passing junk input to the DNS server, and some DNS 68 | // servers will respond with `Ok` to such input, with the ip address of 69 | // the DNS server itself. 70 | // 71 | // This form of the test is more robust: even when the DNS server 72 | // returns its own address, it is still an error to bind a UDP socket to 73 | // a non-local address, and so we still get an error here in that case. 74 | 75 | const INPUT_23076: &str = "1200::AB00:1234::2552:7777:1313:34300"; 76 | 77 | assert!(std::net::UdpSocket::bind(INPUT_23076).is_err()) 78 | } 79 | 80 | #[test] 81 | fn set_ip() { 82 | fn ip4(low: u8) -> Ipv4Addr { 83 | Ipv4Addr::new(77, 88, 21, low) 84 | } 85 | fn ip6(low: u16) -> Ipv6Addr { 86 | Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) 87 | } 88 | 89 | let mut v4 = SocketAddrV4::new(ip4(11), 80); 90 | assert_eq!(v4.ip(), &ip4(11)); 91 | v4.set_ip(ip4(12)); 92 | assert_eq!(v4.ip(), &ip4(12)); 93 | 94 | let mut addr = SocketAddr::V4(v4); 95 | assert_eq!(addr.ip(), IpAddr::V4(ip4(12))); 96 | addr.set_ip(IpAddr::V4(ip4(13))); 97 | assert_eq!(addr.ip(), IpAddr::V4(ip4(13))); 98 | addr.set_ip(IpAddr::V6(ip6(14))); 99 | assert_eq!(addr.ip(), IpAddr::V6(ip6(14))); 100 | 101 | let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0); 102 | assert_eq!(v6.ip(), &ip6(1)); 103 | v6.set_ip(ip6(2)); 104 | assert_eq!(v6.ip(), &ip6(2)); 105 | 106 | let mut addr = SocketAddr::V6(v6); 107 | assert_eq!(addr.ip(), IpAddr::V6(ip6(2))); 108 | addr.set_ip(IpAddr::V6(ip6(3))); 109 | assert_eq!(addr.ip(), IpAddr::V6(ip6(3))); 110 | addr.set_ip(IpAddr::V4(ip4(4))); 111 | assert_eq!(addr.ip(), IpAddr::V4(ip4(4))); 112 | } 113 | 114 | #[test] 115 | fn set_port() { 116 | let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80); 117 | assert_eq!(v4.port(), 80); 118 | v4.set_port(443); 119 | assert_eq!(v4.port(), 443); 120 | 121 | let mut addr = SocketAddr::V4(v4); 122 | assert_eq!(addr.port(), 443); 123 | addr.set_port(8080); 124 | assert_eq!(addr.port(), 8080); 125 | 126 | let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0); 127 | assert_eq!(v6.port(), 80); 128 | v6.set_port(443); 129 | assert_eq!(v6.port(), 443); 130 | 131 | let mut addr = SocketAddr::V6(v6); 132 | assert_eq!(addr.port(), 443); 133 | addr.set_port(8080); 134 | assert_eq!(addr.port(), 8080); 135 | } 136 | 137 | #[test] 138 | fn set_flowinfo() { 139 | let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0); 140 | assert_eq!(v6.flowinfo(), 10); 141 | v6.set_flowinfo(20); 142 | assert_eq!(v6.flowinfo(), 20); 143 | } 144 | 145 | #[test] 146 | fn set_scope_id() { 147 | let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10); 148 | assert_eq!(v6.scope_id(), 10); 149 | v6.set_scope_id(20); 150 | assert_eq!(v6.scope_id(), 20); 151 | } 152 | 153 | #[test] 154 | fn is_v4() { 155 | let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80)); 156 | assert!(v4.is_ipv4()); 157 | assert!(!v4.is_ipv6()); 158 | } 159 | 160 | #[test] 161 | fn is_v6() { 162 | let v6 = SocketAddr::V6(SocketAddrV6::new( 163 | Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 164 | 80, 165 | 10, 166 | 0, 167 | )); 168 | assert!(!v6.is_ipv4()); 169 | assert!(v6.is_ipv6()); 170 | } 171 | 172 | #[test] 173 | fn socket_v4_to_str() { 174 | let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080); 175 | 176 | assert_eq!(format!("{}", socket), "192.168.0.1:8080"); 177 | assert_eq!(format!("{:<20}", socket), "192.168.0.1:8080 "); 178 | assert_eq!(format!("{:>20}", socket), " 192.168.0.1:8080"); 179 | assert_eq!(format!("{:^20}", socket), " 192.168.0.1:8080 "); 180 | assert_eq!(format!("{:.10}", socket), "192.168.0."); 181 | } 182 | 183 | #[test] 184 | fn socket_v6_to_str() { 185 | let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0); 186 | 187 | assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53"); 188 | assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 "); 189 | assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53"); 190 | assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 "); 191 | assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::"); 192 | 193 | socket.set_scope_id(5); 194 | 195 | assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1%5]:53"); 196 | assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1%5]:53 "); 197 | assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1%5]:53"); 198 | assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1%5]:53 "); 199 | assert_eq!(format!("{:.18}", socket), "[2a02:6b8:0:1::1%5"); 200 | } 201 | 202 | #[test] 203 | fn compare() { 204 | let v4_1 = "224.120.45.1:23456".parse::().unwrap(); 205 | let v4_2 = "224.210.103.5:12345".parse::().unwrap(); 206 | let v4_3 = "224.210.103.5:23456".parse::().unwrap(); 207 | let v6_1 = "[2001:db8:f00::1002]:23456" 208 | .parse::() 209 | .unwrap(); 210 | let v6_2 = "[2001:db8:f00::2001]:12345" 211 | .parse::() 212 | .unwrap(); 213 | let v6_3 = "[2001:db8:f00::2001]:23456" 214 | .parse::() 215 | .unwrap(); 216 | 217 | // equality 218 | assert_eq!(v4_1, v4_1); 219 | assert_eq!(v6_1, v6_1); 220 | assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1)); 221 | assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1)); 222 | assert!(v4_1 != v4_2); 223 | assert!(v6_1 != v6_2); 224 | 225 | // compare different addresses 226 | assert!(v4_1 < v4_2); 227 | assert!(v6_1 < v6_2); 228 | assert!(v4_2 > v4_1); 229 | assert!(v6_2 > v6_1); 230 | 231 | // compare the same address with different ports 232 | assert!(v4_2 < v4_3); 233 | assert!(v6_2 < v6_3); 234 | assert!(v4_3 > v4_2); 235 | assert!(v6_3 > v6_2); 236 | 237 | // compare different addresses with the same port 238 | assert!(v4_1 < v4_3); 239 | assert!(v6_1 < v6_3); 240 | assert!(v4_3 > v4_1); 241 | assert!(v6_3 > v6_1); 242 | 243 | // compare with an inferred right-hand side 244 | assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap()); 245 | assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap()); 246 | assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap()); 247 | } 248 | -------------------------------------------------------------------------------- /tests/stdtests/panic.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/panic/tests.rs at revision 3 | //! a61b9638bbbb48f9c2fde0ccbbcf03e64494ea0f. 4 | 5 | #![allow(dead_code)] 6 | 7 | use std::cell::RefCell; 8 | use std::panic::{AssertUnwindSafe, UnwindSafe}; 9 | use std::rc::Rc; 10 | use std::sync::{Arc, Mutex, RwLock}; 11 | 12 | struct Foo { 13 | a: i32, 14 | } 15 | 16 | fn assert() {} 17 | 18 | #[test] 19 | fn panic_safety_traits() { 20 | assert::(); 21 | assert::<&i32>(); 22 | assert::<*mut i32>(); 23 | assert::<*const i32>(); 24 | assert::(); 25 | assert::(); 26 | assert::<&str>(); 27 | assert::(); 28 | assert::<&Foo>(); 29 | assert::>(); 30 | assert::(); 31 | assert::>(); 32 | assert::>(); 33 | assert::>(); 34 | assert::>(); 35 | assert::<&Mutex>(); 36 | assert::<&RwLock>(); 37 | assert::>(); 38 | assert::>(); 39 | assert::>(); 40 | 41 | { 42 | trait Trait: UnwindSafe {} 43 | assert::>(); 44 | } 45 | 46 | fn bar() { 47 | assert::>(); 48 | assert::>(); 49 | } 50 | 51 | fn baz() { 52 | assert::>(); 53 | assert::>(); 54 | assert::>(); 55 | assert::>(); 56 | assert::<&AssertUnwindSafe>(); 57 | assert::>>(); 58 | assert::>>(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /tests/stdtests/process_common.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sys/unix/process/process_common/tests.rs at revision 3 | //! a52c79e859142c1cd5c0c5bdb73f16b754e1b98f. 4 | 5 | use std::ffi::OsStr; 6 | use std::io::{Read, Write}; 7 | use std::mem; 8 | #[cfg(unix)] 9 | use std::os::unix::process::CommandExt; 10 | use std::process::{Command, Stdio}; 11 | use std::ptr; 12 | 13 | #[doc(hidden)] 14 | pub trait IsMinusOne { 15 | fn is_minus_one(&self) -> bool; 16 | } 17 | 18 | macro_rules! impl_is_minus_one { 19 | ($($t:ident)*) => ($(impl IsMinusOne for $t { 20 | fn is_minus_one(&self) -> bool { 21 | *self == -1 22 | } 23 | })*) 24 | } 25 | 26 | impl_is_minus_one! { i8 i16 i32 i64 isize } 27 | 28 | pub fn cvt(t: T) -> std::io::Result { 29 | if t.is_minus_one() { 30 | Err(std::io::Error::last_os_error()) 31 | } else { 32 | Ok(t) 33 | } 34 | } 35 | 36 | pub fn cvt_r(mut f: F) -> std::io::Result 37 | where 38 | T: IsMinusOne, 39 | F: FnMut() -> T, 40 | { 41 | loop { 42 | match cvt(f()) { 43 | Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {} 44 | other => return other, 45 | } 46 | } 47 | } 48 | 49 | #[allow(dead_code)] // Not used on all platforms. 50 | pub fn cvt_nz(error: libc::c_int) -> std::io::Result<()> { 51 | if error == 0 { 52 | Ok(()) 53 | } else { 54 | Err(std::io::Error::from_raw_os_error(error)) 55 | } 56 | } 57 | 58 | macro_rules! t { 59 | ($e:expr) => { 60 | match $e { 61 | Ok(t) => t, 62 | Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), 63 | } 64 | }; 65 | } 66 | 67 | #[test] 68 | #[cfg_attr( 69 | any( 70 | // See #14232 for more information, but it appears that signal delivery to a 71 | // newly spawned process may just be raced in the macOS, so to prevent this 72 | // test from being flaky we ignore it on macOS. 73 | target_os = "macos", 74 | // When run under our current QEMU emulation test suite this test fails, 75 | // although the reason isn't very clear as to why. For now this test is 76 | // ignored there. 77 | target_arch = "arm", 78 | target_arch = "aarch64", 79 | target_arch = "riscv64", 80 | ), 81 | ignore 82 | )] 83 | fn test_process_mask() { 84 | // Test to make sure that a signal mask *does* get inherited. 85 | fn test_inner(mut cmd: Command) { 86 | unsafe { 87 | let mut set = mem::MaybeUninit::::uninit(); 88 | let mut old_set = mem::MaybeUninit::::uninit(); 89 | t!(cvt(libc::sigemptyset(set.as_mut_ptr()))); 90 | t!(cvt(libc::sigaddset(set.as_mut_ptr(), libc::SIGINT))); 91 | t!(cvt_nz(libc::pthread_sigmask( 92 | libc::SIG_SETMASK, 93 | set.as_ptr(), 94 | old_set.as_mut_ptr() 95 | ))); 96 | 97 | cmd.stdin(Stdio::piped()); 98 | cmd.stdout(Stdio::piped()); 99 | cmd.stderr(Stdio::null()); 100 | 101 | let mut child = t!(cmd.spawn()); 102 | let mut stdin_write = child.stdin.take().unwrap(); 103 | let mut stdout_read = child.stdout.take().unwrap(); 104 | 105 | t!(cvt_nz(libc::pthread_sigmask( 106 | libc::SIG_SETMASK, 107 | old_set.as_ptr(), 108 | ptr::null_mut() 109 | ))); 110 | 111 | t!(cvt(libc::kill(child.id() as libc::pid_t, libc::SIGINT))); 112 | // We need to wait until SIGINT is definitely delivered. The 113 | // easiest way is to write something to cat, and try to read it 114 | // back: if SIGINT is unmasked, it'll get delivered when cat is 115 | // next scheduled. 116 | let _ = stdin_write.write(b"Hello"); 117 | drop(stdin_write); 118 | 119 | // Exactly 5 bytes should be read. 120 | let mut buf = [0; 5]; 121 | let ret = t!(stdout_read.read(&mut buf)); 122 | assert_eq!(ret, 5); 123 | assert_eq!(&buf, b"Hello"); 124 | 125 | t!(child.wait()); 126 | } 127 | } 128 | 129 | // A plain `Command::new` uses the posix_spawn path on many platforms. 130 | let cmd = Command::new(OsStr::new("cat")); 131 | test_inner(cmd); 132 | 133 | // Specifying `pre_exec` forces the fork/exec path. 134 | let mut cmd = Command::new(OsStr::new("cat")); 135 | unsafe { cmd.pre_exec(Box::new(|| Ok(()))) }; 136 | test_inner(cmd); 137 | } 138 | 139 | #[test] 140 | #[cfg_attr( 141 | any( 142 | // See test_process_mask 143 | target_os = "macos", 144 | target_arch = "arm", 145 | target_arch = "aarch64", 146 | target_arch = "riscv64", 147 | ), 148 | ignore 149 | )] 150 | fn test_process_group_posix_spawn() { 151 | unsafe { 152 | // Spawn a cat subprocess that's just going to hang since there is no I/O. 153 | let mut cmd = Command::new(OsStr::new("cat")); 154 | cmd.process_group(0); 155 | cmd.stdin(Stdio::piped()); 156 | cmd.stdout(Stdio::piped()); 157 | cmd.stderr(Stdio::null()); 158 | let mut child = t!(cmd.spawn()); 159 | 160 | // Check that we can kill its process group, which means there *is* one. 161 | t!(cvt(libc::kill(-(child.id() as libc::pid_t), libc::SIGINT))); 162 | 163 | t!(child.wait()); 164 | } 165 | } 166 | 167 | #[test] 168 | #[cfg_attr( 169 | any( 170 | // See test_process_mask 171 | target_os = "macos", 172 | target_arch = "arm", 173 | target_arch = "aarch64", 174 | target_arch = "riscv64", 175 | ), 176 | ignore 177 | )] 178 | fn test_process_group_no_posix_spawn() { 179 | unsafe { 180 | // Same as above, create hang-y cat. This time, force using the non-posix_spawnp path. 181 | let mut cmd = Command::new(OsStr::new("cat")); 182 | cmd.process_group(0); 183 | cmd.pre_exec(Box::new(|| Ok(()))); // pre_exec forces fork + exec 184 | cmd.stdin(Stdio::piped()); 185 | cmd.stdout(Stdio::piped()); 186 | cmd.stderr(Stdio::null()); 187 | let mut child = t!(cmd.spawn()); 188 | 189 | // Check that we can kill its process group, which means there *is* one. 190 | t!(cvt(libc::kill(-(child.id() as libc::pid_t), libc::SIGINT))); 191 | 192 | t!(child.wait()); 193 | } 194 | } 195 | 196 | /* 197 | #[test] 198 | fn test_program_kind() { 199 | let vectors = &[ 200 | ("foo", ProgramKind::PathLookup), 201 | ("foo.out", ProgramKind::PathLookup), 202 | ("./foo", ProgramKind::Relative), 203 | ("../foo", ProgramKind::Relative), 204 | ("dir/foo", ProgramKind::Relative), 205 | // Note that paths on Unix can't contain / in them, so this is actually the directory "fo\\" 206 | // followed by the file "o". 207 | ("fo\\/o", ProgramKind::Relative), 208 | ("/foo", ProgramKind::Absolute), 209 | ("/dir/../foo", ProgramKind::Absolute), 210 | ]; 211 | 212 | for (program, expected_kind) in vectors { 213 | assert_eq!( 214 | ProgramKind::new(program.as_ref()), 215 | *expected_kind, 216 | "actual != expected program kind for input {program}", 217 | ); 218 | } 219 | } 220 | */ 221 | -------------------------------------------------------------------------------- /tests/stdtests/process_unix.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sys/unix/process/process_unix/tests.rs at revision 3 | //! 0b35f448f8e9f39ed6fc1c494eeb331afba513bc. 4 | 5 | use std::os::unix::process::{CommandExt, ExitStatusExt}; 6 | use std::panic::catch_unwind; 7 | use std::process::Command; 8 | 9 | // Many of the other aspects of this situation, including heap alloc concurrency 10 | // safety etc., are tested in tests/ui/process/process-panic-after-fork.rs 11 | 12 | #[test] 13 | fn exitstatus_display_tests() { 14 | // In practice this is the same on every Unix. 15 | // If some weird platform turns out to be different, and this test fails, use #[cfg]. 16 | use std::os::unix::process::ExitStatusExt; 17 | use std::process::ExitStatus; 18 | 19 | let t = |v, s| assert_eq!(s, format!("{}", ::from_raw(v))); 20 | 21 | t(0x0000f, "signal: 15 (SIGTERM)"); 22 | t(0x0008b, "signal: 11 (SIGSEGV) (core dumped)"); 23 | t(0x00000, "exit status: 0"); 24 | t(0x0ff00, "exit status: 255"); 25 | 26 | // On MacOS, 0x0137f is WIFCONTINUED, not WIFSTOPPED. Probably *BSD is similar. 27 | // https://github.com/rust-lang/rust/pull/82749#issuecomment-790525956 28 | // The purpose of this test is to test our string formatting, not our understanding of the wait 29 | // status magic numbers. So restrict these to Linux. 30 | if cfg!(target_os = "linux") { 31 | t(0x0137f, "stopped (not terminated) by signal: 19 (SIGSTOP)"); 32 | t(0x0ffff, "continued (WIFCONTINUED)"); 33 | } 34 | 35 | // Testing "unrecognised wait status" is hard because the wait.h macros typically 36 | // assume that the value came from wait and isn't mad. With the glibc I have here 37 | // this works: 38 | if cfg!(all(target_os = "linux", target_env = "gnu")) { 39 | t(0x000ff, "unrecognised wait status: 255 0xff"); 40 | } 41 | } 42 | 43 | #[test] 44 | #[cfg_attr(target_os = "emscripten", ignore)] 45 | fn test_command_fork_no_unwind() { 46 | let got = catch_unwind(|| { 47 | let mut c = Command::new("echo"); 48 | c.arg("hi"); 49 | unsafe { 50 | c.pre_exec(|| panic!("{}", "crash now!")); 51 | } 52 | let st = c.status().expect("failed to get command status"); 53 | dbg!(st); 54 | st 55 | }); 56 | dbg!(&got); 57 | let status = got.expect("panic unexpectedly propagated"); 58 | dbg!(status); 59 | let signal = status 60 | .signal() 61 | .expect("expected child process to die of signal"); 62 | assert!( 63 | signal == libc::SIGABRT 64 | || signal == libc::SIGILL 65 | || signal == libc::SIGTRAP 66 | || signal == libc::SIGSEGV 67 | ); 68 | } 69 | -------------------------------------------------------------------------------- /tests/stdtests/sync_barrier.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/barrier.rs at revision 3 | //! 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | use std::sync::mpsc::{channel, TryRecvError}; 6 | use std::sync::{Arc, Barrier}; 7 | use std::thread; 8 | 9 | #[test] 10 | #[cfg_attr(target_os = "emscripten", ignore)] 11 | fn test_barrier() { 12 | const N: usize = 10; 13 | 14 | let barrier = Arc::new(Barrier::new(N)); 15 | let (tx, rx) = channel(); 16 | 17 | for _ in 0..N - 1 { 18 | let c = barrier.clone(); 19 | let tx = tx.clone(); 20 | thread::spawn(move || { 21 | tx.send(c.wait().is_leader()).unwrap(); 22 | }); 23 | } 24 | 25 | // At this point, all spawned threads should be blocked, 26 | // so we shouldn't get anything from the port 27 | assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty))); 28 | 29 | let mut leader_found = barrier.wait().is_leader(); 30 | 31 | // Now, the barrier is cleared and we should get data. 32 | for _ in 0..N - 1 { 33 | if rx.recv().unwrap() { 34 | assert!(!leader_found); 35 | leader_found = true; 36 | } 37 | } 38 | assert!(leader_found); 39 | } 40 | -------------------------------------------------------------------------------- /tests/stdtests/sync_condvar.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/condvar/tests.rs at revision 3 | //! 21c5f780f464b27802d0ee0f86c95eb29881096b. 4 | 5 | use std::sync::atomic::{AtomicBool, Ordering}; 6 | use std::sync::mpsc::channel; 7 | use std::sync::{Arc, Condvar, Mutex}; 8 | use std::thread; 9 | use std::time::Duration; 10 | 11 | #[test] 12 | fn smoke() { 13 | let c = Condvar::new(); 14 | c.notify_one(); 15 | c.notify_all(); 16 | } 17 | 18 | #[test] 19 | #[cfg_attr(target_os = "emscripten", ignore)] 20 | fn notify_one() { 21 | let m = Arc::new(Mutex::new(())); 22 | let m2 = m.clone(); 23 | let c = Arc::new(Condvar::new()); 24 | let c2 = c.clone(); 25 | 26 | let g = m.lock().unwrap(); 27 | let _t = thread::spawn(move || { 28 | let _g = m2.lock().unwrap(); 29 | c2.notify_one(); 30 | }); 31 | let g = c.wait(g).unwrap(); 32 | drop(g); 33 | } 34 | 35 | #[test] 36 | #[cfg_attr(target_os = "emscripten", ignore)] 37 | fn notify_all() { 38 | const N: usize = 10; 39 | 40 | let data = Arc::new((Mutex::new(0), Condvar::new())); 41 | let (tx, rx) = channel(); 42 | for _ in 0..N { 43 | let data = data.clone(); 44 | let tx = tx.clone(); 45 | thread::spawn(move || { 46 | let &(ref lock, ref cond) = &*data; 47 | let mut cnt = lock.lock().unwrap(); 48 | *cnt += 1; 49 | if *cnt == N { 50 | tx.send(()).unwrap(); 51 | } 52 | while *cnt != 0 { 53 | cnt = cond.wait(cnt).unwrap(); 54 | } 55 | tx.send(()).unwrap(); 56 | }); 57 | } 58 | drop(tx); 59 | 60 | let &(ref lock, ref cond) = &*data; 61 | rx.recv().unwrap(); 62 | let mut cnt = lock.lock().unwrap(); 63 | *cnt = 0; 64 | cond.notify_all(); 65 | drop(cnt); 66 | 67 | for _ in 0..N { 68 | rx.recv().unwrap(); 69 | } 70 | } 71 | 72 | #[test] 73 | #[cfg_attr(target_os = "emscripten", ignore)] 74 | fn wait_while() { 75 | let pair = Arc::new((Mutex::new(false), Condvar::new())); 76 | let pair2 = pair.clone(); 77 | 78 | // Inside of our lock, spawn a new thread, and then wait for it to start. 79 | thread::spawn(move || { 80 | let &(ref lock, ref cvar) = &*pair2; 81 | let mut started = lock.lock().unwrap(); 82 | *started = true; 83 | // We notify the condvar that the value has changed. 84 | cvar.notify_one(); 85 | }); 86 | 87 | // Wait for the thread to start up. 88 | let &(ref lock, ref cvar) = &*pair; 89 | let guard = cvar.wait_while(lock.lock().unwrap(), |started| !*started); 90 | assert!(*guard.unwrap()); 91 | } 92 | 93 | #[test] 94 | #[cfg_attr(target_os = "emscripten", ignore)] 95 | fn wait_timeout_wait() { 96 | let m = Arc::new(Mutex::new(())); 97 | let c = Arc::new(Condvar::new()); 98 | 99 | loop { 100 | let g = m.lock().unwrap(); 101 | let (_g, no_timeout) = c.wait_timeout(g, Duration::from_millis(1)).unwrap(); 102 | // spurious wakeups mean this isn't necessarily true 103 | // so execute test again, if not timeout 104 | if !no_timeout.timed_out() { 105 | continue; 106 | } 107 | 108 | break; 109 | } 110 | } 111 | 112 | #[test] 113 | #[cfg_attr(target_os = "emscripten", ignore)] 114 | fn wait_timeout_while_wait() { 115 | let m = Arc::new(Mutex::new(())); 116 | let c = Arc::new(Condvar::new()); 117 | 118 | let g = m.lock().unwrap(); 119 | let (_g, wait) = c 120 | .wait_timeout_while(g, Duration::from_millis(1), |_| true) 121 | .unwrap(); 122 | // no spurious wakeups. ensure it timed-out 123 | assert!(wait.timed_out()); 124 | } 125 | 126 | #[test] 127 | #[cfg_attr(target_os = "emscripten", ignore)] 128 | fn wait_timeout_while_instant_satisfy() { 129 | let m = Arc::new(Mutex::new(())); 130 | let c = Arc::new(Condvar::new()); 131 | 132 | let g = m.lock().unwrap(); 133 | let (_g, wait) = c 134 | .wait_timeout_while(g, Duration::from_millis(0), |_| false) 135 | .unwrap(); 136 | // ensure it didn't time-out even if we were not given any time. 137 | assert!(!wait.timed_out()); 138 | } 139 | 140 | #[test] 141 | #[cfg_attr(target_os = "emscripten", ignore)] 142 | fn wait_timeout_while_wake() { 143 | let pair = Arc::new((Mutex::new(false), Condvar::new())); 144 | let pair_copy = pair.clone(); 145 | 146 | let &(ref m, ref c) = &*pair; 147 | let g = m.lock().unwrap(); 148 | let _t = thread::spawn(move || { 149 | let &(ref lock, ref cvar) = &*pair_copy; 150 | let mut started = lock.lock().unwrap(); 151 | thread::sleep(Duration::from_millis(1)); 152 | *started = true; 153 | cvar.notify_one(); 154 | }); 155 | let (g2, wait) = c 156 | .wait_timeout_while(g, Duration::from_millis(u64::MAX), |&mut notified| { 157 | !notified 158 | }) 159 | .unwrap(); 160 | // ensure it didn't time-out even if we were not given any time. 161 | assert!(!wait.timed_out()); 162 | assert!(*g2); 163 | } 164 | 165 | #[test] 166 | #[cfg_attr(target_os = "emscripten", ignore)] 167 | fn wait_timeout_wake() { 168 | let m = Arc::new(Mutex::new(())); 169 | let c = Arc::new(Condvar::new()); 170 | 171 | loop { 172 | let g = m.lock().unwrap(); 173 | 174 | let c2 = c.clone(); 175 | let m2 = m.clone(); 176 | 177 | let notified = Arc::new(AtomicBool::new(false)); 178 | let notified_copy = notified.clone(); 179 | 180 | let t = thread::spawn(move || { 181 | let _g = m2.lock().unwrap(); 182 | thread::sleep(Duration::from_millis(1)); 183 | notified_copy.store(true, Ordering::SeqCst); 184 | c2.notify_one(); 185 | }); 186 | let (g, timeout_res) = c.wait_timeout(g, Duration::from_millis(u64::MAX)).unwrap(); 187 | assert!(!timeout_res.timed_out()); 188 | // spurious wakeups mean this isn't necessarily true 189 | // so execute test again, if not notified 190 | if !notified.load(Ordering::SeqCst) { 191 | t.join().unwrap(); 192 | continue; 193 | } 194 | drop(g); 195 | 196 | t.join().unwrap(); 197 | 198 | break; 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /tests/stdtests/sync_lazy_lock.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/lazy_lock/tests.rs at revision 3 | //! c1a2db3372a4d6896744919284f3287650a38ab7. 4 | 5 | use std::{ 6 | cell::LazyCell, 7 | panic, 8 | sync::{ 9 | atomic::{AtomicUsize, Ordering::SeqCst}, 10 | Mutex, 11 | }, 12 | sync::{LazyLock, OnceLock}, 13 | thread, 14 | }; 15 | 16 | fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { 17 | thread::spawn(f).join().unwrap() 18 | } 19 | 20 | #[test] 21 | fn lazy_default() { 22 | static CALLED: AtomicUsize = AtomicUsize::new(0); 23 | 24 | struct Foo(u8); 25 | impl Default for Foo { 26 | fn default() -> Self { 27 | CALLED.fetch_add(1, SeqCst); 28 | Foo(42) 29 | } 30 | } 31 | 32 | let lazy: LazyCell> = <_>::default(); 33 | 34 | assert_eq!(CALLED.load(SeqCst), 0); 35 | 36 | assert_eq!(lazy.lock().unwrap().0, 42); 37 | assert_eq!(CALLED.load(SeqCst), 1); 38 | 39 | lazy.lock().unwrap().0 = 21; 40 | 41 | assert_eq!(lazy.lock().unwrap().0, 21); 42 | assert_eq!(CALLED.load(SeqCst), 1); 43 | } 44 | 45 | #[test] 46 | fn lazy_poisoning() { 47 | let x: LazyCell = LazyCell::new(|| panic!("kaboom")); 48 | for _ in 0..2 { 49 | let res = panic::catch_unwind(panic::AssertUnwindSafe(|| x.len())); 50 | assert!(res.is_err()); 51 | } 52 | } 53 | 54 | #[test] 55 | #[cfg_attr(target_os = "emscripten", ignore)] 56 | fn sync_lazy_new() { 57 | static CALLED: AtomicUsize = AtomicUsize::new(0); 58 | static SYNC_LAZY: LazyLock = LazyLock::new(|| { 59 | CALLED.fetch_add(1, SeqCst); 60 | 92 61 | }); 62 | 63 | assert_eq!(CALLED.load(SeqCst), 0); 64 | 65 | spawn_and_wait(|| { 66 | let y = *SYNC_LAZY - 30; 67 | assert_eq!(y, 62); 68 | assert_eq!(CALLED.load(SeqCst), 1); 69 | }); 70 | 71 | let y = *SYNC_LAZY - 30; 72 | assert_eq!(y, 62); 73 | assert_eq!(CALLED.load(SeqCst), 1); 74 | } 75 | 76 | #[test] 77 | fn sync_lazy_default() { 78 | static CALLED: AtomicUsize = AtomicUsize::new(0); 79 | 80 | struct Foo(u8); 81 | impl Default for Foo { 82 | fn default() -> Self { 83 | CALLED.fetch_add(1, SeqCst); 84 | Foo(42) 85 | } 86 | } 87 | 88 | let lazy: LazyLock> = <_>::default(); 89 | 90 | assert_eq!(CALLED.load(SeqCst), 0); 91 | 92 | assert_eq!(lazy.lock().unwrap().0, 42); 93 | assert_eq!(CALLED.load(SeqCst), 1); 94 | 95 | lazy.lock().unwrap().0 = 21; 96 | 97 | assert_eq!(lazy.lock().unwrap().0, 21); 98 | assert_eq!(CALLED.load(SeqCst), 1); 99 | } 100 | 101 | #[test] 102 | #[cfg_attr(target_os = "emscripten", ignore)] 103 | fn static_sync_lazy() { 104 | static XS: LazyLock> = LazyLock::new(|| { 105 | let mut xs = Vec::new(); 106 | xs.push(1); 107 | xs.push(2); 108 | xs.push(3); 109 | xs 110 | }); 111 | 112 | spawn_and_wait(|| { 113 | assert_eq!(&*XS, &vec![1, 2, 3]); 114 | }); 115 | 116 | assert_eq!(&*XS, &vec![1, 2, 3]); 117 | } 118 | 119 | #[test] 120 | fn static_sync_lazy_via_fn() { 121 | fn xs() -> &'static Vec { 122 | static XS: OnceLock> = OnceLock::new(); 123 | XS.get_or_init(|| { 124 | let mut xs = Vec::new(); 125 | xs.push(1); 126 | xs.push(2); 127 | xs.push(3); 128 | xs 129 | }) 130 | } 131 | assert_eq!(xs(), &vec![1, 2, 3]); 132 | } 133 | 134 | #[test] 135 | fn sync_lazy_poisoning() { 136 | let x: LazyLock = LazyLock::new(|| panic!("kaboom")); 137 | for _ in 0..2 { 138 | let res = panic::catch_unwind(|| x.len()); 139 | assert!(res.is_err()); 140 | } 141 | } 142 | 143 | #[test] 144 | fn is_sync_send() { 145 | fn assert_traits() {} 146 | assert_traits::>(); 147 | } 148 | -------------------------------------------------------------------------------- /tests/stdtests/sync_mutex.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/mutex/tests.rs at revision 3 | //! 72a25d05bf1a4b155d74139ef700ff93af6d8e22. 4 | 5 | use std::sync::atomic::{AtomicUsize, Ordering}; 6 | use std::sync::mpsc::channel; 7 | use std::sync::Condvar; 8 | use std::sync::{Arc, Mutex}; 9 | use std::thread; 10 | 11 | struct Packet(Arc<(Mutex, Condvar)>); 12 | 13 | #[derive(Eq, PartialEq, Debug)] 14 | struct NonCopy(i32); 15 | 16 | #[test] 17 | fn smoke() { 18 | let m = Mutex::new(()); 19 | drop(m.lock().unwrap()); 20 | drop(m.lock().unwrap()); 21 | } 22 | 23 | #[test] 24 | fn lots_and_lots() { 25 | const J: u32 = 1000; 26 | const K: u32 = 3; 27 | 28 | let m = Arc::new(Mutex::new(0)); 29 | 30 | fn inc(m: &Mutex) { 31 | for _ in 0..J { 32 | *m.lock().unwrap() += 1; 33 | } 34 | } 35 | 36 | let (tx, rx) = channel(); 37 | for _ in 0..K { 38 | let tx2 = tx.clone(); 39 | let m2 = m.clone(); 40 | thread::spawn(move || { 41 | inc(&m2); 42 | tx2.send(()).unwrap(); 43 | }); 44 | let tx2 = tx.clone(); 45 | let m2 = m.clone(); 46 | thread::spawn(move || { 47 | inc(&m2); 48 | tx2.send(()).unwrap(); 49 | }); 50 | } 51 | 52 | drop(tx); 53 | for _ in 0..2 * K { 54 | rx.recv().unwrap(); 55 | } 56 | assert_eq!(*m.lock().unwrap(), J * K * 2); 57 | } 58 | 59 | #[test] 60 | fn try_lock() { 61 | let m = Mutex::new(()); 62 | *m.try_lock().unwrap() = (); 63 | } 64 | 65 | #[test] 66 | fn test_into_inner() { 67 | let m = Mutex::new(NonCopy(10)); 68 | assert_eq!(m.into_inner().unwrap(), NonCopy(10)); 69 | } 70 | 71 | #[test] 72 | fn test_into_inner_drop() { 73 | struct Foo(Arc); 74 | impl Drop for Foo { 75 | fn drop(&mut self) { 76 | self.0.fetch_add(1, Ordering::SeqCst); 77 | } 78 | } 79 | let num_drops = Arc::new(AtomicUsize::new(0)); 80 | let m = Mutex::new(Foo(num_drops.clone())); 81 | assert_eq!(num_drops.load(Ordering::SeqCst), 0); 82 | { 83 | let _inner = m.into_inner().unwrap(); 84 | assert_eq!(num_drops.load(Ordering::SeqCst), 0); 85 | } 86 | assert_eq!(num_drops.load(Ordering::SeqCst), 1); 87 | } 88 | 89 | #[test] 90 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 91 | fn test_into_inner_poison() { 92 | let m = Arc::new(Mutex::new(NonCopy(10))); 93 | let m2 = m.clone(); 94 | let _ = thread::spawn(move || { 95 | let _lock = m2.lock().unwrap(); 96 | panic!("test panic in inner thread to poison mutex"); 97 | }) 98 | .join(); 99 | 100 | assert!(m.is_poisoned()); 101 | match Arc::try_unwrap(m).unwrap().into_inner() { 102 | Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), 103 | Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {x:?}"), 104 | } 105 | } 106 | 107 | #[test] 108 | fn test_get_mut() { 109 | let mut m = Mutex::new(NonCopy(10)); 110 | *m.get_mut().unwrap() = NonCopy(20); 111 | assert_eq!(m.into_inner().unwrap(), NonCopy(20)); 112 | } 113 | 114 | #[test] 115 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 116 | fn test_get_mut_poison() { 117 | let m = Arc::new(Mutex::new(NonCopy(10))); 118 | let m2 = m.clone(); 119 | let _ = thread::spawn(move || { 120 | let _lock = m2.lock().unwrap(); 121 | panic!("test panic in inner thread to poison mutex"); 122 | }) 123 | .join(); 124 | 125 | assert!(m.is_poisoned()); 126 | match Arc::try_unwrap(m).unwrap().get_mut() { 127 | Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), 128 | Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {x:?}"), 129 | } 130 | } 131 | 132 | #[test] 133 | fn test_mutex_arc_condvar() { 134 | let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); 135 | let packet2 = Packet(packet.0.clone()); 136 | let (tx, rx) = channel(); 137 | let _t = thread::spawn(move || { 138 | // wait until parent gets in 139 | rx.recv().unwrap(); 140 | let &(ref lock, ref cvar) = &*packet2.0; 141 | let mut lock = lock.lock().unwrap(); 142 | *lock = true; 143 | cvar.notify_one(); 144 | }); 145 | 146 | let &(ref lock, ref cvar) = &*packet.0; 147 | let mut lock = lock.lock().unwrap(); 148 | tx.send(()).unwrap(); 149 | assert!(!*lock); 150 | while !*lock { 151 | lock = cvar.wait(lock).unwrap(); 152 | } 153 | } 154 | 155 | #[test] 156 | fn test_arc_condvar_poison() { 157 | let packet = Packet(Arc::new((Mutex::new(1), Condvar::new()))); 158 | let packet2 = Packet(packet.0.clone()); 159 | let (tx, rx) = channel(); 160 | 161 | let _t = thread::spawn(move || -> () { 162 | rx.recv().unwrap(); 163 | let &(ref lock, ref cvar) = &*packet2.0; 164 | let _g = lock.lock().unwrap(); 165 | cvar.notify_one(); 166 | // Parent should fail when it wakes up. 167 | panic!(); 168 | }); 169 | 170 | let &(ref lock, ref cvar) = &*packet.0; 171 | let mut lock = lock.lock().unwrap(); 172 | tx.send(()).unwrap(); 173 | while *lock == 1 { 174 | match cvar.wait(lock) { 175 | Ok(l) => { 176 | lock = l; 177 | assert_eq!(*lock, 1); 178 | } 179 | Err(..) => break, 180 | } 181 | } 182 | } 183 | 184 | #[test] 185 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 186 | fn test_mutex_arc_poison() { 187 | let arc = Arc::new(Mutex::new(1)); 188 | assert!(!arc.is_poisoned()); 189 | let arc2 = arc.clone(); 190 | let _ = thread::spawn(move || { 191 | let lock = arc2.lock().unwrap(); 192 | assert_eq!(*lock, 2); 193 | }) 194 | .join(); 195 | assert!(arc.lock().is_err()); 196 | assert!(arc.is_poisoned()); 197 | } 198 | 199 | #[test] 200 | fn test_mutex_arc_nested() { 201 | // Tests nested mutexes and access 202 | // to underlying data. 203 | let arc = Arc::new(Mutex::new(1)); 204 | let arc2 = Arc::new(Mutex::new(arc)); 205 | let (tx, rx) = channel(); 206 | let _t = thread::spawn(move || { 207 | let lock = arc2.lock().unwrap(); 208 | let lock2 = lock.lock().unwrap(); 209 | assert_eq!(*lock2, 1); 210 | tx.send(()).unwrap(); 211 | }); 212 | rx.recv().unwrap(); 213 | } 214 | 215 | #[test] 216 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 217 | fn test_mutex_arc_access_in_unwind() { 218 | let arc = Arc::new(Mutex::new(1)); 219 | let arc2 = arc.clone(); 220 | let _ = thread::spawn(move || -> () { 221 | struct Unwinder { 222 | i: Arc>, 223 | } 224 | impl Drop for Unwinder { 225 | fn drop(&mut self) { 226 | *self.i.lock().unwrap() += 1; 227 | } 228 | } 229 | let _u = Unwinder { i: arc2 }; 230 | panic!(); 231 | }) 232 | .join(); 233 | let lock = arc.lock().unwrap(); 234 | assert_eq!(*lock, 2); 235 | } 236 | 237 | #[test] 238 | fn test_mutex_unsized() { 239 | let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); 240 | { 241 | let b = &mut *mutex.lock().unwrap(); 242 | b[0] = 4; 243 | b[2] = 5; 244 | } 245 | let comp: &[i32] = &[4, 2, 5]; 246 | assert_eq!(&*mutex.lock().unwrap(), comp); 247 | } 248 | -------------------------------------------------------------------------------- /tests/stdtests/sync_once.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/once/tests.rs at revision 3 | //! f42e96149dd03e816b8bc3c329e7b9a5d12fcdab. 4 | 5 | use std::panic; 6 | use std::sync::mpsc::channel; 7 | use std::sync::Once; 8 | use std::thread; 9 | 10 | #[test] 11 | fn smoke_once() { 12 | static O: Once = Once::new(); 13 | let mut a = 0; 14 | O.call_once(|| a += 1); 15 | assert_eq!(a, 1); 16 | O.call_once(|| a += 1); 17 | assert_eq!(a, 1); 18 | } 19 | 20 | #[test] 21 | fn stampede_once() { 22 | static O: Once = Once::new(); 23 | static mut RUN: bool = false; 24 | 25 | let (tx, rx) = channel(); 26 | for _ in 0..10 { 27 | let tx = tx.clone(); 28 | thread::spawn(move || { 29 | for _ in 0..4 { 30 | thread::yield_now() 31 | } 32 | unsafe { 33 | O.call_once(|| { 34 | assert!(!RUN); 35 | RUN = true; 36 | }); 37 | assert!(RUN); 38 | } 39 | tx.send(()).unwrap(); 40 | }); 41 | } 42 | 43 | unsafe { 44 | O.call_once(|| { 45 | assert!(!RUN); 46 | RUN = true; 47 | }); 48 | assert!(RUN); 49 | } 50 | 51 | for _ in 0..10 { 52 | rx.recv().unwrap(); 53 | } 54 | } 55 | 56 | #[test] 57 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 58 | fn poison_bad() { 59 | static O: Once = Once::new(); 60 | 61 | // poison the once 62 | let t = panic::catch_unwind(|| { 63 | O.call_once(|| panic!()); 64 | }); 65 | assert!(t.is_err()); 66 | 67 | // poisoning propagates 68 | let t = panic::catch_unwind(|| { 69 | O.call_once(|| {}); 70 | }); 71 | assert!(t.is_err()); 72 | 73 | // we can subvert poisoning, however 74 | let mut called = false; 75 | O.call_once_force(|p| { 76 | called = true; 77 | assert!(p.is_poisoned()) 78 | }); 79 | assert!(called); 80 | 81 | // once any success happens, we stop propagating the poison 82 | O.call_once(|| {}); 83 | } 84 | 85 | #[test] 86 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 87 | fn wait_for_force_to_finish() { 88 | static O: Once = Once::new(); 89 | 90 | // poison the once 91 | let t = panic::catch_unwind(|| { 92 | O.call_once(|| panic!()); 93 | }); 94 | assert!(t.is_err()); 95 | 96 | // make sure someone's waiting inside the once via a force 97 | let (tx1, rx1) = channel(); 98 | let (tx2, rx2) = channel(); 99 | let t1 = thread::spawn(move || { 100 | O.call_once_force(|p| { 101 | assert!(p.is_poisoned()); 102 | tx1.send(()).unwrap(); 103 | rx2.recv().unwrap(); 104 | }); 105 | }); 106 | 107 | rx1.recv().unwrap(); 108 | 109 | // put another waiter on the once 110 | let t2 = thread::spawn(|| { 111 | let mut called = false; 112 | O.call_once(|| { 113 | called = true; 114 | }); 115 | assert!(!called); 116 | }); 117 | 118 | tx2.send(()).unwrap(); 119 | 120 | assert!(t1.join().is_ok()); 121 | assert!(t2.join().is_ok()); 122 | } 123 | -------------------------------------------------------------------------------- /tests/stdtests/sync_once_lock.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/once_lock/tests.rs at revision 3 | //! c1a2db3372a4d6896744919284f3287650a38ab7. 4 | 5 | use std::{ 6 | panic, 7 | sync::OnceLock, 8 | sync::{ 9 | atomic::{AtomicUsize, Ordering::SeqCst}, 10 | mpsc::channel, 11 | }, 12 | thread, 13 | }; 14 | 15 | fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { 16 | thread::spawn(f).join().unwrap() 17 | } 18 | 19 | #[test] 20 | #[cfg_attr(target_os = "emscripten", ignore)] 21 | fn sync_once_cell() { 22 | static ONCE_CELL: OnceLock = OnceLock::new(); 23 | 24 | assert!(ONCE_CELL.get().is_none()); 25 | 26 | spawn_and_wait(|| { 27 | ONCE_CELL.get_or_init(|| 92); 28 | assert_eq!(ONCE_CELL.get(), Some(&92)); 29 | }); 30 | 31 | ONCE_CELL.get_or_init(|| panic!("Kabom!")); 32 | assert_eq!(ONCE_CELL.get(), Some(&92)); 33 | } 34 | 35 | #[test] 36 | fn sync_once_cell_get_mut() { 37 | let mut c = OnceLock::new(); 38 | assert!(c.get_mut().is_none()); 39 | c.set(90).unwrap(); 40 | *c.get_mut().unwrap() += 2; 41 | assert_eq!(c.get_mut(), Some(&mut 92)); 42 | } 43 | 44 | #[test] 45 | fn sync_once_cell_get_unchecked() { 46 | let c = OnceLock::new(); 47 | c.set(92).unwrap(); 48 | //unsafe { 49 | // `get_unchecked` is not public 50 | assert_eq!(c.get().unwrap(), &92); 51 | //} 52 | } 53 | 54 | #[test] 55 | #[cfg_attr(target_os = "emscripten", ignore)] 56 | fn sync_once_cell_drop() { 57 | static DROP_CNT: AtomicUsize = AtomicUsize::new(0); 58 | struct Dropper; 59 | impl Drop for Dropper { 60 | fn drop(&mut self) { 61 | DROP_CNT.fetch_add(1, SeqCst); 62 | } 63 | } 64 | 65 | let x = OnceLock::new(); 66 | spawn_and_wait(move || { 67 | x.get_or_init(|| Dropper); 68 | assert_eq!(DROP_CNT.load(SeqCst), 0); 69 | drop(x); 70 | }); 71 | 72 | assert_eq!(DROP_CNT.load(SeqCst), 1); 73 | } 74 | 75 | #[test] 76 | fn sync_once_cell_drop_empty() { 77 | let x = OnceLock::::new(); 78 | drop(x); 79 | } 80 | 81 | #[test] 82 | fn clone() { 83 | let s = OnceLock::new(); 84 | let c = s.clone(); 85 | assert!(c.get().is_none()); 86 | 87 | s.set("hello".to_string()).unwrap(); 88 | let c = s.clone(); 89 | assert_eq!(c.get().map(String::as_str), Some("hello")); 90 | } 91 | 92 | #[test] 93 | fn get_or_try_init() { 94 | let cell: OnceLock = OnceLock::new(); 95 | assert!(cell.get().is_none()); 96 | 97 | let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() })); 98 | assert!(res.is_err()); 99 | // `is_initialized` is not public 100 | assert!(!cell.get().is_some()); 101 | assert!(cell.get().is_none()); 102 | 103 | assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); 104 | 105 | assert_eq!( 106 | cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())), 107 | Ok(&"hello".to_string()) 108 | ); 109 | assert_eq!(cell.get(), Some(&"hello".to_string())); 110 | } 111 | 112 | #[test] 113 | fn from_impl() { 114 | assert_eq!(OnceLock::from("value").get(), Some(&"value")); 115 | assert_ne!(OnceLock::from("foo").get(), Some(&"bar")); 116 | } 117 | 118 | #[test] 119 | fn partialeq_impl() { 120 | assert!(OnceLock::from("value") == OnceLock::from("value")); 121 | assert!(OnceLock::from("foo") != OnceLock::from("bar")); 122 | 123 | assert!(OnceLock::::new() == OnceLock::new()); 124 | assert!(OnceLock::::new() != OnceLock::from("value".to_owned())); 125 | } 126 | 127 | #[test] 128 | fn into_inner() { 129 | let cell: OnceLock = OnceLock::new(); 130 | assert_eq!(cell.into_inner(), None); 131 | let cell = OnceLock::new(); 132 | cell.set("hello".to_string()).unwrap(); 133 | assert_eq!(cell.into_inner(), Some("hello".to_string())); 134 | } 135 | 136 | #[test] 137 | fn is_sync_send() { 138 | fn assert_traits() {} 139 | assert_traits::>(); 140 | } 141 | 142 | #[test] 143 | fn eval_once_macro() { 144 | macro_rules! eval_once { 145 | (|| -> $ty:ty { 146 | $($body:tt)* 147 | }) => {{ 148 | static ONCE_CELL: OnceLock<$ty> = OnceLock::new(); 149 | fn init() -> $ty { 150 | $($body)* 151 | } 152 | ONCE_CELL.get_or_init(init) 153 | }}; 154 | } 155 | 156 | let fib: &'static Vec = eval_once! { 157 | || -> Vec { 158 | let mut res = vec![1, 1]; 159 | for i in 0..10 { 160 | let next = res[i] + res[i + 1]; 161 | res.push(next); 162 | } 163 | res 164 | } 165 | }; 166 | assert_eq!(fib[5], 8) 167 | } 168 | 169 | #[test] 170 | #[cfg_attr(target_os = "emscripten", ignore)] 171 | fn sync_once_cell_does_not_leak_partially_constructed_boxes() { 172 | static ONCE_CELL: OnceLock = OnceLock::new(); 173 | 174 | let n_readers = 10; 175 | let n_writers = 3; 176 | const MSG: &str = "Hello, World"; 177 | 178 | let (tx, rx) = channel(); 179 | 180 | for _ in 0..n_readers { 181 | let tx = tx.clone(); 182 | thread::spawn(move || loop { 183 | if let Some(msg) = ONCE_CELL.get() { 184 | tx.send(msg).unwrap(); 185 | break; 186 | } 187 | #[cfg(target_env = "sgx")] 188 | std::thread::yield_now(); 189 | }); 190 | } 191 | for _ in 0..n_writers { 192 | thread::spawn(move || { 193 | let _ = ONCE_CELL.set(MSG.to_owned()); 194 | }); 195 | } 196 | 197 | for _ in 0..n_readers { 198 | let msg = rx.recv().unwrap(); 199 | assert_eq!(msg, MSG); 200 | } 201 | } 202 | 203 | #[test] 204 | fn dropck() { 205 | let cell = OnceLock::new(); 206 | { 207 | let s = String::new(); 208 | cell.set(&s).unwrap(); 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /tests/stdtests/sync_rwlock.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sync/rwlock/tests.rs at revision 3 | //! 72a25d05bf1a4b155d74139ef700ff93af6d8e22. 4 | 5 | use rand::{self, Rng}; 6 | use std::sync::atomic::{AtomicUsize, Ordering}; 7 | use std::sync::mpsc::channel; 8 | use std::sync::{Arc, RwLock, TryLockError}; 9 | use std::thread; 10 | 11 | #[derive(Eq, PartialEq, Debug)] 12 | struct NonCopy(i32); 13 | 14 | #[test] 15 | fn smoke() { 16 | let l = RwLock::new(()); 17 | drop(l.read().unwrap()); 18 | drop(l.write().unwrap()); 19 | drop((l.read().unwrap(), l.read().unwrap())); 20 | drop(l.write().unwrap()); 21 | } 22 | 23 | #[test] 24 | fn frob() { 25 | const N: u32 = 10; 26 | const M: usize = 1000; 27 | 28 | let r = Arc::new(RwLock::new(())); 29 | 30 | let (tx, rx) = channel::<()>(); 31 | for _ in 0..N { 32 | let tx = tx.clone(); 33 | let r = r.clone(); 34 | thread::spawn(move || { 35 | let mut rng = rand::rng(); 36 | for _ in 0..M { 37 | if rng.random_bool(1.0 / (N as f64)) { 38 | drop(r.write().unwrap()); 39 | } else { 40 | drop(r.read().unwrap()); 41 | } 42 | } 43 | drop(tx); 44 | }); 45 | } 46 | drop(tx); 47 | let _ = rx.recv(); 48 | } 49 | 50 | #[test] 51 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 52 | fn test_rw_arc_poison_wr() { 53 | let arc = Arc::new(RwLock::new(1)); 54 | let arc2 = arc.clone(); 55 | let _: Result<(), _> = thread::spawn(move || { 56 | let _lock = arc2.write().unwrap(); 57 | panic!(); 58 | }) 59 | .join(); 60 | assert!(arc.read().is_err()); 61 | } 62 | 63 | #[test] 64 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 65 | fn test_rw_arc_poison_ww() { 66 | let arc = Arc::new(RwLock::new(1)); 67 | assert!(!arc.is_poisoned()); 68 | let arc2 = arc.clone(); 69 | let _: Result<(), _> = thread::spawn(move || { 70 | let _lock = arc2.write().unwrap(); 71 | panic!(); 72 | }) 73 | .join(); 74 | assert!(arc.write().is_err()); 75 | assert!(arc.is_poisoned()); 76 | } 77 | 78 | #[test] 79 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 80 | fn test_rw_arc_no_poison_rr() { 81 | let arc = Arc::new(RwLock::new(1)); 82 | let arc2 = arc.clone(); 83 | let _: Result<(), _> = thread::spawn(move || { 84 | let _lock = arc2.read().unwrap(); 85 | panic!(); 86 | }) 87 | .join(); 88 | let lock = arc.read().unwrap(); 89 | assert_eq!(*lock, 1); 90 | } 91 | #[test] 92 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 93 | fn test_rw_arc_no_poison_rw() { 94 | let arc = Arc::new(RwLock::new(1)); 95 | let arc2 = arc.clone(); 96 | let _: Result<(), _> = thread::spawn(move || { 97 | let _lock = arc2.read().unwrap(); 98 | panic!() 99 | }) 100 | .join(); 101 | let lock = arc.write().unwrap(); 102 | assert_eq!(*lock, 1); 103 | } 104 | 105 | #[test] 106 | fn test_rw_arc() { 107 | let arc = Arc::new(RwLock::new(0)); 108 | let arc2 = arc.clone(); 109 | let (tx, rx) = channel(); 110 | 111 | thread::spawn(move || { 112 | let mut lock = arc2.write().unwrap(); 113 | for _ in 0..10 { 114 | let tmp = *lock; 115 | *lock = -1; 116 | thread::yield_now(); 117 | *lock = tmp + 1; 118 | } 119 | tx.send(()).unwrap(); 120 | }); 121 | 122 | // Readers try to catch the writer in the act 123 | let mut children = Vec::new(); 124 | for _ in 0..5 { 125 | let arc3 = arc.clone(); 126 | children.push(thread::spawn(move || { 127 | let lock = arc3.read().unwrap(); 128 | assert!(*lock >= 0); 129 | })); 130 | } 131 | 132 | // Wait for children to pass their asserts 133 | for r in children { 134 | assert!(r.join().is_ok()); 135 | } 136 | 137 | // Wait for writer to finish 138 | rx.recv().unwrap(); 139 | let lock = arc.read().unwrap(); 140 | assert_eq!(*lock, 10); 141 | } 142 | 143 | #[test] 144 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 145 | fn test_rw_arc_access_in_unwind() { 146 | let arc = Arc::new(RwLock::new(1)); 147 | let arc2 = arc.clone(); 148 | let _ = thread::spawn(move || -> () { 149 | struct Unwinder { 150 | i: Arc>, 151 | } 152 | impl Drop for Unwinder { 153 | fn drop(&mut self) { 154 | let mut lock = self.i.write().unwrap(); 155 | *lock += 1; 156 | } 157 | } 158 | let _u = Unwinder { i: arc2 }; 159 | panic!(); 160 | }) 161 | .join(); 162 | let lock = arc.read().unwrap(); 163 | assert_eq!(*lock, 2); 164 | } 165 | 166 | #[test] 167 | fn test_rwlock_unsized() { 168 | let rw: &RwLock<[i32]> = &RwLock::new([1, 2, 3]); 169 | { 170 | let b = &mut *rw.write().unwrap(); 171 | b[0] = 4; 172 | b[2] = 5; 173 | } 174 | let comp: &[i32] = &[4, 2, 5]; 175 | assert_eq!(&*rw.read().unwrap(), comp); 176 | } 177 | 178 | #[test] 179 | fn test_rwlock_try_write() { 180 | let lock = RwLock::new(0isize); 181 | let read_guard = lock.read().unwrap(); 182 | 183 | let write_result = lock.try_write(); 184 | match write_result { 185 | Err(TryLockError::WouldBlock) => (), 186 | Ok(_) => assert!( 187 | false, 188 | "try_write should not succeed while read_guard is in scope" 189 | ), 190 | Err(_) => assert!(false, "unexpected error"), 191 | } 192 | 193 | drop(read_guard); 194 | } 195 | 196 | #[test] 197 | fn test_into_inner() { 198 | let m = RwLock::new(NonCopy(10)); 199 | assert_eq!(m.into_inner().unwrap(), NonCopy(10)); 200 | } 201 | 202 | #[test] 203 | fn test_into_inner_drop() { 204 | struct Foo(Arc); 205 | impl Drop for Foo { 206 | fn drop(&mut self) { 207 | self.0.fetch_add(1, Ordering::SeqCst); 208 | } 209 | } 210 | let num_drops = Arc::new(AtomicUsize::new(0)); 211 | let m = RwLock::new(Foo(num_drops.clone())); 212 | assert_eq!(num_drops.load(Ordering::SeqCst), 0); 213 | { 214 | let _inner = m.into_inner().unwrap(); 215 | assert_eq!(num_drops.load(Ordering::SeqCst), 0); 216 | } 217 | assert_eq!(num_drops.load(Ordering::SeqCst), 1); 218 | } 219 | 220 | #[test] 221 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 222 | fn test_into_inner_poison() { 223 | let m = Arc::new(RwLock::new(NonCopy(10))); 224 | let m2 = m.clone(); 225 | let _ = thread::spawn(move || { 226 | let _lock = m2.write().unwrap(); 227 | panic!("test panic in inner thread to poison RwLock"); 228 | }) 229 | .join(); 230 | 231 | assert!(m.is_poisoned()); 232 | match Arc::try_unwrap(m).unwrap().into_inner() { 233 | Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), 234 | Ok(x) => panic!("into_inner of poisoned RwLock is Ok: {x:?}"), 235 | } 236 | } 237 | 238 | #[test] 239 | fn test_get_mut() { 240 | let mut m = RwLock::new(NonCopy(10)); 241 | *m.get_mut().unwrap() = NonCopy(20); 242 | assert_eq!(m.into_inner().unwrap(), NonCopy(20)); 243 | } 244 | 245 | #[test] 246 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 247 | fn test_get_mut_poison() { 248 | let m = Arc::new(RwLock::new(NonCopy(10))); 249 | let m2 = m.clone(); 250 | let _ = thread::spawn(move || { 251 | let _lock = m2.write().unwrap(); 252 | panic!("test panic in inner thread to poison RwLock"); 253 | }) 254 | .join(); 255 | 256 | assert!(m.is_poisoned()); 257 | match Arc::try_unwrap(m).unwrap().get_mut() { 258 | Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), 259 | Ok(x) => panic!("get_mut of poisoned RwLock is Ok: {x:?}"), 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /tests/stdtests/sys_common/io.rs: -------------------------------------------------------------------------------- 1 | // The following is derived from Rust's 2 | // src/tools/cargo/crates/cargo-test-support/src/lib.rs at revision 3 | // 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | // Bare metal platforms usually have very small amounts of RAM 6 | // (in the order of hundreds of KB) 7 | pub const DEFAULT_BUF_SIZE: usize = if cfg!(target_os = "espidf") { 8 | 512 9 | } else { 10 | 8 * 1024 11 | }; 12 | 13 | #[allow(dead_code)] // not used on emscripten 14 | pub mod test { 15 | use rand::RngCore; 16 | use std::env; 17 | use std::fs; 18 | use std::path::{Path, PathBuf}; 19 | 20 | pub struct TempDir(PathBuf); 21 | 22 | impl TempDir { 23 | pub fn join(&self, path: &str) -> PathBuf { 24 | let TempDir(ref p) = *self; 25 | p.join(path) 26 | } 27 | 28 | pub fn path(&self) -> &Path { 29 | let TempDir(ref p) = *self; 30 | p 31 | } 32 | } 33 | 34 | impl Drop for TempDir { 35 | fn drop(&mut self) { 36 | // Gee, seeing how we're testing the fs module I sure hope that we 37 | // at least implement this correctly! 38 | let TempDir(ref p) = *self; 39 | fs::remove_dir_all(p).unwrap(); 40 | } 41 | } 42 | 43 | pub fn tmpdir() -> TempDir { 44 | let p = env::temp_dir(); 45 | let mut r = rand::rng(); 46 | let ret = p.join(&format!("rust-{}", r.next_u32())); 47 | fs::create_dir(&ret).unwrap(); 48 | TempDir(ret) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /tests/stdtests/sys_common/mod.rs: -------------------------------------------------------------------------------- 1 | #[allow(dead_code)] 2 | pub(crate) mod io; 3 | -------------------------------------------------------------------------------- /tests/stdtests/thread.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/thread/tests.rs at revision 3 | //! eb14dd863a0d8af603c6783b10efff8454944c15. 4 | 5 | use std::any::Any; 6 | use std::mem; 7 | use std::panic::panic_any; 8 | use std::result; 9 | use std::sync::{ 10 | atomic::{AtomicBool, Ordering}, 11 | mpsc::{channel, Sender}, 12 | Arc, Barrier, 13 | }; 14 | use std::thread::Builder; 15 | use std::thread::{self, Scope, ThreadId}; 16 | use std::time::Duration; 17 | use std::time::Instant; 18 | 19 | // !!! These tests are dangerous. If something is buggy, they will hang, !!! 20 | // !!! instead of exiting cleanly. This might wedge the buildbots. !!! 21 | 22 | #[test] 23 | fn test_unnamed_thread() { 24 | thread::spawn(move || { 25 | assert!(thread::current().name().is_none()); 26 | }) 27 | .join() 28 | .ok() 29 | .expect("thread panicked"); 30 | } 31 | 32 | #[test] 33 | fn test_named_thread() { 34 | Builder::new() 35 | .name("ada lovelace".to_string()) 36 | .spawn(move || { 37 | assert!(thread::current().name().unwrap() == "ada lovelace".to_string()); 38 | }) 39 | .unwrap() 40 | .join() 41 | .unwrap(); 42 | } 43 | 44 | #[test] 45 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 46 | #[should_panic] 47 | fn test_invalid_named_thread() { 48 | let _ = Builder::new() 49 | .name("ada l\0velace".to_string()) 50 | .spawn(|| {}); 51 | } 52 | 53 | #[test] 54 | fn test_run_basic() { 55 | let (tx, rx) = channel(); 56 | thread::spawn(move || { 57 | tx.send(()).unwrap(); 58 | }); 59 | rx.recv().unwrap(); 60 | } 61 | 62 | #[test] 63 | fn test_is_finished() { 64 | let b = Arc::new(Barrier::new(2)); 65 | let t = thread::spawn({ 66 | let b = b.clone(); 67 | move || { 68 | b.wait(); 69 | 1234 70 | } 71 | }); 72 | 73 | // Thread is definitely running here, since it's still waiting for the barrier. 74 | assert_eq!(t.is_finished(), false); 75 | 76 | // Unblock the barrier. 77 | b.wait(); 78 | 79 | // Now check that t.is_finished() becomes true within a reasonable time. 80 | let start = Instant::now(); 81 | while !t.is_finished() { 82 | assert!(start.elapsed() < Duration::from_secs(2)); 83 | thread::sleep(Duration::from_millis(15)); 84 | } 85 | 86 | // Joining the thread should not block for a significant time now. 87 | let join_time = Instant::now(); 88 | assert_eq!(t.join().unwrap(), 1234); 89 | assert!(join_time.elapsed() < Duration::from_secs(2)); 90 | } 91 | 92 | #[test] 93 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 94 | fn test_join_panic() { 95 | match thread::spawn(move || panic!()).join() { 96 | result::Result::Err(_) => (), 97 | result::Result::Ok(()) => panic!(), 98 | } 99 | } 100 | 101 | #[test] 102 | fn test_spawn_sched() { 103 | let (tx, rx) = channel(); 104 | 105 | fn f(i: i32, tx: Sender<()>) { 106 | let tx = tx.clone(); 107 | thread::spawn(move || { 108 | if i == 0 { 109 | tx.send(()).unwrap(); 110 | } else { 111 | f(i - 1, tx); 112 | } 113 | }); 114 | } 115 | f(10, tx); 116 | rx.recv().unwrap(); 117 | } 118 | 119 | #[test] 120 | fn test_spawn_sched_childs_on_default_sched() { 121 | let (tx, rx) = channel(); 122 | 123 | thread::spawn(move || { 124 | thread::spawn(move || { 125 | tx.send(()).unwrap(); 126 | }); 127 | }); 128 | 129 | rx.recv().unwrap(); 130 | } 131 | 132 | fn avoid_copying_the_body(spawnfn: F) 133 | where 134 | F: FnOnce(Box), 135 | { 136 | let (tx, rx) = channel(); 137 | 138 | let x: Box<_> = Box::new(1); 139 | let x_in_parent = (&*x) as *const i32 as usize; 140 | 141 | spawnfn(Box::new(move || { 142 | let x_in_child = (&*x) as *const i32 as usize; 143 | tx.send(x_in_child).unwrap(); 144 | })); 145 | 146 | let x_in_child = rx.recv().unwrap(); 147 | assert_eq!(x_in_parent, x_in_child); 148 | } 149 | 150 | #[test] 151 | fn test_avoid_copying_the_body_spawn() { 152 | avoid_copying_the_body(|v| { 153 | thread::spawn(move || v()); 154 | }); 155 | } 156 | 157 | #[test] 158 | fn test_avoid_copying_the_body_thread_spawn() { 159 | avoid_copying_the_body(|f| { 160 | thread::spawn(move || { 161 | f(); 162 | }); 163 | }) 164 | } 165 | 166 | #[test] 167 | fn test_avoid_copying_the_body_join() { 168 | avoid_copying_the_body(|f| { 169 | let _ = thread::spawn(move || f()).join(); 170 | }) 171 | } 172 | 173 | #[test] 174 | fn test_child_doesnt_ref_parent() { 175 | // If the child refcounts the parent thread, this will stack overflow when 176 | // climbing the thread tree to dereference each ancestor. (See #1789) 177 | // (well, it would if the constant were 8000+ - I lowered it to be more 178 | // valgrind-friendly. try this at home, instead..!) 179 | const GENERATIONS: u32 = 16; 180 | fn child_no(x: u32) -> Box { 181 | return Box::new(move || { 182 | if x < GENERATIONS { 183 | thread::spawn(move || child_no(x + 1)()); 184 | } 185 | }); 186 | } 187 | thread::spawn(|| child_no(0)()); 188 | } 189 | 190 | #[test] 191 | fn test_simple_newsched_spawn() { 192 | thread::spawn(move || {}); 193 | } 194 | 195 | #[test] 196 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 197 | fn test_try_panic_message_string_literal() { 198 | match thread::spawn(move || { 199 | panic!("static string"); 200 | }) 201 | .join() 202 | { 203 | Err(e) => { 204 | type T = &'static str; 205 | assert!(e.is::()); 206 | assert_eq!(*e.downcast::().unwrap(), "static string"); 207 | } 208 | Ok(()) => panic!(), 209 | } 210 | } 211 | 212 | #[test] 213 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 214 | fn test_try_panic_any_message_owned_str() { 215 | match thread::spawn(move || { 216 | panic_any("owned string".to_string()); 217 | }) 218 | .join() 219 | { 220 | Err(e) => { 221 | type T = String; 222 | assert!(e.is::()); 223 | assert_eq!(*e.downcast::().unwrap(), "owned string".to_string()); 224 | } 225 | Ok(()) => panic!(), 226 | } 227 | } 228 | 229 | #[test] 230 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 231 | fn test_try_panic_any_message_any() { 232 | match thread::spawn(move || { 233 | panic_any(Box::new(413u16) as Box); 234 | }) 235 | .join() 236 | { 237 | Err(e) => { 238 | type T = Box; 239 | assert!(e.is::()); 240 | let any = e.downcast::().unwrap(); 241 | assert!(any.is::()); 242 | assert_eq!(*any.downcast::().unwrap(), 413); 243 | } 244 | Ok(()) => panic!(), 245 | } 246 | } 247 | 248 | #[test] 249 | #[cfg_attr(all(target_arch = "arm", not(feature = "unwinding")), ignore)] 250 | fn test_try_panic_any_message_unit_struct() { 251 | struct Juju; 252 | 253 | match thread::spawn(move || panic_any(Juju)).join() { 254 | Err(ref e) if e.is::() => {} 255 | Err(_) | Ok(()) => panic!(), 256 | } 257 | } 258 | 259 | #[test] 260 | fn test_park_timeout_unpark_before() { 261 | for _ in 0..10 { 262 | thread::current().unpark(); 263 | thread::park_timeout(Duration::from_millis(u32::MAX as u64)); 264 | } 265 | } 266 | 267 | #[test] 268 | fn test_park_timeout_unpark_not_called() { 269 | for _ in 0..10 { 270 | thread::park_timeout(Duration::from_millis(10)); 271 | } 272 | } 273 | 274 | #[test] 275 | fn test_park_timeout_unpark_called_other_thread() { 276 | for _ in 0..10 { 277 | let th = thread::current(); 278 | 279 | let _guard = thread::spawn(move || { 280 | std::thread::sleep(Duration::from_millis(50)); 281 | th.unpark(); 282 | }); 283 | 284 | thread::park_timeout(Duration::from_millis(u32::MAX as u64)); 285 | } 286 | } 287 | 288 | #[test] 289 | fn sleep_ms_smoke() { 290 | thread::sleep(Duration::from_millis(2)); 291 | } 292 | 293 | #[test] 294 | fn test_size_of_option_thread_id() { 295 | assert_eq!( 296 | mem::size_of::>(), 297 | mem::size_of::() 298 | ); 299 | } 300 | 301 | #[test] 302 | fn test_thread_id_equal() { 303 | assert!(thread::current().id() == thread::current().id()); 304 | } 305 | 306 | #[test] 307 | fn test_thread_id_not_equal() { 308 | let spawned_id = thread::spawn(|| thread::current().id()).join().unwrap(); 309 | assert!(thread::current().id() != spawned_id); 310 | } 311 | 312 | #[test] 313 | fn test_scoped_threads_drop_result_before_join() { 314 | let actually_finished = &AtomicBool::new(false); 315 | struct X<'scope, 'env>(&'scope Scope<'scope, 'env>, &'env AtomicBool); 316 | impl Drop for X<'_, '_> { 317 | fn drop(&mut self) { 318 | thread::sleep(Duration::from_millis(20)); 319 | let actually_finished = self.1; 320 | self.0.spawn(move || { 321 | thread::sleep(Duration::from_millis(20)); 322 | actually_finished.store(true, Ordering::Relaxed); 323 | }); 324 | } 325 | } 326 | thread::scope(|s| { 327 | s.spawn(move || { 328 | thread::sleep(Duration::from_millis(20)); 329 | X(s, actually_finished) 330 | }); 331 | }); 332 | assert!(actually_finished.load(Ordering::Relaxed)); 333 | } 334 | 335 | #[test] 336 | fn test_scoped_threads_nll() { 337 | // this is mostly a *compilation test* for this exact function: 338 | fn foo(x: &u8) { 339 | thread::scope(|s| { 340 | s.spawn(|| match x { 341 | _ => (), 342 | }); 343 | }); 344 | } 345 | // let's also run it for good measure 346 | let x = 42_u8; 347 | foo(&x); 348 | } 349 | -------------------------------------------------------------------------------- /tests/stdtests/thread_local.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/thread/local/tests.rs at revision 3 | //! 497ee321af3b8496eaccd7af7b437f18bab81abf. 4 | 5 | use std::cell::{Cell, UnsafeCell}; 6 | use std::sync::atomic::{AtomicU8, Ordering}; 7 | use std::sync::mpsc::{channel, Sender}; 8 | use std::thread::{self, LocalKey}; 9 | use std::thread_local; 10 | 11 | struct Foo(Sender<()>); 12 | 13 | impl Drop for Foo { 14 | fn drop(&mut self) { 15 | let Foo(ref s) = *self; 16 | s.send(()).unwrap(); 17 | } 18 | } 19 | 20 | #[test] 21 | fn smoke_no_dtor() { 22 | thread_local!(static FOO: Cell = Cell::new(1)); 23 | run(&FOO); 24 | thread_local!(static FOO2: Cell = const { Cell::new(1) }); 25 | run(&FOO2); 26 | 27 | fn run(key: &'static LocalKey>) { 28 | key.with(|f| { 29 | assert_eq!(f.get(), 1); 30 | f.set(2); 31 | }); 32 | let t = thread::spawn(move || { 33 | key.with(|f| { 34 | assert_eq!(f.get(), 1); 35 | }); 36 | }); 37 | t.join().unwrap(); 38 | 39 | key.with(|f| { 40 | assert_eq!(f.get(), 2); 41 | }); 42 | } 43 | } 44 | 45 | #[test] 46 | fn states() { 47 | struct Foo(&'static LocalKey); 48 | impl Drop for Foo { 49 | fn drop(&mut self) { 50 | assert!(self.0.try_with(|_| ()).is_err()); 51 | } 52 | } 53 | 54 | thread_local!(static FOO: Foo = Foo(&FOO)); 55 | run(&FOO); 56 | thread_local!(static FOO2: Foo = const { Foo(&FOO2) }); 57 | run(&FOO2); 58 | 59 | fn run(foo: &'static LocalKey) { 60 | thread::spawn(move || { 61 | assert!(foo.try_with(|_| ()).is_ok()); 62 | }) 63 | .join() 64 | .unwrap(); 65 | } 66 | } 67 | 68 | #[test] 69 | fn smoke_dtor() { 70 | thread_local!(static FOO: UnsafeCell> = UnsafeCell::new(None)); 71 | run(&FOO); 72 | thread_local!(static FOO2: UnsafeCell> = const { UnsafeCell::new(None) }); 73 | run(&FOO2); 74 | 75 | fn run(key: &'static LocalKey>>) { 76 | let (tx, rx) = channel(); 77 | let t = thread::spawn(move || unsafe { 78 | let mut tx = Some(tx); 79 | key.with(|f| { 80 | *f.get() = Some(Foo(tx.take().unwrap())); 81 | }); 82 | }); 83 | rx.recv().unwrap(); 84 | t.join().unwrap(); 85 | } 86 | } 87 | 88 | #[test] 89 | fn circular() { 90 | struct S1( 91 | &'static LocalKey>>, 92 | &'static LocalKey>>, 93 | ); 94 | struct S2( 95 | &'static LocalKey>>, 96 | &'static LocalKey>>, 97 | ); 98 | thread_local!(static K1: UnsafeCell> = UnsafeCell::new(None)); 99 | thread_local!(static K2: UnsafeCell> = UnsafeCell::new(None)); 100 | thread_local!(static K3: UnsafeCell> = const { UnsafeCell::new(None) }); 101 | thread_local!(static K4: UnsafeCell> = const { UnsafeCell::new(None) }); 102 | static mut HITS: usize = 0; 103 | 104 | impl Drop for S1 { 105 | fn drop(&mut self) { 106 | unsafe { 107 | HITS += 1; 108 | if self.1.try_with(|_| ()).is_err() { 109 | assert_eq!(HITS, 3); 110 | } else { 111 | if HITS == 1 { 112 | self.1.with(|s| *s.get() = Some(S2(self.0, self.1))); 113 | } else { 114 | assert_eq!(HITS, 3); 115 | } 116 | } 117 | } 118 | } 119 | } 120 | impl Drop for S2 { 121 | fn drop(&mut self) { 122 | unsafe { 123 | HITS += 1; 124 | assert!(self.0.try_with(|_| ()).is_ok()); 125 | assert_eq!(HITS, 2); 126 | self.0.with(|s| *s.get() = Some(S1(self.0, self.1))); 127 | } 128 | } 129 | } 130 | 131 | thread::spawn(move || { 132 | drop(S1(&K1, &K2)); 133 | }) 134 | .join() 135 | .unwrap(); 136 | 137 | unsafe { 138 | HITS = 0; 139 | } 140 | 141 | thread::spawn(move || { 142 | drop(S1(&K3, &K4)); 143 | }) 144 | .join() 145 | .unwrap(); 146 | } 147 | 148 | #[test] 149 | fn self_referential() { 150 | struct S1(&'static LocalKey>>); 151 | 152 | thread_local!(static K1: UnsafeCell> = UnsafeCell::new(None)); 153 | thread_local!(static K2: UnsafeCell> = const { UnsafeCell::new(None) }); 154 | 155 | impl Drop for S1 { 156 | fn drop(&mut self) { 157 | assert!(self.0.try_with(|_| ()).is_err()); 158 | } 159 | } 160 | 161 | thread::spawn(move || unsafe { 162 | K1.with(|s| *s.get() = Some(S1(&K1))); 163 | }) 164 | .join() 165 | .unwrap(); 166 | 167 | thread::spawn(move || unsafe { 168 | K2.with(|s| *s.get() = Some(S1(&K2))); 169 | }) 170 | .join() 171 | .unwrap(); 172 | } 173 | 174 | // Note that this test will deadlock if TLS destructors aren't run (this 175 | // requires the destructor to be run to pass the test). 176 | #[test] 177 | fn dtors_in_dtors_in_dtors() { 178 | struct S1(Sender<()>); 179 | thread_local!(static K1: UnsafeCell> = UnsafeCell::new(None)); 180 | thread_local!(static K2: UnsafeCell> = UnsafeCell::new(None)); 181 | 182 | impl Drop for S1 { 183 | fn drop(&mut self) { 184 | let S1(ref tx) = *self; 185 | unsafe { 186 | let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone()))); 187 | } 188 | } 189 | } 190 | 191 | let (tx, rx) = channel(); 192 | let _t = thread::spawn(move || unsafe { 193 | let mut tx = Some(tx); 194 | K1.with(|s| *s.get() = Some(S1(tx.take().unwrap()))); 195 | }); 196 | rx.recv().unwrap(); 197 | } 198 | 199 | #[test] 200 | fn dtors_in_dtors_in_dtors_const_init() { 201 | struct S1(Sender<()>); 202 | thread_local!(static K1: UnsafeCell> = const { UnsafeCell::new(None) }); 203 | thread_local!(static K2: UnsafeCell> = const { UnsafeCell::new(None) }); 204 | 205 | impl Drop for S1 { 206 | fn drop(&mut self) { 207 | let S1(ref tx) = *self; 208 | unsafe { 209 | let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone()))); 210 | } 211 | } 212 | } 213 | 214 | let (tx, rx) = channel(); 215 | let _t = thread::spawn(move || unsafe { 216 | let mut tx = Some(tx); 217 | K1.with(|s| *s.get() = Some(S1(tx.take().unwrap()))); 218 | }); 219 | rx.recv().unwrap(); 220 | } 221 | 222 | // This test tests that TLS destructors have run before the thread joins. The 223 | // test has no false positives (meaning: if the test fails, there's actually 224 | // an ordering problem). It may have false negatives, where the test passes but 225 | // join is not guaranteed to be after the TLS destructors. However, false 226 | // negatives should be exceedingly rare due to judicious use of 227 | // thread::yield_now and running the test several times. 228 | #[test] 229 | fn join_orders_after_tls_destructors() { 230 | // We emulate a synchronous MPSC rendezvous channel using only atomics and 231 | // thread::yield_now. We can't use std::mpsc as the implementation itself 232 | // may rely on thread locals. 233 | // 234 | // The basic state machine for an SPSC rendezvous channel is: 235 | // FRESH -> THREAD1_WAITING -> MAIN_THREAD_RENDEZVOUS 236 | // where the first transition is done by the “receiving” thread and the 2nd 237 | // transition is done by the “sending” thread. 238 | // 239 | // We add an additional state `THREAD2_LAUNCHED` between `FRESH` and 240 | // `THREAD1_WAITING` to block until all threads are actually running. 241 | // 242 | // A thread that joins on the “receiving” thread completion should never 243 | // observe the channel in the `THREAD1_WAITING` state. If this does occur, 244 | // we switch to the “poison” state `THREAD2_JOINED` and panic all around. 245 | // (This is equivalent to “sending” from an alternate producer thread.) 246 | const FRESH: u8 = 0; 247 | const THREAD2_LAUNCHED: u8 = 1; 248 | const THREAD1_WAITING: u8 = 2; 249 | const MAIN_THREAD_RENDEZVOUS: u8 = 3; 250 | const THREAD2_JOINED: u8 = 4; 251 | static SYNC_STATE: AtomicU8 = AtomicU8::new(FRESH); 252 | 253 | for _ in 0..10 { 254 | SYNC_STATE.store(FRESH, Ordering::SeqCst); 255 | 256 | let jh = thread::Builder::new() 257 | .name("thread1".into()) 258 | .spawn(move || { 259 | struct TlDrop; 260 | 261 | impl Drop for TlDrop { 262 | fn drop(&mut self) { 263 | let mut sync_state = SYNC_STATE.swap(THREAD1_WAITING, Ordering::SeqCst); 264 | loop { 265 | match sync_state { 266 | THREAD2_LAUNCHED | THREAD1_WAITING => thread::yield_now(), 267 | MAIN_THREAD_RENDEZVOUS => break, 268 | THREAD2_JOINED => panic!( 269 | "Thread 1 still running after thread 2 joined on thread 1" 270 | ), 271 | v => unreachable!("sync state: {}", v), 272 | } 273 | sync_state = SYNC_STATE.load(Ordering::SeqCst); 274 | } 275 | } 276 | } 277 | 278 | thread_local! { 279 | static TL_DROP: TlDrop = TlDrop; 280 | } 281 | 282 | TL_DROP.with(|_| {}); 283 | 284 | loop { 285 | match SYNC_STATE.load(Ordering::SeqCst) { 286 | FRESH => thread::yield_now(), 287 | THREAD2_LAUNCHED => break, 288 | v => unreachable!("sync state: {}", v), 289 | } 290 | } 291 | }) 292 | .unwrap(); 293 | 294 | let jh2 = thread::Builder::new() 295 | .name("thread2".into()) 296 | .spawn(move || { 297 | assert_eq!(SYNC_STATE.swap(THREAD2_LAUNCHED, Ordering::SeqCst), FRESH); 298 | jh.join().unwrap(); 299 | match SYNC_STATE.swap(THREAD2_JOINED, Ordering::SeqCst) { 300 | MAIN_THREAD_RENDEZVOUS => return, 301 | THREAD2_LAUNCHED | THREAD1_WAITING => { 302 | panic!("Thread 2 running after thread 1 join before main thread rendezvous") 303 | } 304 | v => unreachable!("sync state: {:?}", v), 305 | } 306 | }) 307 | .unwrap(); 308 | 309 | loop { 310 | match SYNC_STATE.compare_exchange( 311 | THREAD1_WAITING, 312 | MAIN_THREAD_RENDEZVOUS, 313 | Ordering::SeqCst, 314 | Ordering::SeqCst, 315 | ) { 316 | Ok(_) => break, 317 | Err(FRESH) => thread::yield_now(), 318 | Err(THREAD2_LAUNCHED) => thread::yield_now(), 319 | Err(THREAD2_JOINED) => { 320 | panic!("Main thread rendezvous after thread 2 joined thread 1") 321 | } 322 | v => unreachable!("sync state: {:?}", v), 323 | } 324 | } 325 | jh2.join().unwrap(); 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /tests/stdtests/time.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/time/tests.rs at revision 3 | //! 72a25d05bf1a4b155d74139ef700ff93af6d8e22. 4 | 5 | #![allow(soft_unstable)] 6 | 7 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 8 | #[cfg(feature = "bench")] 9 | #[cfg(not(target_arch = "wasm32"))] 10 | use test::{black_box, Bencher}; 11 | 12 | macro_rules! assert_almost_eq { 13 | ($a:expr, $b:expr) => {{ 14 | let (a, b) = ($a, $b); 15 | if a != b { 16 | let (a, b) = if a > b { (a, b) } else { (b, a) }; 17 | assert!( 18 | a - Duration::from_micros(1) <= b, 19 | "{:?} is not almost equal to {:?}", 20 | a, 21 | b 22 | ); 23 | } 24 | }}; 25 | } 26 | 27 | #[test] 28 | fn instant_monotonic() { 29 | let a = Instant::now(); 30 | loop { 31 | let b = Instant::now(); 32 | assert!(b >= a); 33 | if b > a { 34 | break; 35 | } 36 | } 37 | } 38 | 39 | #[test] 40 | #[cfg(not(target_arch = "wasm32"))] 41 | #[cfg_attr(not(feature = "slow"), ignore)] 42 | fn instant_monotonic_concurrent() -> std::thread::Result<()> { 43 | let threads: Vec<_> = (0..8) 44 | .map(|_| { 45 | std::thread::spawn(|| { 46 | let mut old = Instant::now(); 47 | for _ in 0..5_000_000 { 48 | let new = Instant::now(); 49 | assert!(new >= old); 50 | old = new; 51 | } 52 | }) 53 | }) 54 | .collect(); 55 | for t in threads { 56 | t.join()?; 57 | } 58 | Ok(()) 59 | } 60 | 61 | #[test] 62 | fn instant_elapsed() { 63 | let a = Instant::now(); 64 | let _ = a.elapsed(); 65 | } 66 | 67 | #[test] 68 | fn instant_math() { 69 | let a = Instant::now(); 70 | let b = Instant::now(); 71 | //println!("a: {:?}", a); 72 | //println!("b: {:?}", b); 73 | let dur = b.duration_since(a); 74 | //println!("dur: {:?}", dur); 75 | assert_almost_eq!(b - dur, a); 76 | assert_almost_eq!(a + dur, b); 77 | 78 | let second = Duration::SECOND; 79 | assert_almost_eq!(a - second + second, a); 80 | assert_almost_eq!( 81 | a.checked_sub(second).unwrap().checked_add(second).unwrap(), 82 | a 83 | ); 84 | 85 | // checked_add_duration will not panic on overflow 86 | let mut maybe_t = Some(Instant::now()); 87 | let max_duration = Duration::from_secs(u64::MAX); 88 | // in case `Instant` can store `>= now + max_duration`. 89 | for _ in 0..2 { 90 | maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration)); 91 | } 92 | assert_eq!(maybe_t, None); 93 | 94 | // checked_add_duration calculates the right time and will work for another year 95 | let year = Duration::from_secs(60 * 60 * 24 * 365); 96 | assert_eq!(a + year, a.checked_add(year).unwrap()); 97 | } 98 | 99 | #[test] 100 | fn instant_math_is_associative() { 101 | let now = Instant::now(); 102 | let offset = Duration::from_millis(5); 103 | // Changing the order of instant math shouldn't change the results, 104 | // especially when the expression reduces to X + identity. 105 | assert_eq!((now + offset) - now, (now - now) + offset); 106 | } 107 | 108 | #[test] 109 | fn instant_duration_since_saturates() { 110 | let a = Instant::now(); 111 | assert_eq!((a - Duration::SECOND).duration_since(a), Duration::ZERO); 112 | } 113 | 114 | #[test] 115 | fn instant_checked_duration_since_nopanic() { 116 | let now = Instant::now(); 117 | let earlier = now - Duration::SECOND; 118 | let later = now + Duration::SECOND; 119 | assert_eq!(earlier.checked_duration_since(now), None); 120 | assert_eq!(later.checked_duration_since(now), Some(Duration::SECOND)); 121 | assert_eq!(now.checked_duration_since(now), Some(Duration::ZERO)); 122 | } 123 | 124 | #[test] 125 | fn instant_saturating_duration_since_nopanic() { 126 | let a = Instant::now(); 127 | #[allow(deprecated, deprecated_in_future)] 128 | let ret = (a - Duration::SECOND).saturating_duration_since(a); 129 | assert_eq!(ret, Duration::ZERO); 130 | } 131 | 132 | #[test] 133 | fn system_time_math() { 134 | let a = SystemTime::now(); 135 | let b = SystemTime::now(); 136 | match b.duration_since(a) { 137 | Ok(Duration::ZERO) => { 138 | assert_almost_eq!(a, b); 139 | } 140 | Ok(dur) => { 141 | assert!(b > a); 142 | assert_almost_eq!(b - dur, a); 143 | assert_almost_eq!(a + dur, b); 144 | } 145 | Err(dur) => { 146 | let dur = dur.duration(); 147 | assert!(a > b); 148 | assert_almost_eq!(b + dur, a); 149 | assert_almost_eq!(a - dur, b); 150 | } 151 | } 152 | 153 | let second = Duration::SECOND; 154 | assert_almost_eq!(a.duration_since(a - second).unwrap(), second); 155 | assert_almost_eq!(a.duration_since(a + second).unwrap_err().duration(), second); 156 | 157 | assert_almost_eq!(a - second + second, a); 158 | assert_almost_eq!( 159 | a.checked_sub(second).unwrap().checked_add(second).unwrap(), 160 | a 161 | ); 162 | 163 | let one_second_from_epoch = UNIX_EPOCH + Duration::SECOND; 164 | let one_second_from_epoch2 = 165 | UNIX_EPOCH + Duration::from_millis(500) + Duration::from_millis(500); 166 | assert_eq!(one_second_from_epoch, one_second_from_epoch2); 167 | 168 | // checked_add_duration will not panic on overflow 169 | let mut maybe_t = Some(SystemTime::UNIX_EPOCH); 170 | let max_duration = Duration::from_secs(u64::MAX); 171 | // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`. 172 | for _ in 0..2 { 173 | maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration)); 174 | } 175 | assert_eq!(maybe_t, None); 176 | 177 | // checked_add_duration calculates the right time and will work for another year 178 | let year = Duration::from_secs(60 * 60 * 24 * 365); 179 | assert_eq!(a + year, a.checked_add(year).unwrap()); 180 | } 181 | 182 | #[test] 183 | fn system_time_elapsed() { 184 | let a = SystemTime::now(); 185 | drop(a.elapsed()); 186 | } 187 | 188 | #[test] 189 | fn since_epoch() { 190 | let ts = SystemTime::now(); 191 | let a = ts.duration_since(UNIX_EPOCH + Duration::SECOND).unwrap(); 192 | let b = ts.duration_since(UNIX_EPOCH).unwrap(); 193 | assert!(b > a); 194 | assert_eq!(b - a, Duration::SECOND); 195 | 196 | let thirty_years = Duration::SECOND * 60 * 60 * 24 * 365 * 30; 197 | 198 | // Right now for CI this test is run in an emulator, and apparently the 199 | // aarch64 emulator's sense of time is that we're still living in the 200 | // 70s. This is also true for riscv (also qemu) 201 | // 202 | // Otherwise let's assume that we're all running computers later than 203 | // 2000. 204 | if !cfg!(target_arch = "aarch64") && !cfg!(target_arch = "riscv64") { 205 | assert!(a > thirty_years); 206 | } 207 | 208 | // let's assume that we're all running computers earlier than 2090. 209 | // Should give us ~70 years to fix this! 210 | let hundred_twenty_years = thirty_years * 4; 211 | assert!(a < hundred_twenty_years); 212 | } 213 | 214 | #[cfg(feature = "monotonize_impl")] 215 | #[cfg(all(target_has_atomic = "64", not(target_has_atomic = "128")))] 216 | #[test] 217 | fn monotonizer_wrapping_backslide() { 218 | use core::sync::atomic::AtomicU64; 219 | use std::time::monotonic::inner::{monotonize_impl, ZERO}; 220 | 221 | let reference = AtomicU64::new(0); 222 | 223 | let time = match ZERO.checked_add_duration(&Duration::from_secs(0xffff_ffff)) { 224 | Some(time) => time, 225 | None => { 226 | // platform cannot represent u32::MAX seconds so it won't have to deal with this kind 227 | // of overflow either 228 | return; 229 | } 230 | }; 231 | 232 | let monotonized = monotonize_impl(&reference, time); 233 | let expected = ZERO 234 | .checked_add_duration(&Duration::from_secs(1 << 32)) 235 | .unwrap(); 236 | assert_eq!( 237 | monotonized, expected, 238 | "64bit monotonizer should handle overflows in the seconds part" 239 | ); 240 | } 241 | 242 | #[cfg(feature = "bench")] 243 | macro_rules! bench_instant_threaded { 244 | ($bench_name:ident, $thread_count:expr) => { 245 | #[bench] 246 | #[cfg(not(target_arch = "wasm32"))] 247 | fn $bench_name(b: &mut Bencher) -> std::thread::Result<()> { 248 | use std::sync::atomic::{AtomicBool, Ordering}; 249 | use std::sync::Arc; 250 | 251 | let running = Arc::new(AtomicBool::new(true)); 252 | 253 | let threads: Vec<_> = (0..$thread_count) 254 | .map(|_| { 255 | let flag = Arc::clone(&running); 256 | std::thread::spawn(move || { 257 | while flag.load(Ordering::Relaxed) { 258 | black_box(Instant::now()); 259 | } 260 | }) 261 | }) 262 | .collect(); 263 | 264 | b.iter(|| { 265 | let a = Instant::now(); 266 | let b = Instant::now(); 267 | assert!(b >= a); 268 | }); 269 | 270 | running.store(false, Ordering::Relaxed); 271 | 272 | for t in threads { 273 | t.join()?; 274 | } 275 | Ok(()) 276 | } 277 | }; 278 | } 279 | 280 | #[cfg(feature = "bench")] 281 | bench_instant_threaded!(instant_contention_01_threads, 0); 282 | #[cfg(feature = "bench")] 283 | bench_instant_threaded!(instant_contention_02_threads, 1); 284 | #[cfg(feature = "bench")] 285 | bench_instant_threaded!(instant_contention_04_threads, 3); 286 | #[cfg(feature = "bench")] 287 | bench_instant_threaded!(instant_contention_08_threads, 7); 288 | #[cfg(feature = "bench")] 289 | bench_instant_threaded!(instant_contention_16_threads, 15); 290 | --------------------------------------------------------------------------------