├── .gitignore ├── src ├── fs.rs ├── sync.rs ├── prelude.rs ├── init.rs ├── macros.rs ├── env.rs ├── lib.rs ├── thread.rs ├── io.rs └── stack_overflow.rs ├── .rustfmt.toml ├── examples ├── assert-false.rs ├── hello.rs ├── prelude.rs ├── args.rs ├── rust-by-example-threads.rs ├── libc.rs └── greetings.rs ├── rust-toolchain.toml ├── COPYRIGHT ├── LICENSE-MIT ├── Cargo.toml ├── CODE_OF_CONDUCT.md ├── README.md ├── ORG_CODE_OF_CONDUCT.md ├── LICENSE-APACHE └── LICENSE-Apache-2.0_WITH_LLVM-exception /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /src/fs.rs: -------------------------------------------------------------------------------- 1 | //! Filesystem APIs. 2 | //! 3 | //! TODO: Add some. 4 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # This file tells tools we use rustfmt. We use the default settings. 2 | -------------------------------------------------------------------------------- /examples/assert-false.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | fn main() { 6 | assert!(false); 7 | } 8 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly-2025-03-05" 3 | components = ["rustc", "cargo", "rust-std", "rust-src", "rustfmt"] 4 | -------------------------------------------------------------------------------- /examples/hello.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | fn main() { 6 | println!("Hello, world!"); 7 | } 8 | -------------------------------------------------------------------------------- /examples/prelude.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | fn main() { 6 | debug_assert!(true); 7 | let t = vec![0]; 8 | drop(t); 9 | } 10 | -------------------------------------------------------------------------------- /src/sync.rs: -------------------------------------------------------------------------------- 1 | //! Useful synchronization primitives. 2 | 3 | pub use alloc_crate::sync::*; 4 | pub use core::sync::*; 5 | 6 | pub use rustix_futex_sync::{ 7 | Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, 8 | }; 9 | -------------------------------------------------------------------------------- /examples/args.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | use std::io::Write; 6 | 7 | fn main() { 8 | for i in std::env::args() { 9 | writeln!(std::io::stdout(), "arg {}", i).unwrap(); 10 | } 11 | writeln!(std::io::stdout(), "HOME {}", std::env::var("HOME").unwrap()).unwrap(); 12 | } 13 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | //! The Rust Prelude 2 | 3 | pub mod v1 { 4 | pub use crate::borrow::ToOwned; 5 | pub use crate::boxed::Box; 6 | pub use crate::string::{String, ToString}; 7 | pub use crate::vec::Vec; 8 | pub use core::prelude::v1::*; 9 | } 10 | pub mod rust_2015 { 11 | pub use super::v1::*; 12 | } 13 | pub mod rust_2018 { 14 | pub use super::rust_2015::*; 15 | } 16 | pub mod rust_2021 { 17 | pub use super::rust_2018::*; 18 | pub use core::convert::{TryFrom, TryInto}; 19 | pub use core::iter::FromIterator; 20 | } 21 | -------------------------------------------------------------------------------- /examples/rust-by-example-threads.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | use std::thread; 6 | 7 | const NTHREADS: u32 = 10; 8 | 9 | // This is the `main` thread 10 | fn main() { 11 | // Make a vector to hold the children which are spawned. 12 | let mut children = vec![]; 13 | 14 | for i in 0..NTHREADS { 15 | // Spin up another thread 16 | children.push(thread::spawn(move || { 17 | println!("this is thread number {}", i); 18 | })); 19 | } 20 | 21 | for child in children { 22 | // Wait for the thread to finish. Returns a result. 23 | let _ = child.join(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /examples/libc.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | fn main() { 6 | // Call functions declared in the `libc` crate, which will be resolved by 7 | // c-scape. 8 | unsafe { 9 | // Call functions declared in the `libc` crate, which will be resolved by 10 | // c-scape. c-scape doesn't have `printf`, so we do it by hand. 11 | let message = b"Hello, world!\n"; 12 | let mut remaining = &message[..]; 13 | while !remaining.is_empty() { 14 | match libc::write(1, message.as_ptr().cast(), message.len()) { 15 | -1 => match errno::errno().0 { 16 | libc::EINTR => continue, 17 | _ => panic!(), 18 | }, 19 | n => remaining = &remaining[n as usize..], 20 | } 21 | } 22 | libc::exit(0); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Short version for non-lawyers: 2 | 3 | `origin-studio` 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 `origin-studio` project are retained by their contributors. 10 | No copyright assignment is required to contribute to the `origin-studio` 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), `origin-studio` 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 | -------------------------------------------------------------------------------- /src/init.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "std")] 2 | pub(crate) fn sanitize_stdio_fds() { 3 | use rustix::cstr; 4 | use rustix::fd::BorrowedFd; 5 | use rustix::fs::{open, Mode, OFlags}; 6 | use rustix::io::{fcntl_getfd, Errno}; 7 | 8 | for raw_fd in 0..3 { 9 | let fd = unsafe { BorrowedFd::borrow_raw(raw_fd) }; 10 | if let Err(Errno::BADF) = fcntl_getfd(fd) { 11 | let _ = open(cstr!("/dev/null"), OFlags::RDWR, Mode::empty()).unwrap(); 12 | } 13 | } 14 | } 15 | 16 | #[cfg(feature = "std")] 17 | pub(crate) unsafe fn store_args(argc: i32, argv: *mut *mut u8, envp: *mut *mut u8) { 18 | crate::env::MAIN_ARGS = crate::env::MainArgs { argc, argv, envp }; 19 | } 20 | 21 | pub(crate) unsafe fn reset_sigpipe() { 22 | use core::mem::zeroed; 23 | use origin::signal::{sig_ign, sigaction, Sigaction, SigactionFlags, Signal}; 24 | 25 | let mut action = zeroed::(); 26 | action.sa_handler_kernel = sig_ign(); 27 | action.sa_flags = SigactionFlags::RESTART; 28 | sigaction(Signal::PIPE, Some(action)).unwrap(); 29 | } 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /examples/greetings.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | origin_studio::no_problem!(); 4 | 5 | fn main() { 6 | let greetings = [ 7 | "Hello", 8 | "Hola", 9 | "Bonjour", 10 | "Ciao", 11 | "こんにちは", 12 | "안녕하세요", 13 | "Cześć", 14 | "Olá", 15 | "Здравствуйте", 16 | "Chào bạn", 17 | "您好", 18 | "Hallo", 19 | "Hej", 20 | "Ahoj", 21 | "سلام", 22 | "สวัสดี", 23 | ]; 24 | 25 | for (num, greeting) in greetings.iter().enumerate() { 26 | print!("{} : ", greeting); 27 | match num { 28 | 0 => println!("This code is editable and runnable!"), 29 | 1 => println!("¡Este código es editable y ejecutable!"), 30 | 2 => println!("Ce code est modifiable et exécutable !"), 31 | 3 => println!("Questo codice è modificabile ed eseguibile!"), 32 | 4 => println!("このコードは編集して実行出来ます!"), 33 | 5 => println!("여기에서 코드를 수정하고 실행할 수 있습니다!"), 34 | 6 => println!("Ten kod można edytować oraz uruchomić!"), 35 | 7 => println!("Este código é editável e executável!"), 36 | 8 => println!("Этот код можно отредактировать и запустить!"), 37 | 9 => println!("Bạn có thể edit và run code trực tiếp!"), 38 | 10 => println!("这段代码是可以编辑并且能够运行的!"), 39 | 11 => println!("Dieser Code kann bearbeitet und ausgeführt werden!"), 40 | 12 => println!("Den här koden kan redigeras och köras!"), 41 | 13 => println!("Tento kód můžete upravit a spustit"), 42 | 14 => println!("این کد قابلیت ویرایش و اجرا دارد!"), 43 | 15 => println!("โค้ดนี้สามารถแก้ไขได้และรันได้"), 44 | _ => {} 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | /// Prints to the standard output. 2 | #[macro_export] 3 | macro_rules! print { 4 | ($($args:tt)*) => { 5 | core::fmt::write(&mut $crate::io::stdout(), format_args!($($args)*)).unwrap(); 6 | }; 7 | } 8 | 9 | /// Prints to the standard output, with a newline. 10 | #[macro_export] 11 | macro_rules! println { 12 | () => { 13 | <$crate::io::Stdout as core::fmt::Write>::write_str(&mut $crate::io::stdout(), "\n").unwrap(); 14 | }; 15 | ($format:expr) => { 16 | <$crate::io::Stdout as core::fmt::Write>::write_str(&mut $crate::io::stdout(), concat!($format, "\n")).unwrap(); 17 | }; 18 | ($format:expr, $($args:tt)*) => { 19 | core::fmt::write(&mut $crate::io::stdout().lock(), format_args!(concat!($format, "\n"), $($args)*)).unwrap(); 20 | }; 21 | } 22 | 23 | /// Prints to the standard error. 24 | #[macro_export] 25 | macro_rules! eprint { 26 | ($($args:tt)*) => { 27 | core::fmt::write(&mut $crate::io::stderr(), format_args!($($args)*)).unwrap(); 28 | }; 29 | } 30 | 31 | /// Prints to the standard error< with a newline. 32 | #[macro_export] 33 | macro_rules! eprintln { 34 | () => { 35 | <$crate::io::Stderr as core::fmt::Write>::write_str(&mut $crate::io::stderr(), "\n").unwrap(); 36 | }; 37 | ($format:expr) => { 38 | <$crate::io::Stderr as core::fmt::Write>::write_str(&mut $crate::io::stderr(), concat!($format, "\n")).unwrap(); 39 | }; 40 | ($format:expr, $($args:tt)*) => { 41 | core::fmt::write(&mut $crate::io::stderr().lock(), format_args!(concat!($format, "\n"), $($args)*)).unwrap(); 42 | }; 43 | } 44 | 45 | /// Writes formatted data into a buffer. 46 | #[macro_export] 47 | macro_rules! write { 48 | ($dst:expr, $($arg:tt)*) => { 49 | $dst.write_fmt($crate::format_args!($($arg)*)) 50 | }; 51 | } 52 | 53 | /// Writes formatted data into a buffer, with a newline appended. 54 | #[macro_export] 55 | macro_rules! writeln { 56 | ($dst:expr $(,)?) => { 57 | $crate::write!($dst, "\n") 58 | }; 59 | ($dst:expr, $($arg:tt)*) => { 60 | $dst.write_fmt(format_args!(concat!($format, "\n"), $($args)*)) 61 | }; 62 | } 63 | -------------------------------------------------------------------------------- /src/env.rs: -------------------------------------------------------------------------------- 1 | //! Inspection and manipulation of the process’s environment. 2 | 3 | use core::ffi::CStr; 4 | use core::ptr::null_mut; 5 | use core::{slice, str}; 6 | 7 | pub(crate) struct MainArgs { 8 | pub(crate) argc: i32, 9 | pub(crate) argv: *mut *mut u8, 10 | pub(crate) envp: *mut *mut u8, 11 | } 12 | 13 | pub(crate) static mut MAIN_ARGS: MainArgs = MainArgs { 14 | argc: 0, 15 | argv: null_mut(), 16 | envp: null_mut(), 17 | }; 18 | 19 | unsafe impl Send for MainArgs {} 20 | unsafe impl Sync for MainArgs {} 21 | 22 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 23 | pub enum VarError { 24 | NotPresent, 25 | NotUnicode, 26 | } 27 | 28 | pub fn var>(key: K) -> Result<&'static str, VarError> { 29 | unsafe { 30 | let mut ptr = MAIN_ARGS.envp; 31 | let key_bytes = key.as_ref().as_bytes(); 32 | loop { 33 | let env = *ptr; 34 | if env.is_null() { 35 | break; 36 | } 37 | let mut c = env; 38 | while *c != b'=' { 39 | c = c.add(1); 40 | } 41 | if key_bytes 42 | == slice::from_raw_parts(env.cast::(), c.offset_from(env).try_into().unwrap()) 43 | { 44 | return str::from_utf8(CStr::from_ptr(c.add(1).cast()).to_bytes()) 45 | .map_err(|_| VarError::NotUnicode); 46 | } 47 | ptr = ptr.add(1); 48 | } 49 | } 50 | Err(VarError::NotPresent) 51 | } 52 | 53 | pub fn args() -> Args { 54 | Args { pos: 0 } 55 | } 56 | 57 | pub struct Args { 58 | pos: usize, 59 | } 60 | 61 | impl Iterator for Args { 62 | type Item = &'static str; 63 | 64 | fn next(&mut self) -> Option { 65 | unsafe { 66 | if self.pos < MAIN_ARGS.argc as usize { 67 | let arg = MAIN_ARGS.argv.add(self.pos); 68 | self.pos += 1; 69 | let cstr = CStr::from_ptr(arg.read().cast()); 70 | return Some(core::str::from_utf8(cstr.to_bytes()).unwrap()); 71 | } 72 | } 73 | None 74 | } 75 | } 76 | 77 | impl ExactSizeIterator for Args { 78 | fn len(&self) -> usize { 79 | unsafe { MAIN_ARGS.argc as usize - self.pos } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![no_std] 3 | 4 | #[cfg(feature = "alloc")] 5 | extern crate alloc as alloc_crate; 6 | 7 | // Ensure that origin is linked in. 8 | extern crate origin; 9 | 10 | // 11 | #[cfg(feature = "alloc")] 12 | #[global_allocator] 13 | static GLOBAL_ALLOCATOR: rustix_dlmalloc::GlobalDlmalloc = rustix_dlmalloc::GlobalDlmalloc; 14 | 15 | // Origin calls this. 16 | #[no_mangle] 17 | unsafe fn origin_main(argc: i32, argv: *mut *mut u8, envp: *mut *mut u8) -> i32 { 18 | let _ = (argc, argv, envp); 19 | 20 | #[cfg(feature = "std")] 21 | unsafe { 22 | crate::init::sanitize_stdio_fds(); 23 | crate::init::store_args(argc, argv, envp); 24 | } 25 | unsafe { 26 | crate::init::reset_sigpipe(); 27 | #[cfg(feature = "stack-overflow")] 28 | crate::stack_overflow::init(); 29 | } 30 | 31 | // Call the function expanded by the macro in the user's module to call the 32 | // user's `main` function. 33 | extern "C" { 34 | fn origin_studio_no_problem(); 35 | } 36 | unsafe { 37 | origin_studio_no_problem(); 38 | } 39 | 40 | rustix::runtime::EXIT_SUCCESS 41 | } 42 | 43 | /// 🌟 44 | #[cfg(not(feature = "alloc"))] 45 | #[macro_export] 46 | macro_rules! no_problem { 47 | () => { 48 | #[doc(hidden)] 49 | #[no_mangle] 50 | extern "C" fn origin_studio_no_problem() { 51 | // Call the user's `main` function. 52 | main() 53 | } 54 | }; 55 | } 56 | 57 | /// 🌟 58 | #[cfg(all(feature = "alloc", not(feature = "std")))] 59 | #[macro_export] 60 | macro_rules! no_problem { 61 | () => { 62 | extern crate alloc; 63 | 64 | #[doc(hidden)] 65 | #[no_mangle] 66 | extern "C" fn origin_studio_no_problem() { 67 | // Call the user's `main` function. 68 | main() 69 | } 70 | }; 71 | } 72 | 73 | /// 🌟 74 | #[cfg(feature = "std")] 75 | #[macro_export] 76 | macro_rules! no_problem { 77 | () => { 78 | extern crate alloc; 79 | 80 | #[doc(hidden)] 81 | #[no_mangle] 82 | extern "C" fn origin_studio_no_problem() { 83 | // Call the user's `main` function. 84 | main() 85 | } 86 | 87 | // Provide a prelude. 88 | use ::alloc::{format, vec}; 89 | use $crate::prelude::rust_2021::*; 90 | use $crate::{self as std, eprint, eprintln, print, println}; 91 | }; 92 | } 93 | 94 | mod init; 95 | #[cfg(feature = "stack-overflow")] 96 | mod stack_overflow; 97 | 98 | // Provide a std-like API. 99 | 100 | #[cfg(feature = "std")] 101 | mod macros; 102 | 103 | #[cfg(feature = "std")] 104 | pub mod env; 105 | #[cfg(feature = "std")] 106 | #[cfg(feature = "fs")] 107 | pub mod fs; 108 | #[cfg(feature = "std")] 109 | pub mod io; 110 | #[cfg(feature = "std")] 111 | pub mod prelude; 112 | #[cfg(feature = "std")] 113 | #[cfg(feature = "thread")] 114 | pub mod sync; 115 | #[cfg(feature = "std")] 116 | #[cfg(feature = "thread")] 117 | pub mod thread; 118 | 119 | #[cfg(feature = "alloc")] 120 | pub use alloc_crate::{ 121 | alloc, borrow, boxed, collections, ffi, fmt, rc, slice, str, string, task, vec, 122 | }; 123 | pub use core::*; 124 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "origin-studio" 3 | version = "0.16.0" 4 | authors = [ 5 | "Dan Gohman ", 6 | ] 7 | description = "An alternative `std`-like implementation built on origin" 8 | documentation = "https://docs.rs/origin-studio" 9 | license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" 10 | repository = "https://github.com/sunfishcode/origin-studio" 11 | edition = "2021" 12 | keywords = ["linux"] 13 | categories = ["no-std"] 14 | 15 | [dependencies] 16 | origin = { version = "0.25.1", default-features = false, features = ["origin-start", "signal", "nightly"] } 17 | rustix = { version = "1.0.0", default-features = false, optional = true } 18 | rustix-dlmalloc = { version = "0.2.0", features = ["global"], optional = true } 19 | rustix-futex-sync = { version = "0.3.0", features = ["atomic_usize"], optional = true } 20 | atomic-dbg = { version = "0.1.11", default-features = false, optional = true } 21 | 22 | [dev-dependencies] 23 | libc = { version = "0.2.148", default-features = false } 24 | errno = { version = "0.3.3", default-features = false } 25 | 26 | [features] 27 | default = ["std", "thread", "stack-overflow", "panic-handler", "eh-personality"] 28 | 29 | # Provide a `std`-like API. 30 | std = ["alloc", "rustix/stdio", "fs"] 31 | 32 | # Provide the `alloc` API. 33 | alloc = ["rustix-dlmalloc", "origin/alloc"] 34 | 35 | # Support threads 36 | thread = ["origin/thread", "rustix-futex-sync"] 37 | 38 | # Enable highly experimental filesystem API support. 39 | fs = ["rustix/fs"] 40 | 41 | # Enable debug logging. 42 | log = ["origin/log"] 43 | 44 | # Enable Rust's stack overflow reporting code. 45 | stack-overflow = ["rustix/mm", "rustix/param", "origin/thread"] 46 | 47 | # Enable highly experimental support for performing startup-time relocations, 48 | # needed to support statically-linked PIE executables. 49 | experimental-relocate = ["origin/experimental-relocate"] 50 | 51 | # Provide a `#[lang = eh_personality]` function suitable for unwinding (for 52 | # no-std). 53 | # 54 | # If you know your program never unwinds and want smaller code size, use 55 | # "eh-personality-continue" instead. 56 | # 57 | # This is only needed in no-std builds, as std provides a personality. See 58 | # [the "personality" feature of the unwinding crate] for more details. 59 | # 60 | # [the "personality" feature of the unwinding crate]: https://crates.io/crates/unwinding#personality-and-other-utilities 61 | eh-personality = ["origin/eh-personality"] 62 | 63 | # Provide a `#[lang = eh_personality]` function that just returns 64 | # `CONTINUE_UNWIND` (for no-std). Use this if you know your program will never 65 | # unwind and don't want any extra code. 66 | eh-personality-continue = ["origin/eh-personality-continue"] 67 | 68 | # Provide a `#[panic_handler]` function suitable for unwinding (for no-std). 69 | # 70 | # If you know your program never panics and want smaller code size, use 71 | # "panic-handler-trap" instead. 72 | # 73 | # This is only needed in no-std builds, as std provides a panic handler. See 74 | # [the "panic-handler" feature of the unwinding crate] for more details. 75 | # 76 | # [the "panic-handler" feature of the unwinding crate]: https://crates.io/crates/unwinding#personality-and-other-utilities 77 | panic-handler = ["origin/panic-handler"] 78 | 79 | # Provide a `#[panic_handler]` function that just traps (for no-std). Use this 80 | # if you know your program will never panic and don't want any extra code. 81 | panic-handler-trap = ["origin/panic-handler-trap"] 82 | -------------------------------------------------------------------------------- /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/origin-studio/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 | -------------------------------------------------------------------------------- /src/thread.rs: -------------------------------------------------------------------------------- 1 | //! Native threads. 2 | 3 | use crate::boxed::Box; 4 | use crate::io; 5 | use core::mem::forget; 6 | use core::num::NonZeroUsize; 7 | use core::ptr::{null_mut, NonNull}; 8 | 9 | // Rust does't need the OS tids, it just needs unique ids, so we just use the 10 | // raw `Thread` value casted to `usize`. 11 | #[allow(dead_code)] // TODO: obviate this 12 | pub struct ThreadId(usize); 13 | 14 | pub struct Thread(origin::thread::Thread); 15 | 16 | impl Thread { 17 | pub fn id(&self) -> ThreadId { 18 | ThreadId(self.0.to_raw().addr()) 19 | } 20 | } 21 | 22 | pub struct JoinHandle(Thread); 23 | 24 | impl JoinHandle { 25 | pub fn join(self) -> io::Result<()> { 26 | unsafe { 27 | origin::thread::join(self.0 .0); 28 | } 29 | 30 | // Don't call drop, which would detach the thread we just joined. 31 | forget(self); 32 | 33 | Ok(()) 34 | } 35 | } 36 | 37 | impl Drop for JoinHandle { 38 | fn drop(&mut self) { 39 | unsafe { 40 | origin::thread::detach(self.0 .0); 41 | } 42 | } 43 | } 44 | 45 | pub fn spawn(f: F) -> JoinHandle 46 | where 47 | F: FnOnce() + Send + 'static, 48 | { 49 | // Pack up the closure. 50 | let boxed: Box = Box::new(move || { 51 | #[cfg(feature = "stack-overflow")] 52 | let _handler = unsafe { crate::stack_overflow::Handler::new() }; 53 | 54 | f() 55 | }); 56 | 57 | // We could avoid double boxing by enabling the unstable `ptr_metadata` 58 | // feature, using `.to_raw_parts()` on the box pointer, though it does 59 | // also require transmuting the metadata into `*mut c_void` and back. 60 | /* 61 | let raw: *mut (dyn FnOnce() + Send + 'static) = Box::into_raw(boxed); 62 | let (callee, metadata) = raw.to_raw_parts(); 63 | let args = [ 64 | NonNull::new(callee as _), 65 | NonNull::new(unsafe { transmute(metadata) }), 66 | ]; 67 | */ 68 | let boxed = Box::new(boxed); 69 | let raw: *mut Box = Box::into_raw(boxed); 70 | let args = [NonNull::new(raw.cast())]; 71 | 72 | let thread = unsafe { 73 | let r = origin::thread::create( 74 | move |args| { 75 | // Unpack and call. 76 | /* 77 | let (callee, metadata) = (args[0], args[1]); 78 | let raw: *mut (dyn FnOnce() + Send + 'static) = 79 | ptr::from_raw_parts_mut(transmute(callee), transmute(metadata)); 80 | let boxed = Box::from_raw(raw); 81 | boxed(); 82 | */ 83 | let raw: *mut Box = match args[0] { 84 | Some(raw) => raw.as_ptr().cast(), 85 | None => null_mut(), 86 | }; 87 | let boxed: Box> = Box::from_raw(raw); 88 | (*boxed)(); 89 | 90 | None 91 | }, 92 | &args, 93 | origin::thread::default_stack_size(), 94 | origin::thread::default_guard_size(), 95 | ); 96 | r.unwrap() 97 | }; 98 | 99 | JoinHandle(Thread(thread)) 100 | } 101 | 102 | pub fn current() -> Thread { 103 | Thread(origin::thread::current()) 104 | } 105 | 106 | pub(crate) struct GetThreadId; 107 | 108 | unsafe impl rustix_futex_sync::lock_api::GetThreadId for GetThreadId { 109 | const INIT: Self = Self; 110 | 111 | fn nonzero_thread_id(&self) -> NonZeroUsize { 112 | origin::thread::current().to_raw_non_null().addr() 113 | } 114 | } 115 | 116 | pub(crate) type ReentrantMutex = rustix_futex_sync::ReentrantMutex; 117 | pub(crate) type ReentrantMutexGuard<'a, T> = 118 | rustix_futex_sync::ReentrantMutexGuard<'a, GetThreadId, T>; 119 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

