diff options
author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2022-06-15 21:44:07 +0000 |
---|---|---|
committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2022-06-15 21:44:07 +0000 |
commit | 28f27ef1ac199a65d77fefa3f7f9d83c7cd238df (patch) | |
tree | 78413dcf697346c0e15e4615d70bce99e4175794 | |
parent | 8d2ea43a57360a9d54308fe21f27dd2c38a6f5b4 (diff) | |
parent | fba8cea794b3daf57fa3182b73eb1ab13786fcdf (diff) | |
download | getrandom-aml_tz3_314012010.tar.gz |
Snap for 8730993 from fba8cea794b3daf57fa3182b73eb1ab13786fcdf to mainline-tzdata3-releaseaml_tz3_314012070aml_tz3_314012050aml_tz3_314012010aml_tz3_313110000aml_tz3_312511020aml_tz3_312511010aml_tz3_312410020aml_tz3_312410010android12-mainline-tzdata3-releaseaml_tz3_314012010
Change-Id: Ib3dec89365acb259476d2ca7585ffc11fd9e8695
-rw-r--r-- | .cargo_vcs_info.json | 7 | ||||
-rw-r--r-- | Android.bp | 76 | ||||
-rw-r--r-- | CHANGELOG.md | 67 | ||||
-rw-r--r-- | Cargo.toml | 44 | ||||
-rw-r--r-- | Cargo.toml.orig | 2 | ||||
-rw-r--r-- | METADATA | 8 | ||||
-rw-r--r-- | TEST_MAPPING | 104 | ||||
-rw-r--r-- | build.rs | 14 | ||||
-rw-r--r-- | cargo2android.json | 11 | ||||
-rw-r--r-- | src/custom.rs | 2 | ||||
-rw-r--r-- | src/dragonfly.rs | 26 | ||||
-rw-r--r-- | src/error.rs | 11 | ||||
-rw-r--r-- | src/espidf.rs | 26 | ||||
-rw-r--r-- | src/ios.rs | 3 | ||||
-rw-r--r-- | src/js.rs | 85 | ||||
-rw-r--r-- | src/lib.rs | 103 | ||||
-rw-r--r-- | src/solid.rs | 26 | ||||
-rw-r--r-- | src/use_file.rs | 6 | ||||
-rw-r--r-- | src/wasi.rs | 12 | ||||
-rw-r--r-- | src/windows.rs | 1 |
20 files changed, 179 insertions, 455 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index 279a9af..64fafa1 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,6 +1,5 @@ { "git": { - "sha1": "ffd22552daa7d21b77ec20c1623bb4789b02122a" - }, - "path_in_vcs": "" -}
\ No newline at end of file + "sha1": "d79de0c95c01860268e071bcb6b0d019e18cd608" + } +} @@ -1,4 +1,4 @@ -// This file is generated by cargo2android.py --config cargo2android.json. +// This file is generated by cargo2android.py --device --run --dependencies --tests --features=std. // Do not modify this file as changes will be overridden on upgrade. package { @@ -37,18 +37,12 @@ license { ], } -rust_test { - name: "getrandom_test_src_lib", - host_supported: true, +rust_defaults { + name: "getrandom_defaults", crate_name: "getrandom", - cargo_env_compat: true, - cargo_pkg_version: "0.2.5", srcs: ["src/lib.rs"], test_suites: ["general-tests"], auto_gen_config: true, - test_options: { - unit_test: true, - }, edition: "2018", features: ["std"], rustlibs: [ @@ -57,11 +51,22 @@ rust_test { ], } +rust_test_host { + name: "getrandom_host_test_src_lib", + defaults: ["getrandom_defaults"], + test_options: { + unit_test: true, + }, +} + +rust_test { + name: "getrandom_device_test_src_lib", + defaults: ["getrandom_defaults"], +} + rust_defaults { - name: "getrandom_test_defaults", + name: "getrandom_defaults_getrandom", crate_name: "getrandom", - cargo_env_compat: true, - cargo_pkg_version: "0.2.5", test_suites: ["general-tests"], auto_gen_config: true, edition: "2018", @@ -73,10 +78,24 @@ rust_defaults { ], } +rust_test_host { + name: "getrandom_host_test_tests_custom", + defaults: ["getrandom_defaults_getrandom"], + srcs: ["tests/custom.rs"], + test_options: { + unit_test: true, + }, +} + rust_test { - name: "getrandom_test_tests_normal", - defaults: ["getrandom_test_defaults"], - host_supported: true, + name: "getrandom_device_test_tests_custom", + defaults: ["getrandom_defaults_getrandom"], + srcs: ["tests/custom.rs"], +} + +rust_test_host { + name: "getrandom_host_test_tests_normal", + defaults: ["getrandom_defaults_getrandom"], srcs: ["tests/normal.rs"], test_options: { unit_test: true, @@ -84,21 +103,30 @@ rust_test { } rust_test { - name: "getrandom_test_tests_rdrand", - defaults: ["getrandom_test_defaults"], - host_supported: true, + name: "getrandom_device_test_tests_normal", + defaults: ["getrandom_defaults_getrandom"], + srcs: ["tests/normal.rs"], +} + +rust_test_host { + name: "getrandom_host_test_tests_rdrand", + defaults: ["getrandom_defaults_getrandom"], srcs: ["tests/rdrand.rs"], test_options: { unit_test: true, }, } +rust_test { + name: "getrandom_device_test_tests_rdrand", + defaults: ["getrandom_defaults_getrandom"], + srcs: ["tests/rdrand.rs"], +} + rust_library { name: "libgetrandom", host_supported: true, crate_name: "getrandom", - cargo_env_compat: true, - cargo_pkg_version: "0.2.5", srcs: ["src/lib.rs"], edition: "2018", features: ["std"], @@ -106,8 +134,8 @@ rust_library { "libcfg_if", "liblibc", ], - apex_available: [ - "//apex_available:platform", - "com.android.virt", - ], } + +// dependent_library ["feature_list"] +// cfg-if-1.0.0 +// libc-0.2.87 diff --git a/CHANGELOG.md b/CHANGELOG.md index 99b442b..c3ca728 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,44 +4,6 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [0.2.5] - 2022-02-22 -### Added -- ESP-IDF targets (`*‑espidf`) support [#245] - -### Fixed -- Webpack warning caused by dynamic require [#234] -- Error checking on iOS for `SecRandomCopyBytes` [#244] - -[#234]: https://github.com/rust-random/getrandom/pull/234 -[#244]: https://github.com/rust-random/getrandom/pull/244 -[#245]: https://github.com/rust-random/getrandom/pull/245 - -## [0.2.4] - 2021-12-13 -### Changed -- Use explicit imports in the `js` backend [#220] -- Use `/dev/urandom` on Redox instead of `rand:` [#222] -- Use `NonZeroU32::new_unchecked` to convert wasi error [#233] - -### Added -- SOLID targets (`*-kmc-solid_*`) support [#235] -- Limited Hermit (`x86_64-unknown-hermit`) support [#236] - -[#220]: https://github.com/rust-random/getrandom/pull/220 -[#222]: https://github.com/rust-random/getrandom/pull/222 -[#233]: https://github.com/rust-random/getrandom/pull/233 -[#235]: https://github.com/rust-random/getrandom/pull/235 -[#236]: https://github.com/rust-random/getrandom/pull/236 - -## [0.2.3] - 2021-04-10 -### Changed -- Replace build.rs with link attributes. [#205] -- Add support for getrandom syscall on DragonFly BSD. [#210] -- Improve Node.js detection. [#215] - -[#205]: https://github.com/rust-random/getrandom/pull/205 -[#210]: https://github.com/rust-random/getrandom/pull/210 -[#215]: https://github.com/rust-random/getrandom/pull/215 - ## [0.2.2] - 2021-01-19 ### Changed - Forward `rustc-dep-of-std` to dependencies. [#198] @@ -83,8 +45,8 @@ The following (off by default) Cargo features have been added: - Unsupported targets no longer compile [#107] - Change/Add `Error` constants [#120] - Only impl `std` traits when the `"std"` Cargo feature is specified [#106] -- Remove official support for Hermit, L4Re, and UEFI [#133] -- Remove optional `"log"` dependency [#131] +- Remove offical support for Hermit, L4Re, and UEFI [#133] +- Remove optional `"log"` dependancy [#131] - Update minimum supported Linux kernel to 2.6.32 [#153] - Update MSRV to 1.34 [#159] @@ -280,28 +242,3 @@ Publish initial implementation. ## [0.0.0] - 2019-01-19 Publish an empty template library. - -[0.2.5]: https://github.com/rust-random/getrandom/compare/v0.2.4...v0.2.5 -[0.2.4]: https://github.com/rust-random/getrandom/compare/v0.2.3...v0.2.4 -[0.2.3]: https://github.com/rust-random/getrandom/compare/v0.2.2...v0.2.3 -[0.2.2]: https://github.com/rust-random/getrandom/compare/v0.2.1...v0.2.2 -[0.2.1]: https://github.com/rust-random/getrandom/compare/v0.2.0...v0.2.1 -[0.2.0]: https://github.com/rust-random/getrandom/compare/v0.1.15...v0.2.0 -[0.1.16]: https://github.com/rust-random/getrandom/compare/v0.1.15...v0.1.16 -[0.1.15]: https://github.com/rust-random/getrandom/compare/v0.1.14...v0.1.15 -[0.1.14]: https://github.com/rust-random/getrandom/compare/v0.1.13...v0.1.14 -[0.1.13]: https://github.com/rust-random/getrandom/compare/v0.1.12...v0.1.13 -[0.1.12]: https://github.com/rust-random/getrandom/compare/v0.1.11...v0.1.12 -[0.1.11]: https://github.com/rust-random/getrandom/compare/v0.1.10...v0.1.11 -[0.1.10]: https://github.com/rust-random/getrandom/compare/v0.1.9...v0.1.10 -[0.1.9]: https://github.com/rust-random/getrandom/compare/v0.1.8...v0.1.9 -[0.1.8]: https://github.com/rust-random/getrandom/compare/v0.1.7...v0.1.8 -[0.1.7]: https://github.com/rust-random/getrandom/compare/v0.1.6...v0.1.7 -[0.1.6]: https://github.com/rust-random/getrandom/compare/v0.1.5...v0.1.6 -[0.1.5]: https://github.com/rust-random/getrandom/compare/v0.1.4...v0.1.5 -[0.1.4]: https://github.com/rust-random/getrandom/compare/v0.1.3...v0.1.4 -[0.1.3]: https://github.com/rust-random/getrandom/compare/v0.1.2...v0.1.3 -[0.1.2]: https://github.com/rust-random/getrandom/compare/v0.1.1...v0.1.2 -[0.1.1]: https://github.com/rust-random/getrandom/compare/v0.1.0...v0.1.1 -[0.1.0]: https://github.com/rust-random/getrandom/compare/v0.0.0...v0.1.0 -[0.0.0]: https://github.com/rust-random/getrandom/releases/tag/v0.0.0 @@ -3,37 +3,27 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. +# to registry (e.g., crates.io) dependencies # -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) [package] edition = "2018" name = "getrandom" -version = "0.2.5" +version = "0.2.2" authors = ["The Rand Project Developers"] exclude = [".*"] description = "A small cross-platform library for retrieving random data from system source" documentation = "https://docs.rs/getrandom" -categories = [ - "os", - "no-std", -] +categories = ["os", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-random/getrandom" - [package.metadata.docs.rs] -features = [ - "std", - "custom", -] -rustdoc-args = [ - "--cfg", - "docsrs", -] - +features = ["std", "custom"] +rustdoc-args = ["--cfg", "docsrs"] [dependencies.cfg-if] version = "1" @@ -48,20 +38,11 @@ package = "rustc-std-workspace-core" [features] custom = [] -js = [ - "wasm-bindgen", - "js-sys", -] +js = ["wasm-bindgen", "js-sys"] rdrand = [] -rustc-dep-of-std = [ - "compiler_builtins", - "core", - "libc/rustc-dep-of-std", - "wasi/rustc-dep-of-std", -] +rustc-dep-of-std = ["compiler_builtins", "core", "libc/rustc-dep-of-std", "wasi/rustc-dep-of-std"] std = [] test-in-browser = [] - [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dependencies.js-sys] version = "0.3" optional = true @@ -70,13 +51,10 @@ optional = true version = "0.2.62" optional = true default-features = false - [target."cfg(all(target_arch = \"wasm32\", target_os = \"unknown\"))".dev-dependencies.wasm-bindgen-test] version = "0.3.18" - [target."cfg(target_os = \"wasi\")".dependencies.wasi] version = "0.10" - [target."cfg(unix)".dependencies.libc] version = "0.2.64" default-features = false diff --git a/Cargo.toml.orig b/Cargo.toml.orig index eb51149..dabf016 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,6 +1,6 @@ [package] name = "getrandom" -version = "0.2.5" # Also update html_root_url in lib.rs when bumping this +version = "0.2.2" # Also update html_root_url in lib.rs when bumping this edition = "2018" authors = ["The Rand Project Developers"] license = "MIT OR Apache-2.0" @@ -7,13 +7,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/getrandom/getrandom-0.2.5.crate" + value: "https://static.crates.io/crates/getrandom/getrandom-0.2.2.crate" } - version: "0.2.5" + version: "0.2.2" license_type: NOTICE last_upgrade_date { - year: 2022 + year: 2021 month: 3 - day: 1 + day: 3 } } diff --git a/TEST_MAPPING b/TEST_MAPPING index 42e04b4..efa80d7 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -1,120 +1,32 @@ // Generated by update_crate_tests.py for tests that depend on this crate. { - "imports": [ - { - "path": "external/rust/crates/base64" - }, - { - "path": "external/rust/crates/cast" - }, - { - "path": "external/rust/crates/crc32fast" - }, - { - "path": "external/rust/crates/crossbeam-deque" - }, - { - "path": "external/rust/crates/crossbeam-epoch" - }, - { - "path": "external/rust/crates/crossbeam-queue" - }, - { - "path": "external/rust/crates/crossbeam-utils" - }, - { - "path": "external/rust/crates/mio" - }, - { - "path": "external/rust/crates/quickcheck" - }, - { - "path": "external/rust/crates/rand_chacha" - }, - { - "path": "external/rust/crates/rand_core" - }, - { - "path": "external/rust/crates/rand_xorshift" - }, - { - "path": "external/rust/crates/regex" - }, - { - "path": "external/rust/crates/ryu" - }, - { - "path": "external/rust/crates/tokio" - } - ], "presubmit": [ { - "name": "ZipFuseTest" - }, - { - "name": "apkdmverity.test" - }, - { - "name": "authfs_device_test_src_lib" - }, - { - "name": "getrandom_test_src_lib" - }, - { - "name": "getrandom_test_tests_normal" - }, - { - "name": "getrandom_test_tests_rdrand" - }, - { "name": "keystore2_test" }, { - "name": "keystore2_test_utils_test" - }, - { - "name": "legacykeystore_test" - }, - { - "name": "microdroid_manager_test" - }, - { - "name": "virtualizationservice_device_test" - } - ], - "presubmit-rust": [ - { - "name": "ZipFuseTest" - }, - { - "name": "apkdmverity.test" - }, - { - "name": "authfs_device_test_src_lib" + "name": "getrandom_device_test_tests_custom" }, { - "name": "getrandom_test_src_lib" + "name": "rand_xorshift_device_test_tests_mod" }, { - "name": "getrandom_test_tests_normal" + "name": "getrandom_device_test_tests_normal" }, { - "name": "getrandom_test_tests_rdrand" - }, - { - "name": "keystore2_test" + "name": "rand_xorshift_device_test_src_lib" }, { - "name": "keystore2_test_utils_test" + "name": "getrandom_device_test_tests_rdrand" }, { - "name": "legacykeystore_test" + "name": "rand_core_device_test_src_lib" }, { - "name": "microdroid_manager_test" + "name": "getrandom_device_test_src_lib" }, { - "name": "virtualizationservice_device_test" + "name": "vpnprofilestore_test" } ] } diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..95f4b90 --- /dev/null +++ b/build.rs @@ -0,0 +1,14 @@ +#![deny(warnings)] + +use std::env; + +fn main() { + let target = env::var("TARGET").expect("TARGET was not set"); + if target.contains("windows") { + // for BCryptGenRandom + println!("cargo:rustc-link-lib=bcrypt"); + } else if target.contains("apple-ios") { + // for SecRandomCopyBytes and kSecRandomDefault + println!("cargo:rustc-link-lib=framework=Security"); + } +} diff --git a/cargo2android.json b/cargo2android.json deleted file mode 100644 index b73c7b4..0000000 --- a/cargo2android.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "apex-available": [ - "//apex_available:platform", - "com.android.virt" - ], - "dependencies": true, - "device": true, - "features": "std", - "run": true, - "tests": true -}
\ No newline at end of file diff --git a/src/custom.rs b/src/custom.rs index 6110b05..0d3123c 100644 --- a/src/custom.rs +++ b/src/custom.rs @@ -16,7 +16,7 @@ use core::num::NonZeroU32; /// /// The function to register must have the same signature as /// [`getrandom::getrandom`](crate::getrandom). The function can be defined -/// wherever you want, either in root crate or a dependent crate. +/// wherever you want, either in root crate or a dependant crate. /// /// For example, if we wanted a `failure-getrandom` crate containing an /// implementation that always fails, we would first depend on `getrandom` diff --git a/src/dragonfly.rs b/src/dragonfly.rs deleted file mode 100644 index f27e906..0000000 --- a/src/dragonfly.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2021 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Implementation for DragonFly BSD -use crate::{ - use_file, - util_libc::{sys_fill_exact, Weak}, - Error, -}; - -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") }; - type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t; - - if let Some(fptr) = GETRANDOM.ptr() { - let func: GetRandomFn = unsafe { core::mem::transmute(fptr) }; - return sys_fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) }); - } else { - use_file::getrandom_inner(dest) - } -} diff --git a/src/error.rs b/src/error.rs index 6615753..48abdc1 100644 --- a/src/error.rs +++ b/src/error.rs @@ -73,14 +73,7 @@ impl Error { #[inline] pub fn raw_os_error(self) -> Option<i32> { if self.0.get() < Self::INTERNAL_START { - match () { - #[cfg(target_os = "solid_asp3")] - // On SOLID, negate the error code again to obtain the original - // error code. - () => Some(-(self.0.get() as i32)), - #[cfg(not(target_os = "solid_asp3"))] - () => Some(self.0.get() as i32), - } + Some(self.0.get() as i32) } else { None } @@ -169,7 +162,7 @@ fn internal_desc(error: Error) -> Option<&'static str> { Error::WINDOWS_RTL_GEN_RANDOM => Some("RtlGenRandom: Windows system function failure"), Error::FAILED_RDRAND => Some("RDRAND: failed multiple times: CPU issue likely"), Error::NO_RDRAND => Some("RDRAND: instruction not supported"), - Error::WEB_CRYPTO => Some("Web Crypto API is unavailable"), + Error::WEB_CRYPTO => Some("Web API self.crypto is unavailable"), Error::WEB_GET_RANDOM_VALUES => Some("Web API crypto.getRandomValues is unavailable"), Error::VXWORKS_RAND_SECURE => Some("randSecure: VxWorks RNG module is not initialized"), Error::NODE_CRYPTO => Some("Node.js crypto module is unavailable"), diff --git a/src/espidf.rs b/src/espidf.rs deleted file mode 100644 index dce8a2a..0000000 --- a/src/espidf.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2021 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Implementation for ESP-IDF -use crate::Error; -use core::ffi::c_void; - -extern "C" { - fn esp_fill_random(buf: *mut c_void, len: usize) -> u32; -} - -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - // Not that NOT enabling WiFi, BT, or the voltage noise entropy source (via `bootloader_random_enable`) - // will cause ESP-IDF to return pseudo-random numbers based on the voltage noise entropy, after the initial boot process: - // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html - // - // However tracking if some of these entropy sources is enabled is way too difficult to implement here - unsafe { esp_fill_random(dest.as_mut_ptr().cast(), dest.len()) }; - - Ok(()) -} @@ -18,8 +18,7 @@ extern "C" { pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { // Apple's documentation guarantees kSecRandomDefault is a synonym for NULL. let ret = unsafe { SecRandomCopyBytes(null(), dest.len(), dest.as_mut_ptr()) }; - // errSecSuccess (from SecBase.h) is always zero. - if ret != 0 { + if ret == -1 { Err(Error::IOS_SEC_RANDOM) } else { Ok(()) @@ -10,8 +10,8 @@ use crate::Error; extern crate std; use std::thread_local; -use js_sys::{global, Uint8Array}; -use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; +use js_sys::Uint8Array; +use wasm_bindgen::prelude::*; // Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256; @@ -57,73 +57,50 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { } fn getrandom_init() -> Result<RngSource, Error> { - let global: Global = global().unchecked_into(); - if is_node(&global) { - let crypto = NODE_MODULE - .require("crypto") - .map_err(|_| Error::NODE_CRYPTO)?; - return Ok(RngSource::Node(crypto)); - } - - // Assume we are in some Web environment (browser or web worker). We get - // `self.crypto` (called `msCrypto` on IE), so we can call - // `crypto.getRandomValues`. If `crypto` isn't defined, we assume that - // we are in an older web browser and the OS RNG isn't available. - let crypto = match (global.crypto(), global.ms_crypto()) { - (c, _) if c.is_object() => c, - (_, c) if c.is_object() => c, - _ => return Err(Error::WEB_CRYPTO), - }; - - let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32); - Ok(RngSource::Browser(crypto, buf)) -} + if let Ok(self_) = Global::get_self() { + // If `self` is defined then we're in a browser somehow (main window + // or web worker). We get `self.crypto` (called `msCrypto` on IE), so we + // can call `crypto.getRandomValues`. If `crypto` isn't defined, we + // assume we're in an older web browser and the OS RNG isn't available. + + let crypto: BrowserCrypto = match (self_.crypto(), self_.ms_crypto()) { + (crypto, _) if !crypto.is_undefined() => crypto, + (_, crypto) if !crypto.is_undefined() => crypto, + _ => return Err(Error::WEB_CRYPTO), + }; -// Taken from https://www.npmjs.com/package/browser-or-node -fn is_node(global: &Global) -> bool { - let process = global.process(); - if process.is_object() { - let versions = process.versions(); - if versions.is_object() { - return versions.node().is_string(); - } + let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32); + return Ok(RngSource::Browser(crypto, buf)); } - false + + let crypto = MODULE.require("crypto").map_err(|_| Error::NODE_CRYPTO)?; + Ok(RngSource::Node(crypto)) } #[wasm_bindgen] extern "C" { - type Global; // Return type of js_sys::global() + type Global; + #[wasm_bindgen(getter, catch, static_method_of = Global, js_class = self, js_name = self)] + fn get_self() -> Result<Self_, JsValue>; - // Web Crypto API (https://www.w3.org/TR/WebCryptoAPI/) + type Self_; #[wasm_bindgen(method, getter, js_name = "msCrypto")] - fn ms_crypto(this: &Global) -> BrowserCrypto; + fn ms_crypto(me: &Self_) -> BrowserCrypto; #[wasm_bindgen(method, getter)] - fn crypto(this: &Global) -> BrowserCrypto; + fn crypto(me: &Self_) -> BrowserCrypto; + type BrowserCrypto; #[wasm_bindgen(method, js_name = getRandomValues, catch)] - fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>; + fn get_random_values(me: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>; - // We use a "module" object here instead of just annotating require() with - // js_name = "module.require", so that Webpack doesn't give a warning. See: - // https://github.com/rust-random/getrandom/issues/224 - type NodeModule; #[wasm_bindgen(js_name = module)] - static NODE_MODULE: NodeModule; - // Node JS crypto module (https://nodejs.org/api/crypto.html) + static MODULE: NodeModule; + + type NodeModule; #[wasm_bindgen(method, catch)] fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>; + type NodeCrypto; #[wasm_bindgen(method, js_name = randomFillSync, catch)] - fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>; - - // Node JS process Object (https://nodejs.org/api/process.html) - #[wasm_bindgen(method, getter)] - fn process(this: &Global) -> Process; - type Process; - #[wasm_bindgen(method, getter)] - fn versions(this: &Process) -> Versions; - type Versions; - #[wasm_bindgen(method, getter)] - fn node(this: &Versions) -> JsValue; + fn random_fill_sync(crypto: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>; } @@ -12,27 +12,24 @@ //! //! | Target | Target Triple | Implementation //! | ----------------- | ------------------ | -------------- -//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random` -//! | Windows | `*‑windows‑*` | [`BCryptGenRandom`] -//! | macOS | `*‑apple‑darwin` | [`getentropy`][3] if available, otherwise [`/dev/random`][4] (identical to `/dev/urandom`) -//! | iOS | `*‑apple‑ios` | [`SecRandomCopyBytes`] -//! | FreeBSD | `*‑freebsd` | [`getrandom`][5] if available, otherwise [`kern.arandom`][6] -//! | OpenBSD | `*‑openbsd` | [`getentropy`][7] -//! | NetBSD | `*‑netbsd` | [`kern.arandom`][8] -//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9] if available, otherwise [`/dev/random`][10] -//! | Solaris, illumos | `*‑solaris`, `*‑illumos` | [`getrandom`][11] if available, otherwise [`/dev/random`][12] -//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`] -//! | Redox | `*‑redox` | `/dev/urandom` +//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random` | +//! | Windows | `*‑windows‑*` | [`BCryptGenRandom`][3] | +//! | macOS | `*‑apple‑darwin` | [`getentropy()`][19] if available, otherwise [`/dev/random`][20] (identical to `/dev/urandom`) +//! | iOS | `*‑apple‑ios` | [`SecRandomCopyBytes`][4] +//! | FreeBSD | `*‑freebsd` | [`getrandom()`][21] if available, otherwise [`kern.arandom`][5] +//! | OpenBSD | `*‑openbsd` | [`getentropy`][6] +//! | NetBSD | `*‑netbsd` | [`kern.arandom`][7] +//! | Dragonfly BSD | `*‑dragonfly` | [`/dev/random`][8] +//! | Solaris, illumos | `*‑solaris`, `*‑illumos` | [`getrandom()`][9] if available, otherwise [`/dev/random`][10] +//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`][11] +//! | Redox | `*‑redox` | [`rand:`][12] //! | Haiku | `*‑haiku` | `/dev/random` (identical to `/dev/urandom`) -//! | Hermit | `x86_64-*-hermit` | [`RDRAND`] -//! | SGX | `x86_64‑*‑sgx` | [`RDRAND`] +//! | SGX | `x86_64‑*‑sgx` | [RDRAND][18] //! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure` -//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`] //! | Emscripten | `*‑emscripten` | `/dev/random` (identical to `/dev/urandom`) -//! | WASI | `wasm32‑wasi` | [`random_get`] -//! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues`], see [WebAssembly support] -//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`], see [WebAssembly support] -//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes` +//! | WASI | `wasm32‑wasi` | [`__wasi_random_get`][17] +//! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues()`][14], see [WebAssembly support][16] +//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`][15], see [WebAssembly support][16] //! //! There is no blanket implementation on `unix` targets that reads from //! `/dev/urandom`. This ensures all supported targets are using the recommended @@ -53,8 +50,8 @@ //! //! ### RDRAND on x86 //! -//! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using -//! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64` +//! *If the `"rdrand"` Cargo feature is enabled*, `getrandom` will fallback to using +//! the [`RDRAND`][18] instruction to get randomness on `no_std` `x86`/`x86_64` //! targets. This feature has no effect on other CPU architectures. //! //! ### WebAssembly support @@ -62,12 +59,11 @@ //! This crate fully supports the //! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and //! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/) -//! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used -//! by `wasm-pack`) is not automatically +//! targets. However, the `wasm32-unknown-unknown` target is not automatically //! supported since, from the target name alone, we cannot deduce which //! JavaScript interface is in use (or if JavaScript is available at all). //! -//! Instead, *if the `js` Cargo feature is enabled*, this crate will assume +//! Instead, *if the `"js"` Cargo feature is enabled*, this crate will assume //! that you are building for an environment containing JavaScript, and will //! call the appropriate methods. Both web browser (main window and Web Workers) //! and Node.js environments are supported, invoking the methods @@ -85,7 +81,7 @@ //! //! Note that registering a custom implementation only has an effect on targets //! that would otherwise not compile. Any supported targets (including those -//! using `rdrand` and `js` Cargo features) continue using their normal +//! using `"rdrand"` and `"js"` Cargo features) continue using their normal //! implementations even if a function is registered. //! //! ### Indirect Dependencies @@ -124,31 +120,29 @@ //! //! [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html //! [2]: http://man7.org/linux/man-pages/man4/urandom.4.html -//! [3]: https://www.unix.com/man-page/mojave/2/getentropy/ -//! [4]: https://www.unix.com/man-page/mojave/4/random/ -//! [5]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable -//! [6]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4 -//! [7]: https://man.openbsd.org/getentropy.2 -//! [8]: https://man.netbsd.org/sysctl.7 -//! [9]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom -//! [10]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4 -//! [11]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html -//! [12]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html -//! -//! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom -//! [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues -//! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide -//! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc -//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw -//! [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback -//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t -//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno -//! [WebAssembly support]: #webassembly-support +//! [3]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom +//! [4]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc +//! [5]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4 +//! [6]: https://man.openbsd.org/getentropy.2 +//! [7]: https://netbsd.gw.com/cgi-bin/man-cgi?sysctl+7+NetBSD-8.0 +//! [8]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4 +//! [9]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html +//! [10]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html +//! [11]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw +//! [12]: https://github.com/redox-os/randd/blob/master/src/main.rs +//! [14]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues +//! [15]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback +//! [16]: #webassembly-support +//! [17]: https://github.com/WebAssembly/WASI/blob/master/design/WASI-core.md#__wasi_random_get +//! [18]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide +//! [19]: https://www.unix.com/man-page/mojave/2/getentropy/ +//! [20]: https://www.unix.com/man-page/mojave/4/random/ +//! [21]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/getrandom/0.2.5" + html_root_url = "https://docs.rs/getrandom/0.2.2" )] #![no_std] #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)] @@ -172,8 +166,8 @@ pub use crate::error::Error; // // These should all provide getrandom_inner with the same signature as getrandom. cfg_if! { - if #[cfg(any(target_os = "emscripten", target_os = "haiku", - target_os = "redox"))] { + if #[cfg(any(target_os = "dragonfly", target_os = "emscripten", + target_os = "haiku", target_os = "redox"))] { mod util_libc; #[path = "use_file.rs"] mod imp; } else if #[cfg(any(target_os = "android", target_os = "linux"))] { @@ -187,10 +181,6 @@ cfg_if! { } else if #[cfg(any(target_os = "freebsd", target_os = "netbsd"))] { mod util_libc; #[path = "bsd_arandom.rs"] mod imp; - } else if #[cfg(target_os = "dragonfly")] { - mod util_libc; - mod use_file; - #[path = "dragonfly.rs"] mod imp; } else if #[cfg(target_os = "fuchsia")] { #[path = "fuchsia.rs"] mod imp; } else if #[cfg(target_os = "ios")] { @@ -204,15 +194,9 @@ cfg_if! { #[path = "openbsd.rs"] mod imp; } else if #[cfg(target_os = "wasi")] { #[path = "wasi.rs"] mod imp; - } else if #[cfg(all(target_arch = "x86_64", target_os = "hermit"))] { - #[path = "rdrand.rs"] mod imp; } else if #[cfg(target_os = "vxworks")] { mod util_libc; #[path = "vxworks.rs"] mod imp; - } else if #[cfg(target_os = "solid_asp3")] { - #[path = "solid.rs"] mod imp; - } else if #[cfg(target_os = "espidf")] { - #[path = "espidf.rs"] mod imp; } else if #[cfg(windows)] { #[path = "windows.rs"] mod imp; } else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] { @@ -225,11 +209,6 @@ cfg_if! { #[path = "js.rs"] mod imp; } else if #[cfg(feature = "custom")] { use custom as imp; - } else if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] { - compile_error!("the wasm32-unknown-unknown target is not supported by \ - default, you may need to enable the \"js\" feature. \ - For more information see: \ - https://docs.rs/getrandom/#webassembly-support"); } else { compile_error!("target is not supported, for more information see: \ https://docs.rs/getrandom/#unsupported-targets"); diff --git a/src/solid.rs b/src/solid.rs deleted file mode 100644 index dc76aac..0000000 --- a/src/solid.rs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2021 Developers of the Rand project. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Implementation for SOLID -use crate::Error; -use core::num::NonZeroU32; - -extern "C" { - pub fn SOLID_RNG_SampleRandomBytes(buffer: *mut u8, length: usize) -> i32; -} - -pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - let ret = unsafe { SOLID_RNG_SampleRandomBytes(dest.as_mut_ptr(), dest.len()) }; - if ret >= 0 { - Ok(()) - } else { - // ITRON error numbers are always negative, so we negate it so that it - // falls in the dedicated OS error range (1..INTERNAL_START). - Err(NonZeroU32::new((-ret) as u32).unwrap().into()) - } -} diff --git a/src/use_file.rs b/src/use_file.rs index 16c0216..465c069 100644 --- a/src/use_file.rs +++ b/src/use_file.rs @@ -17,6 +17,8 @@ use core::{ sync::atomic::{AtomicUsize, Ordering::Relaxed}, }; +#[cfg(target_os = "redox")] +const FILE_PATH: &str = "rand:\0"; #[cfg(any( target_os = "dragonfly", target_os = "emscripten", @@ -26,7 +28,7 @@ use core::{ target_os = "illumos" ))] const FILE_PATH: &str = "/dev/random\0"; -#[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] +#[cfg(any(target_os = "android", target_os = "linux"))] const FILE_PATH: &str = "/dev/urandom\0"; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { @@ -45,7 +47,7 @@ pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { } // Returns the file descriptor for the device file used to retrieve random -// bytes. The file will be opened exactly once. All subsequent calls will +// bytes. The file will be opened exactly once. All successful calls will // return the same file descriptor. This file descriptor is never closed. fn get_rng_fd() -> Result<libc::c_int, Error> { static FD: AtomicUsize = AtomicUsize::new(LazyUsize::UNINIT); diff --git a/src/wasi.rs b/src/wasi.rs index 2d413e0..4674f43 100644 --- a/src/wasi.rs +++ b/src/wasi.rs @@ -12,12 +12,8 @@ use core::num::NonZeroU32; use wasi::random_get; pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { - unsafe { - random_get(dest.as_mut_ptr(), dest.len()).map_err(|e: wasi::Error| { - // convert wasi's Error into getrandom's NonZeroU32 error - // SAFETY: `wasi::Error` is `NonZeroU16` internally, so `e.raw_error()` - // will never return 0 - NonZeroU32::new_unchecked(e.raw_error() as u32).into() - }) - } + unsafe { random_get(dest.as_mut_ptr(), dest.len()) }.map_err(|e: wasi::Error| { + // convert wasi's Error into getrandom's NonZeroU32 error + NonZeroU32::new(e.raw_error() as u32).unwrap().into() + }) } diff --git a/src/windows.rs b/src/windows.rs index 643badd..56b3d07 100644 --- a/src/windows.rs +++ b/src/windows.rs @@ -11,7 +11,6 @@ use core::{ffi::c_void, num::NonZeroU32, ptr}; const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002; -#[link(name = "bcrypt")] extern "system" { fn BCryptGenRandom( hAlgorithm: *mut c_void, |