Origin Studio

3 | 4 |

5 | An alternative `std`-like implementation built on Origin 6 |

7 | 8 |

9 | Github Actions CI Status 10 | zulip chat 11 | crates.io page 12 | docs.rs docs 13 |

14 |
15 | 16 | Origin Stdio is an alternative [`std`]-like implementation built on [`origin`]. 17 | 18 | At this time, it only works on Linux (x86-64, aarch64, riscv64, 32-bit x86), 19 | requires Rust nightly, lacks full `std` compatibility, and is overall 20 | experimental. But it supports threads and stuff. 21 | 22 | ## Quick start 23 | 24 | In an empty directory, on Linux, with Rust nightly, run these commands: 25 | ```sh 26 | cargo init 27 | cargo add origin_studio 28 | echo 'fn main() { println!("cargo:rustc-link-arg=-nostartfiles"); }' > build.rs 29 | sed -i '1s/^/#![no_std]\n#![no_main]\norigin_studio::no_problem!();\n\n/' src/main.rs 30 | cargo run --quiet 31 | ``` 32 | 33 | This will produce a crate and print "Hello, world!". 34 | 35 | Yes, you might say, I could have already done that, with just the first and 36 | last commands. But this version uses `origin` to start and stop the program, 37 | and [`rustix`] to do the printing. 38 | 39 | And beyond that, Origin Studio uses `origin` to start and stop threads, 40 | [`rustix-futex-sync`] and [`lock_api`] to do locking for threads, 41 | [`rustix-dlmalloc`] to do memory allocation, and [`unwinding`] to do stack 42 | unwinding, so it doesn't use libc at all. 43 | 44 | ## What are those commands doing? 45 | 46 | > cargo init 47 | 48 | This creates a new Rust project containing a "Hello, world!" program. 49 | 50 | > cargo add origin_studio 51 | 52 | This adds a dependency on `origin_studio`, which is this crate. 53 | 54 | > echo 'fn main() { println!("cargo:rustc-link-arg=-nostartfiles"); }' > build.rs 55 | 56 | This creates a build.rs file that arranges for [`-nostartfiles`] to be passed 57 | to the link command, which disables the use of libc's `crt1.o` and other startup 58 | object files. This allows origin to define its own symbol named `_start` which 59 | serves as the program entrypoint, and handle the entire process of starting the 60 | program itself. 61 | 62 | [`-nostartfiles`]: https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html#index-nostartfiles 63 | 64 | > sed -i '1s/^/#![no_std]\n#![no_main]\norigin_studio::no_problem!();\n\n/' src/main.rs 65 | 66 | This inserts three lines to the top of src/main.rs: 67 | - `#![no_std]`, which disables the use of Rust's standard library 68 | implementation, since Origin Studio provides its own implementation that 69 | using rustix and origin. 70 | - `#![no_main]`, which tells Rust to disable its code that calls the user's 71 | `main` function, since Origin Studio will be handling that. 72 | - `origin_studio::no_problem!()` inserts code to set up a Rust panic handler, 73 | and optionally a global allocator (with the "alloc" feature). 74 | 75 | > cargo run --quiet 76 | 77 | This runs the program, which will be started by origin, prints "Hello, world!" 78 | using Origin Studio's `println!` macro, which uses Origin Studio's 79 | `std::io::stdout()` and `std::io::Write` and `rustix-futex-sync`'s `Mutex` to 80 | do the locking, and `rustix` to do the actual I/O system call, and ends the 81 | program, using origin. 82 | 83 | [rustix-futex-sync]: https://github.com/sunfishcode/rustix-futex-sync#readme 84 | 85 | ## Similar crates 86 | 87 | Other alternative implementations of std include [steed], [tiny-std] and 88 | [veneer]. 89 | 90 | [Mustang] and [Eyra] are crates that use origin to build a libc implementation 91 | that can slide underneath existing std builds, rather than having their own std 92 | implementations. 93 | 94 | [relibc] also includes a Rust implementation of program and thread startup and 95 | shutdown. 96 | 97 | ## Why? 98 | 99 | Right now, this is a demo of how to use `origin`. If you're interested in 100 | seeing this grow into something specific, or interested in seeing projects 101 | which might be inspired by this, please reach out! 102 | 103 | [`std`]: https://doc.rust-lang.org/stable/std/ 104 | [`origin`]: https://github.com/sunfishcode/origin#readme 105 | [`rustix`]: https://github.com/bytecodealliance/rustix#readme 106 | [`rustix-futex-sync`]: https://docs.rs/rustix-futex-sync/latest/rustix_futex_sync/ 107 | [`rustix-dlmalloc`]: https://docs.rs/rustix-dlmalloc/latest/rustix_dlmalloc/ 108 | [`lock_api`]: https://docs.rs/lock_api/latest/lock_api/ 109 | [`unwinding`]: https://docs.rs/unwinding/latest/unwinding/ 110 | [steed]: https://github.com/japaric/steed 111 | [tiny-std]: https://github.com/MarcusGrass/tiny-std 112 | [veneer]: https://crates.io/crates/veneer 113 | [Mustang]: https://github.com/sunfishcode/mustang#readme 114 | [Eyra]: https://github.com/sunfishcode/eyra#readme 115 | [relibc]: https://gitlab.redox-os.org/redox-os/relibc/ 116 | -------------------------------------------------------------------------------- /src/io.rs: -------------------------------------------------------------------------------- 1 | //! Traits, helpers, and type definitions for core I/O functionality. 2 | 3 | #[cfg(feature = "thread")] 4 | use crate::thread::{ReentrantMutex, ReentrantMutexGuard}; 5 | use core::fmt::{self, Arguments}; 6 | #[cfg(not(feature = "thread"))] 7 | use core::marker::PhantomData; 8 | 9 | pub type Error = rustix::io::Errno; 10 | 11 | pub type Result = core::result::Result; 12 | 13 | pub trait Read { 14 | fn read(&mut self, buf: &mut [u8]) -> Result; 15 | 16 | fn is_read_vectored(&self) -> bool { 17 | false 18 | } 19 | } 20 | 21 | pub trait Write { 22 | fn write(&mut self, buf: &[u8]) -> Result; 23 | 24 | fn is_write_vectored(&self) -> bool { 25 | false 26 | } 27 | 28 | fn flush(&mut self) -> Result<()>; 29 | 30 | fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { 31 | while !buf.is_empty() { 32 | match self.write(buf) { 33 | Ok(n) => buf = &buf[n..], 34 | Err(Error::INTR) => {} 35 | Err(err) => return Err(err), 36 | } 37 | } 38 | Ok(()) 39 | } 40 | 41 | fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()> { 42 | // Create a shim which translates a Write to a fmt::Write and saves 43 | // off I/O errors. instead of discarding them 44 | struct Adapter<'a, T: ?Sized + 'a> { 45 | inner: &'a mut T, 46 | error: Result<()>, 47 | } 48 | 49 | impl fmt::Write for Adapter<'_, T> { 50 | fn write_str(&mut self, s: &str) -> fmt::Result { 51 | match self.inner.write_all(s.as_bytes()) { 52 | Ok(()) => Ok(()), 53 | Err(e) => { 54 | self.error = Err(e); 55 | Err(fmt::Error) 56 | } 57 | } 58 | } 59 | } 60 | 61 | let mut output = Adapter { 62 | inner: self, 63 | error: Ok(()), 64 | }; 65 | match fmt::write(&mut output, fmt) { 66 | Ok(()) => Ok(()), 67 | Err(..) => { 68 | // check if the error came from the underlying `Write` or not 69 | if output.error.is_err() { 70 | output.error 71 | } else { 72 | Err(Error::IO) 73 | } 74 | } 75 | } 76 | } 77 | } 78 | 79 | pub struct StdoutLock<'a> { 80 | #[cfg(feature = "thread")] 81 | _lock: ReentrantMutexGuard<'a, ()>, 82 | 83 | #[cfg(not(feature = "thread"))] 84 | _phantom: PhantomData<&'a ()>, 85 | } 86 | 87 | #[cfg(feature = "thread")] 88 | static STDOUT_LOCK: ReentrantMutex<()> = ReentrantMutex::new(()); 89 | 90 | pub struct Stdout(()); 91 | 92 | pub fn stdout() -> Stdout { 93 | Stdout(()) 94 | } 95 | 96 | impl Stdout { 97 | pub fn lock(&self) -> StdoutLock<'static> { 98 | StdoutLock { 99 | #[cfg(feature = "thread")] 100 | _lock: STDOUT_LOCK.lock(), 101 | 102 | #[cfg(not(feature = "thread"))] 103 | _phantom: PhantomData, 104 | } 105 | } 106 | } 107 | 108 | impl Write for Stdout { 109 | #[cfg_attr(feature = "std", allow(unused_unsafe))] 110 | fn write(&mut self, buf: &[u8]) -> Result { 111 | rustix::io::write(unsafe { rustix::stdio::stdout() }, buf) 112 | } 113 | 114 | fn flush(&mut self) -> Result<()> { 115 | Ok(()) 116 | } 117 | } 118 | 119 | impl<'a> Write for StdoutLock<'a> { 120 | fn write(&mut self, buf: &[u8]) -> Result { 121 | Stdout(()).write(buf) 122 | } 123 | 124 | fn flush(&mut self) -> Result<()> { 125 | Stdout(()).flush() 126 | } 127 | } 128 | 129 | impl core::fmt::Write for Stdout { 130 | fn write_str(&mut self, s: &str) -> core::fmt::Result { 131 | match self.write_all(s.as_bytes()) { 132 | Ok(_) => Ok(()), 133 | Err(err) => panic!("failed printing to stdout: {:?}", err), 134 | } 135 | } 136 | } 137 | 138 | impl<'a> core::fmt::Write for StdoutLock<'a> { 139 | fn write_str(&mut self, s: &str) -> core::fmt::Result { 140 | Stdout(()).write_str(s) 141 | } 142 | } 143 | 144 | pub struct StderrLock<'a> { 145 | #[cfg(feature = "thread")] 146 | _lock: ReentrantMutexGuard<'a, ()>, 147 | 148 | #[cfg(not(feature = "thread"))] 149 | _phantom: PhantomData<&'a ()>, 150 | } 151 | 152 | #[cfg(feature = "thread")] 153 | static STDERR_LOCK: ReentrantMutex<()> = ReentrantMutex::new(()); 154 | 155 | pub struct Stderr(()); 156 | 157 | pub fn stderr() -> Stderr { 158 | Stderr(()) 159 | } 160 | 161 | impl Stderr { 162 | pub fn lock(&self) -> StderrLock<'static> { 163 | StderrLock { 164 | #[cfg(feature = "thread")] 165 | _lock: STDERR_LOCK.lock(), 166 | 167 | #[cfg(not(feature = "thread"))] 168 | _phantom: PhantomData, 169 | } 170 | } 171 | } 172 | 173 | impl Write for Stderr { 174 | #[cfg_attr(feature = "std", allow(unused_unsafe))] 175 | fn write(&mut self, buf: &[u8]) -> Result { 176 | rustix::io::write(unsafe { rustix::stdio::stderr() }, buf) 177 | } 178 | 179 | fn flush(&mut self) -> Result<()> { 180 | Ok(()) 181 | } 182 | } 183 | 184 | impl<'a> Write for StderrLock<'a> { 185 | fn write(&mut self, buf: &[u8]) -> Result { 186 | Stderr(()).write(buf) 187 | } 188 | 189 | fn flush(&mut self) -> Result<()> { 190 | Stderr(()).flush() 191 | } 192 | } 193 | 194 | impl core::fmt::Write for Stderr { 195 | fn write_str(&mut self, s: &str) -> core::fmt::Result { 196 | match self.write_all(s.as_bytes()) { 197 | Ok(_) => Ok(()), 198 | Err(err) => panic!("failed printing to stderr: {:?}", err), 199 | } 200 | } 201 | } 202 | 203 | impl<'a> core::fmt::Write for StderrLock<'a> { 204 | fn write_str(&mut self, s: &str) -> core::fmt::Result { 205 | Stderr(()).write_str(s) 206 | } 207 | } 208 | 209 | pub trait Seek { 210 | fn seek(&mut self, pos: SeekFrom) -> Result; 211 | 212 | fn rewind(&mut self) -> Result<()> { 213 | self.seek(SeekFrom::Start(0))?; 214 | Ok(()) 215 | } 216 | 217 | fn stream_position(&mut self) -> Result { 218 | self.seek(SeekFrom::Current(0)) 219 | } 220 | } 221 | 222 | #[derive(Copy, Clone, Eq, PartialEq, Debug)] 223 | pub enum SeekFrom { 224 | Start(u64), 225 | End(i64), 226 | Current(i64), 227 | } 228 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/stack_overflow.rs: -------------------------------------------------------------------------------- 1 | //! The following is derived from Rust's 2 | //! library/std/src/sys/unix/stack_overflow.rs at revision 3 | //! 3e35b39d9dbfcd937c6b9163a3514d6a4775c198. 4 | 5 | macro_rules! rtprintpanic { 6 | ($($t:tt)*) => { 7 | #[cfg(feature = "std")] 8 | let _ = $crate::io::Write::write_fmt(&mut $crate::io::stderr(), format_args!($($t)*)); 9 | } 10 | } 11 | 12 | macro_rules! rtabort { 13 | ($($t:tt)*) => { 14 | { 15 | rtprintpanic!("fatal runtime error: {}\n", format_args!($($t)*)); 16 | origin::program::trap(); 17 | } 18 | } 19 | } 20 | 21 | use core::ffi::c_void; 22 | 23 | pub(crate) struct Handler { 24 | data: *mut c_void, 25 | } 26 | 27 | impl Handler { 28 | pub(crate) unsafe fn new() -> Handler { 29 | make_handler() 30 | } 31 | 32 | fn null() -> Handler { 33 | Handler { 34 | data: core::ptr::null_mut(), 35 | } 36 | } 37 | } 38 | 39 | impl Drop for Handler { 40 | fn drop(&mut self) { 41 | unsafe { 42 | drop_handler(self.data); 43 | } 44 | } 45 | } 46 | 47 | use core::{mem, ptr}; 48 | 49 | use origin::signal::{ 50 | sigaction, Sigaction, SigactionFlags, Siginfo, Signal, SIGSTKSZ, SIG_DFL, SS_DISABLE, 51 | }; 52 | use rustix::mm::{mmap_anonymous, munmap, MapFlags, ProtFlags}; 53 | use rustix::runtime::kernel_sigaltstack; 54 | 55 | use core::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; 56 | use rustix::param::page_size; 57 | 58 | // Signal handler for the SIGSEGV and SIGBUS handlers. We've got guard pages 59 | // (unmapped pages) at the end of every thread's stack, so if a thread ends 60 | // up running into the guard page it'll trigger this handler. We want to 61 | // detect these cases and print out a helpful error saying that the stack 62 | // has overflowed. All other signals, however, should go back to what they 63 | // were originally supposed to do. 64 | // 65 | // This handler currently exists purely to print an informative message 66 | // whenever a thread overflows its stack. We then abort to exit and 67 | // indicate a crash, but to avoid a misleading SIGSEGV that might lead 68 | // users to believe that unsafe code has accessed an invalid pointer; the 69 | // SIGSEGV encountered when overflowing the stack is expected and 70 | // well-defined. 71 | // 72 | // If this is not a stack overflow, the handler un-registers itself and 73 | // then returns (to allow the original signal to be delivered again). 74 | // Returning from this kind of signal handler is technically not defined 75 | // to work when reading the POSIX spec strictly, but in practice it turns 76 | // out many large systems and all implementations allow returning from a 77 | // signal handler to work. For a more detailed explanation see the 78 | // comments on #26458. 79 | unsafe extern "C" fn signal_handler(signum: Signal, info: *mut Siginfo, _data: *mut c_void) { 80 | let (stack_addr, _stack_size, guard_size) = origin::thread::stack(origin::thread::current()); 81 | let guard_end = stack_addr.addr(); 82 | let guard_start = guard_end - guard_size; 83 | 84 | let addr = (*info) 85 | .__bindgen_anon_1 86 | .__bindgen_anon_1 87 | ._sifields 88 | ._sigfault 89 | ._addr 90 | .addr(); 91 | 92 | // If the faulting address is within the guard page, then we print a 93 | // message saying so and abort. 94 | if guard_start <= addr && addr < guard_end { 95 | rtprintpanic!( 96 | "\nthread '{}' has overflowed its stack\n", 97 | rustix::thread::name() 98 | .map(|c_str| alloc_crate::format!("{:?}", c_str)) 99 | .unwrap_or("".into()) 100 | ); 101 | rtabort!("stack overflow"); 102 | } else { 103 | // Unregister ourselves by reverting back to the default behavior. 104 | let mut action: Sigaction = mem::zeroed(); 105 | action.sa_handler_kernel = SIG_DFL; 106 | let _ = sigaction(signum, Some(action)); 107 | 108 | // See comment above for why this function returns. 109 | } 110 | } 111 | 112 | static MAIN_ALTSTACK: AtomicPtr = AtomicPtr::new(ptr::null_mut()); 113 | static NEED_ALTSTACK: AtomicBool = AtomicBool::new(false); 114 | 115 | pub unsafe fn init() { 116 | for &signal in &[Signal::SEGV, Signal::BUS] { 117 | let mut action = sigaction(signal, None).unwrap(); 118 | // Configure our signal handler if one is not already set. Ignore 119 | // the warnings about unpredictability since `SigDfl` isn't a real 120 | // function anyway. 121 | #[allow(unpredictable_function_pointer_comparisons)] 122 | if action.sa_handler_kernel == SIG_DFL { 123 | action.sa_flags = SigactionFlags::SIGINFO | SigactionFlags::ONSTACK; 124 | action.sa_handler_kernel = Some(mem::transmute( 125 | signal_handler as unsafe extern "C" fn(_, _, _), 126 | )); 127 | let _ = sigaction(signal, Some(action)); 128 | NEED_ALTSTACK.store(true, Ordering::Relaxed); 129 | } 130 | } 131 | 132 | let handler = make_handler(); 133 | MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed); 134 | mem::forget(handler); 135 | } 136 | 137 | // Calling the cleanup function isn't necessary. 138 | /* 139 | pub unsafe fn cleanup() { 140 | drop_handler(MAIN_ALTSTACK.load(Ordering::Relaxed)); 141 | } 142 | */ 143 | 144 | unsafe fn get_stackp() -> *mut c_void { 145 | // OpenBSD requires this flag for stack mapping 146 | // otherwise the said mapping will fail as a no-op on most systems 147 | // and has a different meaning on FreeBSD 148 | #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "linux"))] 149 | let flags = MapFlags::PRIVATE | MapFlags::STACK; 150 | #[cfg(not(any(target_os = "openbsd", target_os = "netbsd", target_os = "linux")))] 151 | let flags = MapFlags::PRIVATE; 152 | let stackp = match mmap_anonymous( 153 | ptr::null_mut(), 154 | SIGSTKSZ + page_size(), 155 | ProtFlags::READ | ProtFlags::WRITE, 156 | flags, 157 | ) { 158 | Ok(stackp) => stackp, 159 | Err(err) => panic!("failed to allocate an alternative stack: {}", err), 160 | }; 161 | match rustix::mm::mprotect(stackp, page_size(), rustix::mm::MprotectFlags::empty()) { 162 | Ok(guard_result) => guard_result, 163 | Err(err) => panic!("failed to set up alternative stack guard page: {}", err), 164 | }; 165 | stackp.add(page_size()) 166 | } 167 | 168 | unsafe fn get_stack() -> rustix::runtime::Stack { 169 | rustix::runtime::Stack { 170 | ss_sp: get_stackp(), 171 | ss_flags: 0, 172 | ss_size: SIGSTKSZ as _, 173 | } 174 | } 175 | 176 | unsafe fn make_handler() -> Handler { 177 | if !NEED_ALTSTACK.load(Ordering::Relaxed) { 178 | return Handler::null(); 179 | } 180 | let mut stack = kernel_sigaltstack(None).unwrap(); 181 | // Configure alternate signal stack, if one is not already set. 182 | if stack.ss_flags & SS_DISABLE != 0 { 183 | stack = get_stack(); 184 | let _ = kernel_sigaltstack(Some(stack)).unwrap(); 185 | Handler { 186 | data: stack.ss_sp as *mut c_void, 187 | } 188 | } else { 189 | Handler::null() 190 | } 191 | } 192 | 193 | unsafe fn drop_handler(data: *mut c_void) { 194 | if !data.is_null() { 195 | let stack = rustix::runtime::Stack { 196 | ss_sp: ptr::null_mut(), 197 | ss_flags: SS_DISABLE, 198 | // Workaround for bug in macOS implementation of sigaltstack 199 | // UNIX2003 which returns ENOMEM when disabling a stack while 200 | // passing ss_size smaller than MINSIGSTKSZ. According to POSIX 201 | // both ss_sp and ss_size should be ignored in this case. 202 | ss_size: SIGSTKSZ as _, 203 | }; 204 | let _ = kernel_sigaltstack(Some(stack)); 205 | // We know from `get_stackp` that the alternate stack we installed is part of a 206 | // mapping that started one page earlier, so walk back a page and unmap 207 | // from there. 208 | let _ = munmap(data.sub(page_size()), SIGSTKSZ + page_size()); 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /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-Apache-2.0_WITH_LLVM-exception: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | 205 | --- LLVM Exceptions to the Apache 2.0 License ---- 206 | 207 | As an exception, if, as a result of your compiling your source code, portions 208 | of this Software are embedded into an Object form of such source code, you 209 | may redistribute such embedded portions in such Object form without complying 210 | with the conditions of Sections 4(a), 4(b) and 4(d) of the License. 211 | 212 | In addition, if you combine or link compiled forms of this Software with 213 | software that is licensed under the GPLv2 ("Combined Software") and if a 214 | court of competent jurisdiction determines that the patent provision (Section 215 | 3), the indemnity provision (Section 9) or other Section of the License 216 | conflicts with the conditions of the GPLv2, you may retroactively and 217 | prospectively choose to deem waived or otherwise exclude such Section(s) of 218 | the License, but only in their entirety and only with respect to the Combined 219 | Software. 220 | 221 | --------------------------------------------------------------------------------