From c288cb1f7437ab052613409f34b03afbdf30eeff Mon Sep 17 00:00:00 2001 From: bohan Date: Sat, 13 Jan 2024 21:05:41 +0800 Subject: store the segment name when resolution fails --- compiler/rustc_resolve/src/diagnostics.rs | 17 ++++------- compiler/rustc_resolve/src/ident.rs | 44 +++++++++++------------------ compiler/rustc_resolve/src/imports.rs | 3 +- compiler/rustc_resolve/src/late.rs | 3 +- compiler/rustc_resolve/src/lib.rs | 15 ++++++++-- compiler/rustc_resolve/src/macros.rs | 2 +- tests/ui/cfg/diagnostics-cross-crate.rs | 2 +- tests/ui/cfg/diagnostics-cross-crate.stderr | 8 +++++- tests/ui/cfg/diagnostics-same-crate.rs | 3 +- tests/ui/cfg/diagnostics-same-crate.stderr | 12 ++++++-- 10 files changed, 58 insertions(+), 51 deletions(-) diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 0d744238eeb..b5700661385 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -786,7 +786,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => { self.dcx().create_err(errs::SelfImportOnlyInImportListWithNonEmptyPrefix { span }) } - ResolutionError::FailedToResolve { last_segment, label, suggestion, module } => { + ResolutionError::FailedToResolve { segment, label, suggestion, module } => { let mut err = struct_span_code_err!(self.dcx(), span, E0433, "failed to resolve: {}", &label); err.span_label(span, label); @@ -801,9 +801,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if let Some(ModuleOrUniformRoot::Module(module)) = module && let Some(module) = module.opt_def_id() - && let Some(last_segment) = last_segment + && let Some(segment) = segment { - self.find_cfg_stripped(&mut err, &last_segment, module); + self.find_cfg_stripped(&mut err, &segment, module); } err @@ -981,12 +981,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error( span, - ResolutionError::FailedToResolve { - last_segment: None, - label, - suggestion, - module: None, - }, + ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None }, ), VisResolutionError::ExpectedFound(span, path_str, res) => { self.dcx().create_err(errs::ExpectedFound { span, res, path_str }) @@ -2450,7 +2445,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { pub(crate) fn find_cfg_stripped( &mut self, err: &mut Diagnostic, - last_segment: &Symbol, + segment: &Symbol, module: DefId, ) { let local_items; @@ -2469,7 +2464,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { }; for &StrippedCfgItem { parent_module, name, ref cfg } in symbols { - if parent_module != module || name.name != *last_segment { + if parent_module != module || name.name != *segment { continue; } diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 3a31addb109..7fb9db16e9c 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -1381,13 +1381,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { continue; } } - return PathResult::failed( - ident.span, - false, - finalize.is_some(), - module, - || ("there are too many leading `super` keywords".to_string(), None), - ); + return PathResult::failed(ident, false, finalize.is_some(), module, || { + ("there are too many leading `super` keywords".to_string(), None) + }); } if segment_idx == 0 { if name == kw::SelfLower { @@ -1419,7 +1415,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // Report special messages for path segment keywords in wrong positions. if ident.is_path_segment_keyword() && segment_idx != 0 { - return PathResult::failed(ident.span, false, finalize.is_some(), module, || { + return PathResult::failed(ident, false, finalize.is_some(), module, || { let name_str = if name == kw::PathRoot { "crate root".to_string() } else { @@ -1515,7 +1511,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { )); } else { return PathResult::failed( - ident.span, + ident, is_last, finalize.is_some(), module, @@ -1541,24 +1537,18 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } - return PathResult::failed( - ident.span, - is_last, - finalize.is_some(), - module, - || { - self.report_path_resolution_error( - path, - opt_ns, - parent_scope, - ribs, - ignore_binding, - module, - segment_idx, - ident, - ) - }, - ); + return PathResult::failed(ident, is_last, finalize.is_some(), module, || { + self.report_path_resolution_error( + path, + opt_ns, + parent_scope, + ribs, + ignore_binding, + module, + segment_idx, + ident, + ) + }); } } } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 2ebf4c20562..f846dbec2c6 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -886,6 +886,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { PathResult::Failed { is_error_from_last_segment: false, span, + segment_name, label, suggestion, module, @@ -895,7 +896,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.report_error( span, ResolutionError::FailedToResolve { - last_segment: None, + segment: Some(segment_name), label, suggestion, module, diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index b9e603a4992..82f50227911 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -4054,11 +4054,12 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { label, suggestion, module, + segment_name, } => { return Err(respan( span, ResolutionError::FailedToResolve { - last_segment: None, + segment: Some(segment_name), label, suggestion, module, diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 0adea65ee58..90aa7d79bf0 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -213,7 +213,7 @@ enum ResolutionError<'a> { SelfImportOnlyInImportListWithNonEmptyPrefix, /// Error E0433: failed to resolve. FailedToResolve { - last_segment: Option, + segment: Option, label: String, suggestion: Option, module: Option>, @@ -396,12 +396,14 @@ enum PathResult<'a> { suggestion: Option, is_error_from_last_segment: bool, module: Option>, + /// The segment name of target + segment_name: Symbol, }, } impl<'a> PathResult<'a> { fn failed( - span: Span, + ident: Ident, is_error_from_last_segment: bool, finalize: bool, module: Option>, @@ -409,7 +411,14 @@ impl<'a> PathResult<'a> { ) -> PathResult<'a> { let (label, suggestion) = if finalize { label_and_suggestion() } else { (String::new(), None) }; - PathResult::Failed { span, label, suggestion, is_error_from_last_segment, module } + PathResult::Failed { + span: ident.span, + segment_name: ident.name, + label, + suggestion, + is_error_from_last_segment, + module, + } } } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 66ecaeb4449..aa9a02d7c44 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -779,7 +779,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.report_error( span, ResolutionError::FailedToResolve { - last_segment: path.last().map(|segment| segment.ident.name), + segment: path.last().map(|segment| segment.ident.name), label, suggestion, module, diff --git a/tests/ui/cfg/diagnostics-cross-crate.rs b/tests/ui/cfg/diagnostics-cross-crate.rs index d2725c94b08..ad4e47b7b2e 100644 --- a/tests/ui/cfg/diagnostics-cross-crate.rs +++ b/tests/ui/cfg/diagnostics-cross-crate.rs @@ -14,9 +14,9 @@ fn main() { // The module isn't found - we would like to get a diagnostic, but currently don't due to // the awkward way the resolver diagnostics are currently implemented. - // FIXME(Nilstrieb): Also add a note to the cfg diagnostic here cfged_out::inner::doesnt_exist::hello(); //~ ERROR failed to resolve //~^ NOTE could not find `doesnt_exist` in `inner` + //~| NOTE found an item that was configured out // It should find the one in the right module, not the wrong one. cfged_out::inner::right::meow(); //~ ERROR cannot find function diff --git a/tests/ui/cfg/diagnostics-cross-crate.stderr b/tests/ui/cfg/diagnostics-cross-crate.stderr index 046929bc260..8a238f36404 100644 --- a/tests/ui/cfg/diagnostics-cross-crate.stderr +++ b/tests/ui/cfg/diagnostics-cross-crate.stderr @@ -1,8 +1,14 @@ error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner` - --> $DIR/diagnostics-cross-crate.rs:18:23 + --> $DIR/diagnostics-cross-crate.rs:17:23 | LL | cfged_out::inner::doesnt_exist::hello(); | ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner` + | +note: found an item that was configured out + --> $DIR/auxiliary/cfged_out.rs:6:13 + | +LL | pub mod doesnt_exist { + | ^^^^^^^^^^^^ error[E0425]: cannot find function `uwu` in crate `cfged_out` --> $DIR/diagnostics-cross-crate.rs:7:16 diff --git a/tests/ui/cfg/diagnostics-same-crate.rs b/tests/ui/cfg/diagnostics-same-crate.rs index f76ace06a76..2d0907c6dfb 100644 --- a/tests/ui/cfg/diagnostics-same-crate.rs +++ b/tests/ui/cfg/diagnostics-same-crate.rs @@ -4,7 +4,7 @@ pub mod inner { //~^ NOTE found an item that was configured out #[cfg(FALSE)] - pub mod doesnt_exist { + pub mod doesnt_exist { //~ NOTE found an item that was configured out pub fn hello() {} } @@ -34,7 +34,6 @@ fn main() { // The module isn't found - we would like to get a diagnostic, but currently don't due to // the awkward way the resolver diagnostics are currently implemented. - // FIXME(Nilstrieb): Also add a note to the cfg diagnostic here inner::doesnt_exist::hello(); //~ ERROR failed to resolve //~| NOTE could not find `doesnt_exist` in `inner` diff --git a/tests/ui/cfg/diagnostics-same-crate.stderr b/tests/ui/cfg/diagnostics-same-crate.stderr index 30ee6479bd2..62a9d132de0 100644 --- a/tests/ui/cfg/diagnostics-same-crate.stderr +++ b/tests/ui/cfg/diagnostics-same-crate.stderr @@ -1,8 +1,14 @@ error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner` - --> $DIR/diagnostics-same-crate.rs:38:12 + --> $DIR/diagnostics-same-crate.rs:37:12 | LL | inner::doesnt_exist::hello(); | ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner` + | +note: found an item that was configured out + --> $DIR/diagnostics-same-crate.rs:7:13 + | +LL | pub mod doesnt_exist { + | ^^^^^^^^^^^^ error[E0425]: cannot find function `uwu` in module `inner` --> $DIR/diagnostics-same-crate.rs:32:12 @@ -17,7 +23,7 @@ LL | pub fn uwu() {} | ^^^ error[E0425]: cannot find function `meow` in module `inner::right` - --> $DIR/diagnostics-same-crate.rs:42:19 + --> $DIR/diagnostics-same-crate.rs:41:19 | LL | inner::right::meow(); | ^^^^ not found in `inner::right` @@ -36,7 +42,7 @@ LL | uwu(); | ^^^ not found in this scope error[E0425]: cannot find function `vanished` in this scope - --> $DIR/diagnostics-same-crate.rs:49:5 + --> $DIR/diagnostics-same-crate.rs:48:5 | LL | vanished(); | ^^^^^^^^ not found in this scope -- cgit 1.4.1-3-g733a5 From 994d11ace9b325ad3d32271ca86983112df5868f Mon Sep 17 00:00:00 2001 From: henrispriet Date: Thu, 21 Dec 2023 16:27:07 +0100 Subject: Move section "Installing from Source" to seperate file --- .reuse/dep5 | 1 + INSTALL.md | 253 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 253 +----------------------------------------------------------- 3 files changed, 256 insertions(+), 251 deletions(-) create mode 100644 INSTALL.md diff --git a/.reuse/dep5 b/.reuse/dep5 index e62e3504090..10ea8bcc49f 100644 --- a/.reuse/dep5 +++ b/.reuse/dep5 @@ -18,6 +18,7 @@ Files: compiler/* configure CONTRIBUTING.md COPYRIGHT + INSTALL.md LICENSE-APACHE LICENSE-MIT README.md diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000000..b872d317e36 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,253 @@ +# Installing from Source + +**Note: This document describes _building_ Rust _from source_. +This is _not recommended_ if you don't know what you're doing. +If you just want to install Rust, check out the [README.md](README.md) instead.** + +The Rust build system uses a Python script called `x.py` to build the compiler, +which manages the bootstrapping process. It lives at the root of the project. +It also uses a file named `config.toml` to determine various configuration +settings for the build. You can see a full list of options in +`config.example.toml`. + +The `x.py` command can be run directly on most Unix systems in the following +format: + +```sh +./x.py [flags] +``` + +This is how the documentation and examples assume you are running `x.py`. +See the [rustc dev guide][rustcguidebuild] if this does not work on your +platform. + +More information about `x.py` can be found by running it with the `--help` flag +or reading the [rustc dev guide][rustcguidebuild]. + +[gettingstarted]: https://rustc-dev-guide.rust-lang.org/getting-started.html +[rustcguidebuild]: https://rustc-dev-guide.rust-lang.org/building/how-to-build-and-run.html#what-is-xpy + +## Dependencies + +Make sure you have installed the dependencies: + +* `python` 3 or 2.7 +* `git` +* A C compiler (when building for the host, `cc` is enough; cross-compiling may + need additional compilers) +* `curl` (not needed on Windows) +* `pkg-config` if you are compiling on Linux and targeting Linux +* `libiconv` (already included with glibc on Debian-based distros) + +To build Cargo, you'll also need OpenSSL (`libssl-dev` or `openssl-devel` on +most Unix distros). + +If building LLVM from source, you'll need additional tools: + +* `g++`, `clang++`, or MSVC with versions listed on + [LLVM's documentation](https://llvm.org/docs/GettingStarted.html#host-c-toolchain-both-compiler-and-standard-library) +* `ninja`, or GNU `make` 3.81 or later (Ninja is recommended, especially on + Windows) +* `cmake` 3.13.4 or later +* `libstdc++-static` may be required on some Linux distributions such as Fedora + and Ubuntu + +On tier 1 or tier 2 with host tools platforms, you can also choose to download +LLVM by setting `llvm.download-ci-llvm = true`. +Otherwise, you'll need LLVM installed and `llvm-config` in your path. +See [the rustc-dev-guide for more info][sysllvm]. + +[sysllvm]: https://rustc-dev-guide.rust-lang.org/building/new-target.html#using-pre-built-llvm + + +## Building on a Unix-like system + +### Build steps + +1. Clone the [source] with `git`: + + ```sh + git clone https://github.com/rust-lang/rust.git + cd rust + ``` + +[source]: https://github.com/rust-lang/rust + +2. Configure the build settings: + + ```sh + ./configure + ``` + + If you plan to use `x.py install` to create an installation, it is + recommended that you set the `prefix` value in the `[install]` section to a + directory: `./configure --set install.prefix=` + +3. Build and install: + + ```sh + ./x.py build && ./x.py install + ``` + + When complete, `./x.py install` will place several programs into + `$PREFIX/bin`: `rustc`, the Rust compiler, and `rustdoc`, the + API-documentation tool. By default, it will also include [Cargo], Rust's + package manager. You can disable this behavior by passing + `--set build.extended=false` to `./configure`. + +[Cargo]: https://github.com/rust-lang/cargo + +### Configure and Make + +This project provides a configure script and makefile (the latter of which just +invokes `x.py`). `./configure` is the recommended way to programmatically +generate a `config.toml`. `make` is not recommended (we suggest using `x.py` +directly), but it is supported and we try not to break it unnecessarily. + +```sh +./configure +make && sudo make install +``` + +`configure` generates a `config.toml` which can also be used with normal `x.py` +invocations. + +## Building on Windows + +On Windows, we suggest using [winget] to install dependencies by running the +following in a terminal: + +```powershell +winget install -e Python.Python.3 +winget install -e Kitware.CMake +winget install -e Git.Git +``` + +Then edit your system's `PATH` variable and add: `C:\Program Files\CMake\bin`. +See +[this guide on editing the system `PATH`](https://www.java.com/en/download/help/path.html) +from the Java documentation. + +[winget]: https://github.com/microsoft/winget-cli + +There are two prominent ABIs in use on Windows: the native (MSVC) ABI used by +Visual Studio and the GNU ABI used by the GCC toolchain. Which version of Rust +you need depends largely on what C/C++ libraries you want to interoperate with. +Use the MSVC build of Rust to interop with software produced by Visual Studio +and the GNU build to interop with GNU software built using the MinGW/MSYS2 +toolchain. + +### MinGW + +[MSYS2][msys2] can be used to easily build Rust on Windows: + +[msys2]: https://www.msys2.org/ + +1. Download the latest [MSYS2 installer][msys2] and go through the installer. + +2. Run `mingw32_shell.bat` or `mingw64_shell.bat` from the MSYS2 installation + directory (e.g. `C:\msys64`), depending on whether you want 32-bit or 64-bit + Rust. (As of the latest version of MSYS2 you have to run `msys2_shell.cmd + -mingw32` or `msys2_shell.cmd -mingw64` from the command line instead.) + +3. From this terminal, install the required tools: + + ```sh + # Update package mirrors (may be needed if you have a fresh install of MSYS2) + pacman -Sy pacman-mirrors + + # Install build tools needed for Rust. If you're building a 32-bit compiler, + # then replace "x86_64" below with "i686". If you've already got Git, Python, + # or CMake installed and in PATH you can remove them from this list. + # Note that it is important that you do **not** use the 'python2', 'cmake', + # and 'ninja' packages from the 'msys2' subsystem. + # The build has historically been known to fail with these packages. + pacman -S git \ + make \ + diffutils \ + tar \ + mingw-w64-x86_64-python \ + mingw-w64-x86_64-cmake \ + mingw-w64-x86_64-gcc \ + mingw-w64-x86_64-ninja + ``` + +4. Navigate to Rust's source code (or clone it), then build it: + + ```sh + python x.py setup user && python x.py build && python x.py install + ``` + +### MSVC + +MSVC builds of Rust additionally require an installation of Visual Studio 2017 +(or later) so `rustc` can use its linker. The simplest way is to get +[Visual Studio], check the "C++ build tools" and "Windows 10 SDK" workload. + +[Visual Studio]: https://visualstudio.microsoft.com/downloads/ + +(If you're installing CMake yourself, be careful that "C++ CMake tools for +Windows" doesn't get included under "Individual components".) + +With these dependencies installed, you can build the compiler in a `cmd.exe` +shell with: + +```sh +python x.py setup user +python x.py build +``` + +Right now, building Rust only works with some known versions of Visual Studio. +If you have a more recent version installed and the build system doesn't +understand, you may need to force rustbuild to use an older version. +This can be done by manually calling the appropriate vcvars file before running +the bootstrap. + +```batch +CALL "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" +python x.py build +``` + +### Specifying an ABI + +Each specific ABI can also be used from either environment (for example, using +the GNU ABI in PowerShell) by using an explicit build triple. The available +Windows build triples are: +- GNU ABI (using GCC) + - `i686-pc-windows-gnu` + - `x86_64-pc-windows-gnu` +- The MSVC ABI + - `i686-pc-windows-msvc` + - `x86_64-pc-windows-msvc` + +The build triple can be specified by either specifying `--build=` when +invoking `x.py` commands, or by creating a `config.toml` file (as described in +[Building on a Unix-like system](#building-on-a-unix-like-system)), and passing +`--set build.build=` to `./configure`. + +## Building Documentation + +If you'd like to build the documentation, it's almost the same: + +```sh +./x.py doc +``` + +The generated documentation will appear under `doc` in the `build` directory for +the ABI used. That is, if the ABI was `x86_64-pc-windows-msvc`, the directory +will be `build\x86_64-pc-windows-msvc\doc`. + +## Notes + +Since the Rust compiler is written in Rust, it must be built by a precompiled +"snapshot" version of itself (made in an earlier stage of development). +As such, source builds require an Internet connection to fetch snapshots, and an +OS that can execute the available snapshot binaries. + +See https://doc.rust-lang.org/nightly/rustc/platform-support.html for a list of +supported platforms. +Only "host tools" platforms have a pre-compiled snapshot binary available; to +compile for a platform without host tools you must cross-compile. + +You may find that other platforms work, but these are our officially supported +build environments that are most likely to work. diff --git a/README.md b/README.md index 5d5beaf1b7a..da9e3556b4c 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,6 @@ If you wish to _contribute_ to the compiler, you should read Table of Contents - [Quick Start](#quick-start) -- [Installing from Source](#installing-from-source) -- [Building Documentation](#building-documentation) -- [Notes](#notes) - [Getting Help](#getting-help) - [Contributing](#contributing) - [License](#license) @@ -32,255 +29,9 @@ Read ["Installation"] from [The Book]. ["Installation"]: https://doc.rust-lang.org/book/ch01-01-installation.html [The Book]: https://doc.rust-lang.org/book/index.html -## Installing from Source +## Installing from source -The Rust build system uses a Python script called `x.py` to build the compiler, -which manages the bootstrapping process. It lives at the root of the project. -It also uses a file named `config.toml` to determine various configuration -settings for the build. You can see a full list of options in -`config.example.toml`. - -The `x.py` command can be run directly on most Unix systems in the following -format: - -```sh -./x.py [flags] -``` - -This is how the documentation and examples assume you are running `x.py`. -See the [rustc dev guide][rustcguidebuild] if this does not work on your -platform. - -More information about `x.py` can be found by running it with the `--help` flag -or reading the [rustc dev guide][rustcguidebuild]. - -[gettingstarted]: https://rustc-dev-guide.rust-lang.org/getting-started.html -[rustcguidebuild]: https://rustc-dev-guide.rust-lang.org/building/how-to-build-and-run.html#what-is-xpy - -### Dependencies - -Make sure you have installed the dependencies: - -* `python` 3 or 2.7 -* `git` -* A C compiler (when building for the host, `cc` is enough; cross-compiling may - need additional compilers) -* `curl` (not needed on Windows) -* `pkg-config` if you are compiling on Linux and targeting Linux -* `libiconv` (already included with glibc on Debian-based distros) - -To build Cargo, you'll also need OpenSSL (`libssl-dev` or `openssl-devel` on -most Unix distros). - -If building LLVM from source, you'll need additional tools: - -* `g++`, `clang++`, or MSVC with versions listed on - [LLVM's documentation](https://llvm.org/docs/GettingStarted.html#host-c-toolchain-both-compiler-and-standard-library) -* `ninja`, or GNU `make` 3.81 or later (Ninja is recommended, especially on - Windows) -* `cmake` 3.13.4 or later -* `libstdc++-static` may be required on some Linux distributions such as Fedora - and Ubuntu - -On tier 1 or tier 2 with host tools platforms, you can also choose to download -LLVM by setting `llvm.download-ci-llvm = true`. -Otherwise, you'll need LLVM installed and `llvm-config` in your path. -See [the rustc-dev-guide for more info][sysllvm]. - -[sysllvm]: https://rustc-dev-guide.rust-lang.org/building/new-target.html#using-pre-built-llvm - - -### Building on a Unix-like system - -#### Build steps - -1. Clone the [source] with `git`: - - ```sh - git clone https://github.com/rust-lang/rust.git - cd rust - ``` - -[source]: https://github.com/rust-lang/rust - -2. Configure the build settings: - - ```sh - ./configure - ``` - - If you plan to use `x.py install` to create an installation, it is - recommended that you set the `prefix` value in the `[install]` section to a - directory: `./configure --set install.prefix=` - -3. Build and install: - - ```sh - ./x.py build && ./x.py install - ``` - - When complete, `./x.py install` will place several programs into - `$PREFIX/bin`: `rustc`, the Rust compiler, and `rustdoc`, the - API-documentation tool. By default, it will also include [Cargo], Rust's - package manager. You can disable this behavior by passing - `--set build.extended=false` to `./configure`. - -[Cargo]: https://github.com/rust-lang/cargo - -#### Configure and Make - -This project provides a configure script and makefile (the latter of which just -invokes `x.py`). `./configure` is the recommended way to programmatically -generate a `config.toml`. `make` is not recommended (we suggest using `x.py` -directly), but it is supported and we try not to break it unnecessarily. - -```sh -./configure -make && sudo make install -``` - -`configure` generates a `config.toml` which can also be used with normal `x.py` -invocations. - -### Building on Windows - -On Windows, we suggest using [winget] to install dependencies by running the -following in a terminal: - -```powershell -winget install -e Python.Python.3 -winget install -e Kitware.CMake -winget install -e Git.Git -``` - -Then edit your system's `PATH` variable and add: `C:\Program Files\CMake\bin`. -See -[this guide on editing the system `PATH`](https://www.java.com/en/download/help/path.html) -from the Java documentation. - -[winget]: https://github.com/microsoft/winget-cli - -There are two prominent ABIs in use on Windows: the native (MSVC) ABI used by -Visual Studio and the GNU ABI used by the GCC toolchain. Which version of Rust -you need depends largely on what C/C++ libraries you want to interoperate with. -Use the MSVC build of Rust to interop with software produced by Visual Studio -and the GNU build to interop with GNU software built using the MinGW/MSYS2 -toolchain. - -#### MinGW - -[MSYS2][msys2] can be used to easily build Rust on Windows: - -[msys2]: https://www.msys2.org/ - -1. Download the latest [MSYS2 installer][msys2] and go through the installer. - -2. Run `mingw32_shell.bat` or `mingw64_shell.bat` from the MSYS2 installation - directory (e.g. `C:\msys64`), depending on whether you want 32-bit or 64-bit - Rust. (As of the latest version of MSYS2 you have to run `msys2_shell.cmd - -mingw32` or `msys2_shell.cmd -mingw64` from the command line instead.) - -3. From this terminal, install the required tools: - - ```sh - # Update package mirrors (may be needed if you have a fresh install of MSYS2) - pacman -Sy pacman-mirrors - - # Install build tools needed for Rust. If you're building a 32-bit compiler, - # then replace "x86_64" below with "i686". If you've already got Git, Python, - # or CMake installed and in PATH you can remove them from this list. - # Note that it is important that you do **not** use the 'python2', 'cmake', - # and 'ninja' packages from the 'msys2' subsystem. - # The build has historically been known to fail with these packages. - pacman -S git \ - make \ - diffutils \ - tar \ - mingw-w64-x86_64-python \ - mingw-w64-x86_64-cmake \ - mingw-w64-x86_64-gcc \ - mingw-w64-x86_64-ninja - ``` - -4. Navigate to Rust's source code (or clone it), then build it: - - ```sh - python x.py setup user && python x.py build && python x.py install - ``` - -#### MSVC - -MSVC builds of Rust additionally require an installation of Visual Studio 2017 -(or later) so `rustc` can use its linker. The simplest way is to get -[Visual Studio], check the "C++ build tools" and "Windows 10 SDK" workload. - -[Visual Studio]: https://visualstudio.microsoft.com/downloads/ - -(If you're installing CMake yourself, be careful that "C++ CMake tools for -Windows" doesn't get included under "Individual components".) - -With these dependencies installed, you can build the compiler in a `cmd.exe` -shell with: - -```sh -python x.py setup user -python x.py build -``` - -Right now, building Rust only works with some known versions of Visual Studio. -If you have a more recent version installed and the build system doesn't -understand, you may need to force rustbuild to use an older version. -This can be done by manually calling the appropriate vcvars file before running -the bootstrap. - -```batch -CALL "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" -python x.py build -``` - -#### Specifying an ABI - -Each specific ABI can also be used from either environment (for example, using -the GNU ABI in PowerShell) by using an explicit build triple. The available -Windows build triples are: -- GNU ABI (using GCC) - - `i686-pc-windows-gnu` - - `x86_64-pc-windows-gnu` -- The MSVC ABI - - `i686-pc-windows-msvc` - - `x86_64-pc-windows-msvc` - -The build triple can be specified by either specifying `--build=` when -invoking `x.py` commands, or by creating a `config.toml` file (as described in -[Building on a Unix-like system](#building-on-a-unix-like-system)), and passing -`--set build.build=` to `./configure`. - -## Building Documentation - -If you'd like to build the documentation, it's almost the same: - -```sh -./x.py doc -``` - -The generated documentation will appear under `doc` in the `build` directory for -the ABI used. That is, if the ABI was `x86_64-pc-windows-msvc`, the directory -will be `build\x86_64-pc-windows-msvc\doc`. - -## Notes - -Since the Rust compiler is written in Rust, it must be built by a precompiled -"snapshot" version of itself (made in an earlier stage of development). -As such, source builds require an Internet connection to fetch snapshots, and an -OS that can execute the available snapshot binaries. - -See https://doc.rust-lang.org/nightly/rustc/platform-support.html for a list of -supported platforms. -Only "host tools" platforms have a pre-compiled snapshot binary available; to -compile for a platform without host tools you must cross-compile. - -You may find that other platforms work, but these are our officially supported -build environments that are most likely to work. +If you really want to install from source (though this is not recommended), see [INSTALL.md](INSTALL.md). ## Getting Help -- cgit 1.4.1-3-g733a5 From cb052d57b36c554c4546765e25d377c2dbd5a77f Mon Sep 17 00:00:00 2001 From: joboet Date: Sat, 13 Jan 2024 18:30:44 +0100 Subject: std: move personality implementation out of PAL --- library/std/src/sys/mod.rs | 2 + library/std/src/sys/pal/mod.rs | 1 - library/std/src/sys/pal/personality/dwarf/eh.rs | 257 ------------------ library/std/src/sys/pal/personality/dwarf/mod.rs | 73 ----- library/std/src/sys/pal/personality/dwarf/tests.rs | 19 -- library/std/src/sys/pal/personality/emcc.rs | 20 -- library/std/src/sys/pal/personality/gcc.rs | 293 --------------------- library/std/src/sys/pal/personality/mod.rs | 47 ---- library/std/src/sys/personality/dwarf/eh.rs | 257 ++++++++++++++++++ library/std/src/sys/personality/dwarf/mod.rs | 73 +++++ library/std/src/sys/personality/dwarf/tests.rs | 19 ++ library/std/src/sys/personality/emcc.rs | 20 ++ library/std/src/sys/personality/gcc.rs | 293 +++++++++++++++++++++ library/std/src/sys/personality/mod.rs | 47 ++++ 14 files changed, 711 insertions(+), 710 deletions(-) delete mode 100644 library/std/src/sys/pal/personality/dwarf/eh.rs delete mode 100644 library/std/src/sys/pal/personality/dwarf/mod.rs delete mode 100644 library/std/src/sys/pal/personality/dwarf/tests.rs delete mode 100644 library/std/src/sys/pal/personality/emcc.rs delete mode 100644 library/std/src/sys/pal/personality/gcc.rs delete mode 100644 library/std/src/sys/pal/personality/mod.rs create mode 100644 library/std/src/sys/personality/dwarf/eh.rs create mode 100644 library/std/src/sys/personality/dwarf/mod.rs create mode 100644 library/std/src/sys/personality/dwarf/tests.rs create mode 100644 library/std/src/sys/personality/emcc.rs create mode 100644 library/std/src/sys/personality/gcc.rs create mode 100644 library/std/src/sys/personality/mod.rs diff --git a/library/std/src/sys/mod.rs b/library/std/src/sys/mod.rs index 0cd4528b69e..bbdcb32606c 100644 --- a/library/std/src/sys/mod.rs +++ b/library/std/src/sys/mod.rs @@ -3,6 +3,8 @@ /// descriptors. mod pal; +mod personality; + // FIXME(117276): remove this, move feature implementations into individual // submodules. pub use pal::*; diff --git a/library/std/src/sys/pal/mod.rs b/library/std/src/sys/pal/mod.rs index 88420bd3612..66b2a4b8885 100644 --- a/library/std/src/sys/pal/mod.rs +++ b/library/std/src/sys/pal/mod.rs @@ -23,7 +23,6 @@ #![allow(missing_debug_implementations)] pub mod common; -mod personality; cfg_if::cfg_if! { if #[cfg(unix)] { diff --git a/library/std/src/sys/pal/personality/dwarf/eh.rs b/library/std/src/sys/pal/personality/dwarf/eh.rs deleted file mode 100644 index a78084de0fa..00000000000 --- a/library/std/src/sys/pal/personality/dwarf/eh.rs +++ /dev/null @@ -1,257 +0,0 @@ -//! Parsing of GCC-style Language-Specific Data Area (LSDA) -//! For details see: -//! * -//! * -//! * -//! * -//! * -//! -//! A reference implementation may be found in the GCC source tree -//! (`/libgcc/unwind-c.c` as of this writing). - -#![allow(non_upper_case_globals)] -#![allow(unused)] - -use super::DwarfReader; -use core::mem; -use core::ptr; - -pub const DW_EH_PE_omit: u8 = 0xFF; -pub const DW_EH_PE_absptr: u8 = 0x00; - -pub const DW_EH_PE_uleb128: u8 = 0x01; -pub const DW_EH_PE_udata2: u8 = 0x02; -pub const DW_EH_PE_udata4: u8 = 0x03; -pub const DW_EH_PE_udata8: u8 = 0x04; -pub const DW_EH_PE_sleb128: u8 = 0x09; -pub const DW_EH_PE_sdata2: u8 = 0x0A; -pub const DW_EH_PE_sdata4: u8 = 0x0B; -pub const DW_EH_PE_sdata8: u8 = 0x0C; - -pub const DW_EH_PE_pcrel: u8 = 0x10; -pub const DW_EH_PE_textrel: u8 = 0x20; -pub const DW_EH_PE_datarel: u8 = 0x30; -pub const DW_EH_PE_funcrel: u8 = 0x40; -pub const DW_EH_PE_aligned: u8 = 0x50; - -pub const DW_EH_PE_indirect: u8 = 0x80; - -#[derive(Copy, Clone)] -pub struct EHContext<'a> { - pub ip: *const u8, // Current instruction pointer - pub func_start: *const u8, // Pointer to the current function - pub get_text_start: &'a dyn Fn() -> *const u8, // Get pointer to the code section - pub get_data_start: &'a dyn Fn() -> *const u8, // Get pointer to the data section -} - -/// Landing pad. -type LPad = *const u8; -pub enum EHAction { - None, - Cleanup(LPad), - Catch(LPad), - Filter(LPad), - Terminate, -} - -pub const USING_SJLJ_EXCEPTIONS: bool = cfg!(all(target_os = "ios", target_arch = "arm")); - -pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result { - if lsda.is_null() { - return Ok(EHAction::None); - } - - let func_start = context.func_start; - let mut reader = DwarfReader::new(lsda); - - let start_encoding = reader.read::(); - // base address for landing pad offsets - let lpad_base = if start_encoding != DW_EH_PE_omit { - read_encoded_pointer(&mut reader, context, start_encoding)? - } else { - func_start - }; - - let ttype_encoding = reader.read::(); - if ttype_encoding != DW_EH_PE_omit { - // Rust doesn't analyze exception types, so we don't care about the type table - reader.read_uleb128(); - } - - let call_site_encoding = reader.read::(); - let call_site_table_length = reader.read_uleb128(); - let action_table = reader.ptr.add(call_site_table_length as usize); - let ip = context.ip; - - if !USING_SJLJ_EXCEPTIONS { - // read the callsite table - while reader.ptr < action_table { - // these are offsets rather than pointers; - let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_action_entry = reader.read_uleb128(); - // Callsite table is sorted by cs_start, so if we've passed the ip, we - // may stop searching. - if ip < func_start.wrapping_add(cs_start) { - break; - } - if ip < func_start.wrapping_add(cs_start + cs_len) { - if cs_lpad == 0 { - return Ok(EHAction::None); - } else { - let lpad = lpad_base.wrapping_add(cs_lpad); - return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); - } - } - } - // Ip is not present in the table. This indicates a nounwind call. - Ok(EHAction::Terminate) - } else { - // SjLj version: - // The "IP" is an index into the call-site table, with two exceptions: - // -1 means 'no-action', and 0 means 'terminate'. - match ip.addr() as isize { - -1 => return Ok(EHAction::None), - 0 => return Ok(EHAction::Terminate), - _ => (), - } - let mut idx = ip.addr(); - loop { - let cs_lpad = reader.read_uleb128(); - let cs_action_entry = reader.read_uleb128(); - idx -= 1; - if idx == 0 { - // Can never have null landing pad for sjlj -- that would have - // been indicated by a -1 call site index. - // FIXME(strict provenance) - let lpad = ptr::from_exposed_addr((cs_lpad + 1) as usize); - return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); - } - } - } -} - -unsafe fn interpret_cs_action( - action_table: *const u8, - cs_action_entry: u64, - lpad: LPad, -) -> EHAction { - if cs_action_entry == 0 { - // If cs_action_entry is 0 then this is a cleanup (Drop::drop). We run these - // for both Rust panics and foreign exceptions. - EHAction::Cleanup(lpad) - } else { - // If lpad != 0 and cs_action_entry != 0, we have to check ttype_index. - // If ttype_index == 0 under the condition, we take cleanup action. - let action_record = action_table.offset(cs_action_entry as isize - 1); - let mut action_reader = DwarfReader::new(action_record); - let ttype_index = action_reader.read_sleb128(); - if ttype_index == 0 { - EHAction::Cleanup(lpad) - } else if ttype_index > 0 { - // Stop unwinding Rust panics at catch_unwind. - EHAction::Catch(lpad) - } else { - EHAction::Filter(lpad) - } - } -} - -#[inline] -fn round_up(unrounded: usize, align: usize) -> Result { - if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) } -} - -/// Read a offset (`usize`) from `reader` whose encoding is described by `encoding`. -/// -/// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. -/// In addition the upper ("application") part must be zero. -/// -/// # Errors -/// Returns `Err` if `encoding` -/// * is not a valid DWARF Exception Header Encoding, -/// * is `DW_EH_PE_omit`, or -/// * has a non-zero application part. -/// -/// [LSB-dwarf-ext]: https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html -unsafe fn read_encoded_offset(reader: &mut DwarfReader, encoding: u8) -> Result { - if encoding == DW_EH_PE_omit || encoding & 0xF0 != 0 { - return Err(()); - } - let result = match encoding & 0x0F { - // despite the name, LLVM also uses absptr for offsets instead of pointers - DW_EH_PE_absptr => reader.read::(), - DW_EH_PE_uleb128 => reader.read_uleb128() as usize, - DW_EH_PE_udata2 => reader.read::() as usize, - DW_EH_PE_udata4 => reader.read::() as usize, - DW_EH_PE_udata8 => reader.read::() as usize, - DW_EH_PE_sleb128 => reader.read_sleb128() as usize, - DW_EH_PE_sdata2 => reader.read::() as usize, - DW_EH_PE_sdata4 => reader.read::() as usize, - DW_EH_PE_sdata8 => reader.read::() as usize, - _ => return Err(()), - }; - Ok(result) -} - -/// Read a pointer from `reader` whose encoding is described by `encoding`. -/// -/// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. -/// -/// # Errors -/// Returns `Err` if `encoding` -/// * is not a valid DWARF Exception Header Encoding, -/// * is `DW_EH_PE_omit`, or -/// * combines `DW_EH_PE_absptr` or `DW_EH_PE_aligned` application part with an integer encoding -/// (not `DW_EH_PE_absptr`) in the value format part. -/// -/// [LSB-dwarf-ext]: https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html -unsafe fn read_encoded_pointer( - reader: &mut DwarfReader, - context: &EHContext<'_>, - encoding: u8, -) -> Result<*const u8, ()> { - if encoding == DW_EH_PE_omit { - return Err(()); - } - - let base_ptr = match encoding & 0x70 { - DW_EH_PE_absptr => core::ptr::null(), - // relative to address of the encoded value, despite the name - DW_EH_PE_pcrel => reader.ptr, - DW_EH_PE_funcrel => { - if context.func_start.is_null() { - return Err(()); - } - context.func_start - } - DW_EH_PE_textrel => (*context.get_text_start)(), - DW_EH_PE_datarel => (*context.get_data_start)(), - // aligned means the value is aligned to the size of a pointer - DW_EH_PE_aligned => { - reader.ptr = - reader.ptr.with_addr(round_up(reader.ptr.addr(), mem::size_of::<*const u8>())?); - core::ptr::null() - } - _ => return Err(()), - }; - - let mut ptr = if base_ptr.is_null() { - // any value encoding other than absptr would be nonsensical here; - // there would be no source of pointer provenance - if encoding & 0x0F != DW_EH_PE_absptr { - return Err(()); - } - reader.read::<*const u8>() - } else { - let offset = read_encoded_offset(reader, encoding & 0x0F)?; - base_ptr.wrapping_add(offset) - }; - - if encoding & DW_EH_PE_indirect != 0 { - ptr = *(ptr.cast::<*const u8>()); - } - - Ok(ptr) -} diff --git a/library/std/src/sys/pal/personality/dwarf/mod.rs b/library/std/src/sys/pal/personality/dwarf/mod.rs deleted file mode 100644 index 652fbe95a14..00000000000 --- a/library/std/src/sys/pal/personality/dwarf/mod.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Utilities for parsing DWARF-encoded data streams. -//! See , -//! DWARF-4 standard, Section 7 - "Data Representation" - -// This module is used only by x86_64-pc-windows-gnu for now, but we -// are compiling it everywhere to avoid regressions. -#![allow(unused)] - -#[cfg(test)] -mod tests; - -pub mod eh; - -use core::mem; - -pub struct DwarfReader { - pub ptr: *const u8, -} - -#[repr(C, packed)] -struct Unaligned(T); - -impl DwarfReader { - pub fn new(ptr: *const u8) -> DwarfReader { - DwarfReader { ptr } - } - - // DWARF streams are packed, so e.g., a u32 would not necessarily be aligned - // on a 4-byte boundary. This may cause problems on platforms with strict - // alignment requirements. By wrapping data in a "packed" struct, we are - // telling the backend to generate "misalignment-safe" code. - pub unsafe fn read(&mut self) -> T { - let Unaligned(result) = *(self.ptr as *const Unaligned); - self.ptr = self.ptr.add(mem::size_of::()); - result - } - - // ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable - // Length Data". - pub unsafe fn read_uleb128(&mut self) -> u64 { - let mut shift: usize = 0; - let mut result: u64 = 0; - let mut byte: u8; - loop { - byte = self.read::(); - result |= ((byte & 0x7F) as u64) << shift; - shift += 7; - if byte & 0x80 == 0 { - break; - } - } - result - } - - pub unsafe fn read_sleb128(&mut self) -> i64 { - let mut shift: u32 = 0; - let mut result: u64 = 0; - let mut byte: u8; - loop { - byte = self.read::(); - result |= ((byte & 0x7F) as u64) << shift; - shift += 7; - if byte & 0x80 == 0 { - break; - } - } - // sign-extend - if shift < u64::BITS && (byte & 0x40) != 0 { - result |= (!0 as u64) << shift; - } - result as i64 - } -} diff --git a/library/std/src/sys/pal/personality/dwarf/tests.rs b/library/std/src/sys/pal/personality/dwarf/tests.rs deleted file mode 100644 index 1644f37083a..00000000000 --- a/library/std/src/sys/pal/personality/dwarf/tests.rs +++ /dev/null @@ -1,19 +0,0 @@ -use super::*; - -#[test] -fn dwarf_reader() { - let encoded: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 0xE5, 0x8E, 0x26, 0x9B, 0xF1, 0x59, 0xFF, 0xFF]; - - let mut reader = DwarfReader::new(encoded.as_ptr()); - - unsafe { - assert!(reader.read::() == u8::to_be(1u8)); - assert!(reader.read::() == u16::to_be(0x0203)); - assert!(reader.read::() == u32::to_be(0x04050607)); - - assert!(reader.read_uleb128() == 624485); - assert!(reader.read_sleb128() == -624485); - - assert!(reader.read::() == i8::to_be(-1)); - } -} diff --git a/library/std/src/sys/pal/personality/emcc.rs b/library/std/src/sys/pal/personality/emcc.rs deleted file mode 100644 index cb52ae89b19..00000000000 --- a/library/std/src/sys/pal/personality/emcc.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! On Emscripten Rust panics are wrapped in C++ exceptions, so we just forward -//! to `__gxx_personality_v0` which is provided by Emscripten. - -use crate::ffi::c_int; -use unwind as uw; - -// This is required by the compiler to exist (e.g., it's a lang item), but it's -// never actually called by the compiler. Emscripten EH doesn't use a -// personality function at all, it instead uses __cxa_find_matching_catch. -// Wasm error handling would use __gxx_personality_wasm0. -#[lang = "eh_personality"] -unsafe extern "C" fn rust_eh_personality( - _version: c_int, - _actions: uw::_Unwind_Action, - _exception_class: uw::_Unwind_Exception_Class, - _exception_object: *mut uw::_Unwind_Exception, - _context: *mut uw::_Unwind_Context, -) -> uw::_Unwind_Reason_Code { - core::intrinsics::abort() -} diff --git a/library/std/src/sys/pal/personality/gcc.rs b/library/std/src/sys/pal/personality/gcc.rs deleted file mode 100644 index 6f317131145..00000000000 --- a/library/std/src/sys/pal/personality/gcc.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! Implementation of panics backed by libgcc/libunwind (in some form). -//! -//! For background on exception handling and stack unwinding please see -//! "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and -//! documents linked from it. -//! These are also good reads: -//! * -//! * -//! * -//! -//! ## A brief summary -//! -//! Exception handling happens in two phases: a search phase and a cleanup -//! phase. -//! -//! In both phases the unwinder walks stack frames from top to bottom using -//! information from the stack frame unwind sections of the current process's -//! modules ("module" here refers to an OS module, i.e., an executable or a -//! dynamic library). -//! -//! For each stack frame, it invokes the associated "personality routine", whose -//! address is also stored in the unwind info section. -//! -//! In the search phase, the job of a personality routine is to examine -//! exception object being thrown, and to decide whether it should be caught at -//! that stack frame. Once the handler frame has been identified, cleanup phase -//! begins. -//! -//! In the cleanup phase, the unwinder invokes each personality routine again. -//! This time it decides which (if any) cleanup code needs to be run for -//! the current stack frame. If so, the control is transferred to a special -//! branch in the function body, the "landing pad", which invokes destructors, -//! frees memory, etc. At the end of the landing pad, control is transferred -//! back to the unwinder and unwinding resumes. -//! -//! Once stack has been unwound down to the handler frame level, unwinding stops -//! and the last personality routine transfers control to the catch block. - -use super::dwarf::eh::{self, EHAction, EHContext}; -use crate::ffi::c_int; -use unwind as uw; - -// Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister() -// and TargetLowering::getExceptionSelectorRegister() for each architecture, -// then mapped to DWARF register numbers via register definition tables -// (typically RegisterInfo.td, search for "DwarfRegNum"). -// See also https://llvm.org/docs/WritingAnLLVMBackend.html#defining-a-register. - -#[cfg(target_arch = "x86")] -const UNWIND_DATA_REG: (i32, i32) = (0, 2); // EAX, EDX - -#[cfg(target_arch = "x86_64")] -const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX - -#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] -const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1 - -#[cfg(target_arch = "m68k")] -const UNWIND_DATA_REG: (i32, i32) = (0, 1); // D0, D1 - -#[cfg(any( - target_arch = "mips", - target_arch = "mips32r6", - target_arch = "mips64", - target_arch = "mips64r6" -))] -const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, A1 - -#[cfg(target_arch = "csky")] -const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 - -#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))] -const UNWIND_DATA_REG: (i32, i32) = (3, 4); // R3, R4 / X3, X4 - -#[cfg(target_arch = "s390x")] -const UNWIND_DATA_REG: (i32, i32) = (6, 7); // R6, R7 - -#[cfg(any(target_arch = "sparc", target_arch = "sparc64"))] -const UNWIND_DATA_REG: (i32, i32) = (24, 25); // I0, I1 - -#[cfg(target_arch = "hexagon")] -const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 - -#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))] -const UNWIND_DATA_REG: (i32, i32) = (10, 11); // x10, x11 - -#[cfg(target_arch = "loongarch64")] -const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1 - -// The following code is based on GCC's C and C++ personality routines. For reference, see: -// https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc -// https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c - -cfg_if::cfg_if! { - if #[cfg(all(target_arch = "arm", not(target_os = "ios"), not(target_os = "tvos"), not(target_os = "watchos"), not(target_os = "netbsd")))] { - // ARM EHABI personality routine. - // https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf - // - // iOS uses the default routine instead since it uses SjLj unwinding. - #[lang = "eh_personality"] - unsafe extern "C" fn rust_eh_personality( - state: uw::_Unwind_State, - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code { - let state = state as c_int; - let action = state & uw::_US_ACTION_MASK as c_int; - let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { - // Backtraces on ARM will call the personality routine with - // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases - // we want to continue unwinding the stack, otherwise all our backtraces - // would end at __rust_try - if state & uw::_US_FORCE_UNWIND as c_int != 0 { - return continue_unwind(exception_object, context); - } - true - } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int { - false - } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int { - return continue_unwind(exception_object, context); - } else { - return uw::_URC_FAILURE; - }; - - // The DWARF unwinder assumes that _Unwind_Context holds things like the function - // and LSDA pointers, however ARM EHABI places them into the exception object. - // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which - // take only the context pointer, GCC personality routines stash a pointer to - // exception_object in the context, using location reserved for ARM's - // "scratch register" (r12). - uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr); - // ...A more principled approach would be to provide the full definition of ARM's - // _Unwind_Context in our libunwind bindings and fetch the required data from there - // directly, bypassing DWARF compatibility functions. - - let eh_action = match find_eh_action(context) { - Ok(action) => action, - Err(_) => return uw::_URC_FAILURE, - }; - if search_phase { - match eh_action { - EHAction::None | EHAction::Cleanup(_) => { - return continue_unwind(exception_object, context); - } - EHAction::Catch(_) | EHAction::Filter(_) => { - // EHABI requires the personality routine to update the - // SP value in the barrier cache of the exception object. - (*exception_object).private[5] = - uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); - return uw::_URC_HANDLER_FOUND; - } - EHAction::Terminate => return uw::_URC_FAILURE, - } - } else { - match eh_action { - EHAction::None => return continue_unwind(exception_object, context), - EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context), - EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { - uw::_Unwind_SetGR( - context, - UNWIND_DATA_REG.0, - exception_object as uw::_Unwind_Ptr, - ); - uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); - uw::_Unwind_SetIP(context, lpad); - return uw::_URC_INSTALL_CONTEXT; - } - EHAction::Terminate => return uw::_URC_FAILURE, - } - } - - // On ARM EHABI the personality routine is responsible for actually - // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1). - unsafe fn continue_unwind( - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code { - if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON { - uw::_URC_CONTINUE_UNWIND - } else { - uw::_URC_FAILURE - } - } - // defined in libgcc - extern "C" { - fn __gnu_unwind_frame( - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code; - } - } - } else { - // Default personality routine, which is used directly on most targets - // and indirectly on Windows x86_64 via SEH. - unsafe extern "C" fn rust_eh_personality_impl( - version: c_int, - actions: uw::_Unwind_Action, - _exception_class: uw::_Unwind_Exception_Class, - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code { - if version != 1 { - return uw::_URC_FATAL_PHASE1_ERROR; - } - let eh_action = match find_eh_action(context) { - Ok(action) => action, - Err(_) => return uw::_URC_FATAL_PHASE1_ERROR, - }; - if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 { - match eh_action { - EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND, - EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND, - EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR, - } - } else { - match eh_action { - EHAction::None => uw::_URC_CONTINUE_UNWIND, - // Forced unwinding hits a terminate action. - EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND, - EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { - uw::_Unwind_SetGR( - context, - UNWIND_DATA_REG.0, - exception_object.cast(), - ); - uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); - uw::_Unwind_SetIP(context, lpad); - uw::_URC_INSTALL_CONTEXT - } - EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR, - } - } - } - - cfg_if::cfg_if! { - if #[cfg(all(windows, any(target_arch = "aarch64", target_arch = "x86_64"), target_env = "gnu"))] { - // On x86_64 MinGW targets, the unwinding mechanism is SEH however the unwind - // handler data (aka LSDA) uses GCC-compatible encoding. - #[lang = "eh_personality"] - #[allow(nonstandard_style)] - unsafe extern "C" fn rust_eh_personality( - exceptionRecord: *mut uw::EXCEPTION_RECORD, - establisherFrame: uw::LPVOID, - contextRecord: *mut uw::CONTEXT, - dispatcherContext: *mut uw::DISPATCHER_CONTEXT, - ) -> uw::EXCEPTION_DISPOSITION { - uw::_GCC_specific_handler( - exceptionRecord, - establisherFrame, - contextRecord, - dispatcherContext, - rust_eh_personality_impl, - ) - } - } else { - // The personality routine for most of our targets. - #[lang = "eh_personality"] - unsafe extern "C" fn rust_eh_personality( - version: c_int, - actions: uw::_Unwind_Action, - exception_class: uw::_Unwind_Exception_Class, - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code { - rust_eh_personality_impl( - version, - actions, - exception_class, - exception_object, - context, - ) - } - } - } - } -} - -unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result { - let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8; - let mut ip_before_instr: c_int = 0; - let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr); - let eh_context = EHContext { - // The return address points 1 byte past the call instruction, - // which could be in the next IP range in LSDA range table. - // - // `ip = -1` has special meaning, so use wrapping sub to allow for that - ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) }, - func_start: uw::_Unwind_GetRegionStart(context), - get_text_start: &|| uw::_Unwind_GetTextRelBase(context), - get_data_start: &|| uw::_Unwind_GetDataRelBase(context), - }; - eh::find_eh_action(lsda, &eh_context) -} diff --git a/library/std/src/sys/pal/personality/mod.rs b/library/std/src/sys/pal/personality/mod.rs deleted file mode 100644 index d37b8ce6346..00000000000 --- a/library/std/src/sys/pal/personality/mod.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! This module contains the implementation of the `eh_personality` lang item. -//! -//! The actual implementation is heavily dependent on the target since Rust -//! tries to use the native stack unwinding mechanism whenever possible. -//! -//! This personality function is still required with `-C panic=abort` because -//! it is used to catch foreign exceptions from `extern "C-unwind"` and turn -//! them into aborts. -//! -//! Additionally, ARM EHABI uses the personality function when generating -//! backtraces. - -mod dwarf; - -#[cfg(not(any(test, doctest)))] -cfg_if::cfg_if! { - if #[cfg(target_os = "emscripten")] { - mod emcc; - } else if #[cfg(target_env = "msvc")] { - // This is required by the compiler to exist (e.g., it's a lang item), - // but it's never actually called by the compiler because - // _CxxFrameHandler3 is the personality function that is always used. - // Hence this is just an aborting stub. - #[lang = "eh_personality"] - fn rust_eh_personality() { - core::intrinsics::abort() - } - } else if #[cfg(any( - all(target_family = "windows", target_env = "gnu"), - target_os = "psp", - target_os = "xous", - target_os = "solid_asp3", - all(target_family = "unix", not(target_os = "espidf"), not(target_os = "l4re")), - all(target_vendor = "fortanix", target_env = "sgx"), - ))] { - mod gcc; - } else { - // Targets that don't support unwinding. - // - family=wasm - // - os=none ("bare metal" targets) - // - os=uefi - // - os=espidf - // - os=hermit - // - nvptx64-nvidia-cuda - // - arch=avr - } -} diff --git a/library/std/src/sys/personality/dwarf/eh.rs b/library/std/src/sys/personality/dwarf/eh.rs new file mode 100644 index 00000000000..a78084de0fa --- /dev/null +++ b/library/std/src/sys/personality/dwarf/eh.rs @@ -0,0 +1,257 @@ +//! Parsing of GCC-style Language-Specific Data Area (LSDA) +//! For details see: +//! * +//! * +//! * +//! * +//! * +//! +//! A reference implementation may be found in the GCC source tree +//! (`/libgcc/unwind-c.c` as of this writing). + +#![allow(non_upper_case_globals)] +#![allow(unused)] + +use super::DwarfReader; +use core::mem; +use core::ptr; + +pub const DW_EH_PE_omit: u8 = 0xFF; +pub const DW_EH_PE_absptr: u8 = 0x00; + +pub const DW_EH_PE_uleb128: u8 = 0x01; +pub const DW_EH_PE_udata2: u8 = 0x02; +pub const DW_EH_PE_udata4: u8 = 0x03; +pub const DW_EH_PE_udata8: u8 = 0x04; +pub const DW_EH_PE_sleb128: u8 = 0x09; +pub const DW_EH_PE_sdata2: u8 = 0x0A; +pub const DW_EH_PE_sdata4: u8 = 0x0B; +pub const DW_EH_PE_sdata8: u8 = 0x0C; + +pub const DW_EH_PE_pcrel: u8 = 0x10; +pub const DW_EH_PE_textrel: u8 = 0x20; +pub const DW_EH_PE_datarel: u8 = 0x30; +pub const DW_EH_PE_funcrel: u8 = 0x40; +pub const DW_EH_PE_aligned: u8 = 0x50; + +pub const DW_EH_PE_indirect: u8 = 0x80; + +#[derive(Copy, Clone)] +pub struct EHContext<'a> { + pub ip: *const u8, // Current instruction pointer + pub func_start: *const u8, // Pointer to the current function + pub get_text_start: &'a dyn Fn() -> *const u8, // Get pointer to the code section + pub get_data_start: &'a dyn Fn() -> *const u8, // Get pointer to the data section +} + +/// Landing pad. +type LPad = *const u8; +pub enum EHAction { + None, + Cleanup(LPad), + Catch(LPad), + Filter(LPad), + Terminate, +} + +pub const USING_SJLJ_EXCEPTIONS: bool = cfg!(all(target_os = "ios", target_arch = "arm")); + +pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result { + if lsda.is_null() { + return Ok(EHAction::None); + } + + let func_start = context.func_start; + let mut reader = DwarfReader::new(lsda); + + let start_encoding = reader.read::(); + // base address for landing pad offsets + let lpad_base = if start_encoding != DW_EH_PE_omit { + read_encoded_pointer(&mut reader, context, start_encoding)? + } else { + func_start + }; + + let ttype_encoding = reader.read::(); + if ttype_encoding != DW_EH_PE_omit { + // Rust doesn't analyze exception types, so we don't care about the type table + reader.read_uleb128(); + } + + let call_site_encoding = reader.read::(); + let call_site_table_length = reader.read_uleb128(); + let action_table = reader.ptr.add(call_site_table_length as usize); + let ip = context.ip; + + if !USING_SJLJ_EXCEPTIONS { + // read the callsite table + while reader.ptr < action_table { + // these are offsets rather than pointers; + let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_action_entry = reader.read_uleb128(); + // Callsite table is sorted by cs_start, so if we've passed the ip, we + // may stop searching. + if ip < func_start.wrapping_add(cs_start) { + break; + } + if ip < func_start.wrapping_add(cs_start + cs_len) { + if cs_lpad == 0 { + return Ok(EHAction::None); + } else { + let lpad = lpad_base.wrapping_add(cs_lpad); + return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + } + } + } + // Ip is not present in the table. This indicates a nounwind call. + Ok(EHAction::Terminate) + } else { + // SjLj version: + // The "IP" is an index into the call-site table, with two exceptions: + // -1 means 'no-action', and 0 means 'terminate'. + match ip.addr() as isize { + -1 => return Ok(EHAction::None), + 0 => return Ok(EHAction::Terminate), + _ => (), + } + let mut idx = ip.addr(); + loop { + let cs_lpad = reader.read_uleb128(); + let cs_action_entry = reader.read_uleb128(); + idx -= 1; + if idx == 0 { + // Can never have null landing pad for sjlj -- that would have + // been indicated by a -1 call site index. + // FIXME(strict provenance) + let lpad = ptr::from_exposed_addr((cs_lpad + 1) as usize); + return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + } + } + } +} + +unsafe fn interpret_cs_action( + action_table: *const u8, + cs_action_entry: u64, + lpad: LPad, +) -> EHAction { + if cs_action_entry == 0 { + // If cs_action_entry is 0 then this is a cleanup (Drop::drop). We run these + // for both Rust panics and foreign exceptions. + EHAction::Cleanup(lpad) + } else { + // If lpad != 0 and cs_action_entry != 0, we have to check ttype_index. + // If ttype_index == 0 under the condition, we take cleanup action. + let action_record = action_table.offset(cs_action_entry as isize - 1); + let mut action_reader = DwarfReader::new(action_record); + let ttype_index = action_reader.read_sleb128(); + if ttype_index == 0 { + EHAction::Cleanup(lpad) + } else if ttype_index > 0 { + // Stop unwinding Rust panics at catch_unwind. + EHAction::Catch(lpad) + } else { + EHAction::Filter(lpad) + } + } +} + +#[inline] +fn round_up(unrounded: usize, align: usize) -> Result { + if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) } +} + +/// Read a offset (`usize`) from `reader` whose encoding is described by `encoding`. +/// +/// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. +/// In addition the upper ("application") part must be zero. +/// +/// # Errors +/// Returns `Err` if `encoding` +/// * is not a valid DWARF Exception Header Encoding, +/// * is `DW_EH_PE_omit`, or +/// * has a non-zero application part. +/// +/// [LSB-dwarf-ext]: https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html +unsafe fn read_encoded_offset(reader: &mut DwarfReader, encoding: u8) -> Result { + if encoding == DW_EH_PE_omit || encoding & 0xF0 != 0 { + return Err(()); + } + let result = match encoding & 0x0F { + // despite the name, LLVM also uses absptr for offsets instead of pointers + DW_EH_PE_absptr => reader.read::(), + DW_EH_PE_uleb128 => reader.read_uleb128() as usize, + DW_EH_PE_udata2 => reader.read::() as usize, + DW_EH_PE_udata4 => reader.read::() as usize, + DW_EH_PE_udata8 => reader.read::() as usize, + DW_EH_PE_sleb128 => reader.read_sleb128() as usize, + DW_EH_PE_sdata2 => reader.read::() as usize, + DW_EH_PE_sdata4 => reader.read::() as usize, + DW_EH_PE_sdata8 => reader.read::() as usize, + _ => return Err(()), + }; + Ok(result) +} + +/// Read a pointer from `reader` whose encoding is described by `encoding`. +/// +/// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. +/// +/// # Errors +/// Returns `Err` if `encoding` +/// * is not a valid DWARF Exception Header Encoding, +/// * is `DW_EH_PE_omit`, or +/// * combines `DW_EH_PE_absptr` or `DW_EH_PE_aligned` application part with an integer encoding +/// (not `DW_EH_PE_absptr`) in the value format part. +/// +/// [LSB-dwarf-ext]: https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html +unsafe fn read_encoded_pointer( + reader: &mut DwarfReader, + context: &EHContext<'_>, + encoding: u8, +) -> Result<*const u8, ()> { + if encoding == DW_EH_PE_omit { + return Err(()); + } + + let base_ptr = match encoding & 0x70 { + DW_EH_PE_absptr => core::ptr::null(), + // relative to address of the encoded value, despite the name + DW_EH_PE_pcrel => reader.ptr, + DW_EH_PE_funcrel => { + if context.func_start.is_null() { + return Err(()); + } + context.func_start + } + DW_EH_PE_textrel => (*context.get_text_start)(), + DW_EH_PE_datarel => (*context.get_data_start)(), + // aligned means the value is aligned to the size of a pointer + DW_EH_PE_aligned => { + reader.ptr = + reader.ptr.with_addr(round_up(reader.ptr.addr(), mem::size_of::<*const u8>())?); + core::ptr::null() + } + _ => return Err(()), + }; + + let mut ptr = if base_ptr.is_null() { + // any value encoding other than absptr would be nonsensical here; + // there would be no source of pointer provenance + if encoding & 0x0F != DW_EH_PE_absptr { + return Err(()); + } + reader.read::<*const u8>() + } else { + let offset = read_encoded_offset(reader, encoding & 0x0F)?; + base_ptr.wrapping_add(offset) + }; + + if encoding & DW_EH_PE_indirect != 0 { + ptr = *(ptr.cast::<*const u8>()); + } + + Ok(ptr) +} diff --git a/library/std/src/sys/personality/dwarf/mod.rs b/library/std/src/sys/personality/dwarf/mod.rs new file mode 100644 index 00000000000..652fbe95a14 --- /dev/null +++ b/library/std/src/sys/personality/dwarf/mod.rs @@ -0,0 +1,73 @@ +//! Utilities for parsing DWARF-encoded data streams. +//! See , +//! DWARF-4 standard, Section 7 - "Data Representation" + +// This module is used only by x86_64-pc-windows-gnu for now, but we +// are compiling it everywhere to avoid regressions. +#![allow(unused)] + +#[cfg(test)] +mod tests; + +pub mod eh; + +use core::mem; + +pub struct DwarfReader { + pub ptr: *const u8, +} + +#[repr(C, packed)] +struct Unaligned(T); + +impl DwarfReader { + pub fn new(ptr: *const u8) -> DwarfReader { + DwarfReader { ptr } + } + + // DWARF streams are packed, so e.g., a u32 would not necessarily be aligned + // on a 4-byte boundary. This may cause problems on platforms with strict + // alignment requirements. By wrapping data in a "packed" struct, we are + // telling the backend to generate "misalignment-safe" code. + pub unsafe fn read(&mut self) -> T { + let Unaligned(result) = *(self.ptr as *const Unaligned); + self.ptr = self.ptr.add(mem::size_of::()); + result + } + + // ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable + // Length Data". + pub unsafe fn read_uleb128(&mut self) -> u64 { + let mut shift: usize = 0; + let mut result: u64 = 0; + let mut byte: u8; + loop { + byte = self.read::(); + result |= ((byte & 0x7F) as u64) << shift; + shift += 7; + if byte & 0x80 == 0 { + break; + } + } + result + } + + pub unsafe fn read_sleb128(&mut self) -> i64 { + let mut shift: u32 = 0; + let mut result: u64 = 0; + let mut byte: u8; + loop { + byte = self.read::(); + result |= ((byte & 0x7F) as u64) << shift; + shift += 7; + if byte & 0x80 == 0 { + break; + } + } + // sign-extend + if shift < u64::BITS && (byte & 0x40) != 0 { + result |= (!0 as u64) << shift; + } + result as i64 + } +} diff --git a/library/std/src/sys/personality/dwarf/tests.rs b/library/std/src/sys/personality/dwarf/tests.rs new file mode 100644 index 00000000000..1644f37083a --- /dev/null +++ b/library/std/src/sys/personality/dwarf/tests.rs @@ -0,0 +1,19 @@ +use super::*; + +#[test] +fn dwarf_reader() { + let encoded: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 0xE5, 0x8E, 0x26, 0x9B, 0xF1, 0x59, 0xFF, 0xFF]; + + let mut reader = DwarfReader::new(encoded.as_ptr()); + + unsafe { + assert!(reader.read::() == u8::to_be(1u8)); + assert!(reader.read::() == u16::to_be(0x0203)); + assert!(reader.read::() == u32::to_be(0x04050607)); + + assert!(reader.read_uleb128() == 624485); + assert!(reader.read_sleb128() == -624485); + + assert!(reader.read::() == i8::to_be(-1)); + } +} diff --git a/library/std/src/sys/personality/emcc.rs b/library/std/src/sys/personality/emcc.rs new file mode 100644 index 00000000000..cb52ae89b19 --- /dev/null +++ b/library/std/src/sys/personality/emcc.rs @@ -0,0 +1,20 @@ +//! On Emscripten Rust panics are wrapped in C++ exceptions, so we just forward +//! to `__gxx_personality_v0` which is provided by Emscripten. + +use crate::ffi::c_int; +use unwind as uw; + +// This is required by the compiler to exist (e.g., it's a lang item), but it's +// never actually called by the compiler. Emscripten EH doesn't use a +// personality function at all, it instead uses __cxa_find_matching_catch. +// Wasm error handling would use __gxx_personality_wasm0. +#[lang = "eh_personality"] +unsafe extern "C" fn rust_eh_personality( + _version: c_int, + _actions: uw::_Unwind_Action, + _exception_class: uw::_Unwind_Exception_Class, + _exception_object: *mut uw::_Unwind_Exception, + _context: *mut uw::_Unwind_Context, +) -> uw::_Unwind_Reason_Code { + core::intrinsics::abort() +} diff --git a/library/std/src/sys/personality/gcc.rs b/library/std/src/sys/personality/gcc.rs new file mode 100644 index 00000000000..6f317131145 --- /dev/null +++ b/library/std/src/sys/personality/gcc.rs @@ -0,0 +1,293 @@ +//! Implementation of panics backed by libgcc/libunwind (in some form). +//! +//! For background on exception handling and stack unwinding please see +//! "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and +//! documents linked from it. +//! These are also good reads: +//! * +//! * +//! * +//! +//! ## A brief summary +//! +//! Exception handling happens in two phases: a search phase and a cleanup +//! phase. +//! +//! In both phases the unwinder walks stack frames from top to bottom using +//! information from the stack frame unwind sections of the current process's +//! modules ("module" here refers to an OS module, i.e., an executable or a +//! dynamic library). +//! +//! For each stack frame, it invokes the associated "personality routine", whose +//! address is also stored in the unwind info section. +//! +//! In the search phase, the job of a personality routine is to examine +//! exception object being thrown, and to decide whether it should be caught at +//! that stack frame. Once the handler frame has been identified, cleanup phase +//! begins. +//! +//! In the cleanup phase, the unwinder invokes each personality routine again. +//! This time it decides which (if any) cleanup code needs to be run for +//! the current stack frame. If so, the control is transferred to a special +//! branch in the function body, the "landing pad", which invokes destructors, +//! frees memory, etc. At the end of the landing pad, control is transferred +//! back to the unwinder and unwinding resumes. +//! +//! Once stack has been unwound down to the handler frame level, unwinding stops +//! and the last personality routine transfers control to the catch block. + +use super::dwarf::eh::{self, EHAction, EHContext}; +use crate::ffi::c_int; +use unwind as uw; + +// Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister() +// and TargetLowering::getExceptionSelectorRegister() for each architecture, +// then mapped to DWARF register numbers via register definition tables +// (typically RegisterInfo.td, search for "DwarfRegNum"). +// See also https://llvm.org/docs/WritingAnLLVMBackend.html#defining-a-register. + +#[cfg(target_arch = "x86")] +const UNWIND_DATA_REG: (i32, i32) = (0, 2); // EAX, EDX + +#[cfg(target_arch = "x86_64")] +const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX + +#[cfg(any(target_arch = "arm", target_arch = "aarch64"))] +const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1 + +#[cfg(target_arch = "m68k")] +const UNWIND_DATA_REG: (i32, i32) = (0, 1); // D0, D1 + +#[cfg(any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" +))] +const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, A1 + +#[cfg(target_arch = "csky")] +const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 + +#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))] +const UNWIND_DATA_REG: (i32, i32) = (3, 4); // R3, R4 / X3, X4 + +#[cfg(target_arch = "s390x")] +const UNWIND_DATA_REG: (i32, i32) = (6, 7); // R6, R7 + +#[cfg(any(target_arch = "sparc", target_arch = "sparc64"))] +const UNWIND_DATA_REG: (i32, i32) = (24, 25); // I0, I1 + +#[cfg(target_arch = "hexagon")] +const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 + +#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))] +const UNWIND_DATA_REG: (i32, i32) = (10, 11); // x10, x11 + +#[cfg(target_arch = "loongarch64")] +const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1 + +// The following code is based on GCC's C and C++ personality routines. For reference, see: +// https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc +// https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c + +cfg_if::cfg_if! { + if #[cfg(all(target_arch = "arm", not(target_os = "ios"), not(target_os = "tvos"), not(target_os = "watchos"), not(target_os = "netbsd")))] { + // ARM EHABI personality routine. + // https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf + // + // iOS uses the default routine instead since it uses SjLj unwinding. + #[lang = "eh_personality"] + unsafe extern "C" fn rust_eh_personality( + state: uw::_Unwind_State, + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code { + let state = state as c_int; + let action = state & uw::_US_ACTION_MASK as c_int; + let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { + // Backtraces on ARM will call the personality routine with + // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases + // we want to continue unwinding the stack, otherwise all our backtraces + // would end at __rust_try + if state & uw::_US_FORCE_UNWIND as c_int != 0 { + return continue_unwind(exception_object, context); + } + true + } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int { + false + } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int { + return continue_unwind(exception_object, context); + } else { + return uw::_URC_FAILURE; + }; + + // The DWARF unwinder assumes that _Unwind_Context holds things like the function + // and LSDA pointers, however ARM EHABI places them into the exception object. + // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which + // take only the context pointer, GCC personality routines stash a pointer to + // exception_object in the context, using location reserved for ARM's + // "scratch register" (r12). + uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr); + // ...A more principled approach would be to provide the full definition of ARM's + // _Unwind_Context in our libunwind bindings and fetch the required data from there + // directly, bypassing DWARF compatibility functions. + + let eh_action = match find_eh_action(context) { + Ok(action) => action, + Err(_) => return uw::_URC_FAILURE, + }; + if search_phase { + match eh_action { + EHAction::None | EHAction::Cleanup(_) => { + return continue_unwind(exception_object, context); + } + EHAction::Catch(_) | EHAction::Filter(_) => { + // EHABI requires the personality routine to update the + // SP value in the barrier cache of the exception object. + (*exception_object).private[5] = + uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); + return uw::_URC_HANDLER_FOUND; + } + EHAction::Terminate => return uw::_URC_FAILURE, + } + } else { + match eh_action { + EHAction::None => return continue_unwind(exception_object, context), + EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context), + EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { + uw::_Unwind_SetGR( + context, + UNWIND_DATA_REG.0, + exception_object as uw::_Unwind_Ptr, + ); + uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); + uw::_Unwind_SetIP(context, lpad); + return uw::_URC_INSTALL_CONTEXT; + } + EHAction::Terminate => return uw::_URC_FAILURE, + } + } + + // On ARM EHABI the personality routine is responsible for actually + // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1). + unsafe fn continue_unwind( + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code { + if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON { + uw::_URC_CONTINUE_UNWIND + } else { + uw::_URC_FAILURE + } + } + // defined in libgcc + extern "C" { + fn __gnu_unwind_frame( + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code; + } + } + } else { + // Default personality routine, which is used directly on most targets + // and indirectly on Windows x86_64 via SEH. + unsafe extern "C" fn rust_eh_personality_impl( + version: c_int, + actions: uw::_Unwind_Action, + _exception_class: uw::_Unwind_Exception_Class, + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code { + if version != 1 { + return uw::_URC_FATAL_PHASE1_ERROR; + } + let eh_action = match find_eh_action(context) { + Ok(action) => action, + Err(_) => return uw::_URC_FATAL_PHASE1_ERROR, + }; + if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 { + match eh_action { + EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND, + EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND, + EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR, + } + } else { + match eh_action { + EHAction::None => uw::_URC_CONTINUE_UNWIND, + // Forced unwinding hits a terminate action. + EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND, + EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { + uw::_Unwind_SetGR( + context, + UNWIND_DATA_REG.0, + exception_object.cast(), + ); + uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); + uw::_Unwind_SetIP(context, lpad); + uw::_URC_INSTALL_CONTEXT + } + EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR, + } + } + } + + cfg_if::cfg_if! { + if #[cfg(all(windows, any(target_arch = "aarch64", target_arch = "x86_64"), target_env = "gnu"))] { + // On x86_64 MinGW targets, the unwinding mechanism is SEH however the unwind + // handler data (aka LSDA) uses GCC-compatible encoding. + #[lang = "eh_personality"] + #[allow(nonstandard_style)] + unsafe extern "C" fn rust_eh_personality( + exceptionRecord: *mut uw::EXCEPTION_RECORD, + establisherFrame: uw::LPVOID, + contextRecord: *mut uw::CONTEXT, + dispatcherContext: *mut uw::DISPATCHER_CONTEXT, + ) -> uw::EXCEPTION_DISPOSITION { + uw::_GCC_specific_handler( + exceptionRecord, + establisherFrame, + contextRecord, + dispatcherContext, + rust_eh_personality_impl, + ) + } + } else { + // The personality routine for most of our targets. + #[lang = "eh_personality"] + unsafe extern "C" fn rust_eh_personality( + version: c_int, + actions: uw::_Unwind_Action, + exception_class: uw::_Unwind_Exception_Class, + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code { + rust_eh_personality_impl( + version, + actions, + exception_class, + exception_object, + context, + ) + } + } + } + } +} + +unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result { + let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8; + let mut ip_before_instr: c_int = 0; + let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr); + let eh_context = EHContext { + // The return address points 1 byte past the call instruction, + // which could be in the next IP range in LSDA range table. + // + // `ip = -1` has special meaning, so use wrapping sub to allow for that + ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) }, + func_start: uw::_Unwind_GetRegionStart(context), + get_text_start: &|| uw::_Unwind_GetTextRelBase(context), + get_data_start: &|| uw::_Unwind_GetDataRelBase(context), + }; + eh::find_eh_action(lsda, &eh_context) +} diff --git a/library/std/src/sys/personality/mod.rs b/library/std/src/sys/personality/mod.rs new file mode 100644 index 00000000000..d37b8ce6346 --- /dev/null +++ b/library/std/src/sys/personality/mod.rs @@ -0,0 +1,47 @@ +//! This module contains the implementation of the `eh_personality` lang item. +//! +//! The actual implementation is heavily dependent on the target since Rust +//! tries to use the native stack unwinding mechanism whenever possible. +//! +//! This personality function is still required with `-C panic=abort` because +//! it is used to catch foreign exceptions from `extern "C-unwind"` and turn +//! them into aborts. +//! +//! Additionally, ARM EHABI uses the personality function when generating +//! backtraces. + +mod dwarf; + +#[cfg(not(any(test, doctest)))] +cfg_if::cfg_if! { + if #[cfg(target_os = "emscripten")] { + mod emcc; + } else if #[cfg(target_env = "msvc")] { + // This is required by the compiler to exist (e.g., it's a lang item), + // but it's never actually called by the compiler because + // _CxxFrameHandler3 is the personality function that is always used. + // Hence this is just an aborting stub. + #[lang = "eh_personality"] + fn rust_eh_personality() { + core::intrinsics::abort() + } + } else if #[cfg(any( + all(target_family = "windows", target_env = "gnu"), + target_os = "psp", + target_os = "xous", + target_os = "solid_asp3", + all(target_family = "unix", not(target_os = "espidf"), not(target_os = "l4re")), + all(target_vendor = "fortanix", target_env = "sgx"), + ))] { + mod gcc; + } else { + // Targets that don't support unwinding. + // - family=wasm + // - os=none ("bare metal" targets) + // - os=uefi + // - os=espidf + // - os=hermit + // - nvptx64-nvidia-cuda + // - arch=avr + } +} -- cgit 1.4.1-3-g733a5 From b8d996c09e3aba782ac02334ac3ded7b74162d89 Mon Sep 17 00:00:00 2001 From: joboet Date: Sat, 13 Jan 2024 18:36:47 +0100 Subject: tidy: allow platform-dependent code in `sys` --- src/tools/tidy/src/pal.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 398257d2bc2..7e5656926ab 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -46,8 +46,8 @@ const EXCEPTION_PATHS: &[&str] = &[ // we must use `#[cfg(windows)]` to conditionally compile the // correct `VaList` structure for windows. "library/core/src/ffi/mod.rs", - "library/std/src/sys/pal/", // Platform-specific code for std lives here. - "library/std/src/os", // Platform-specific public interfaces + "library/std/src/sys", // Platform-specific code for std lives here. + "library/std/src/os", // Platform-specific public interfaces // Temporary `std` exceptions // FIXME: platform-specific code should be moved to `sys` "library/std/src/io/copy.rs", -- cgit 1.4.1-3-g733a5 From 074220296d83cc1b6b85b26c45e47a0264a6d111 Mon Sep 17 00:00:00 2001 From: Nicholas Bishop Date: Sat, 13 Jan 2024 12:59:00 -0500 Subject: Add crate links to unknown-uefi.md --- src/doc/rustc/src/platform-support/unknown-uefi.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/doc/rustc/src/platform-support/unknown-uefi.md b/src/doc/rustc/src/platform-support/unknown-uefi.md index 1230ea22bd9..a0bd2c502bd 100644 --- a/src/doc/rustc/src/platform-support/unknown-uefi.md +++ b/src/doc/rustc/src/platform-support/unknown-uefi.md @@ -88,7 +88,7 @@ UEFI applications can be copied into the ESP on any UEFI system and executed via the firmware boot menu. The qemu suite allows emulating UEFI systems and executing UEFI applications as well. See its documentation for details. -The [uefi-run](https://github.com/Richard-W/uefi-run) rust tool is a simple +The [uefi-run] rust tool is a simple wrapper around `qemu` that can spawn UEFI applications in qemu. You can install it via `cargo install uefi-run` and execute qemu applications as `uefi-run ./application.efi`. @@ -132,19 +132,19 @@ have been developed to provide access to UEFI protocols and make UEFI programming more ergonomic in rust. The following list is a short overview (in alphabetical ordering): -- **efi**: *Ergonomic Rust bindings for writing UEFI applications*. Provides +- **[efi][efi-crate]**: *Ergonomic Rust bindings for writing UEFI applications*. Provides _rustified_ access to UEFI protocols, implements allocators and a safe environment to write UEFI applications. -- **r-efi**: *UEFI Reference Specification Protocol Constants and Definitions*. +- **[r-efi]**: *UEFI Reference Specification Protocol Constants and Definitions*. A pure transpose of the UEFI specification into rust. This provides the raw definitions from the specification, without any extended helpers or _rustification_. It serves as baseline to implement any more elaborate rust UEFI layers. -- **uefi-rs**: *Safe and easy-to-use wrapper for building UEFI apps*. An +- **[uefi-rs]**: *Safe and easy-to-use wrapper for building UEFI apps*. An elaborate library providing safe abstractions for UEFI protocols and features. It implements allocators and provides an execution environment to UEFI applications written in rust. -- **uefi-run**: *Run UEFI applications*. A small wrapper around _qemu_ to spawn +- **[uefi-run]**: *Run UEFI applications*. A small wrapper around _qemu_ to spawn UEFI applications in an emulated `x86_64` machine. ## Example: Freestanding @@ -311,3 +311,8 @@ pub fn main() { The current implementation of std makes `BootServices` unavailable once `ExitBootServices` is called. Refer to [Runtime Drivers](https://edk2-docs.gitbook.io/edk-ii-uefi-driver-writer-s-guide/7_driver_entry_point/711_runtime_drivers) for more information regarding how to handle switching from using physical addresses to using virtual addresses. Note: It should be noted that it is up to the user to drop all allocated memory before `ExitBootServices` is called. + +[efi-crate]: https://github.com/gurry/efi +[r-efi]: https://github.com/r-efi/r-efi +[uefi-rs]: https://github.com/rust-osdev/uefi-rs +[uefi-run]: https://github.com/Richard-W/uefi-run -- cgit 1.4.1-3-g733a5 From 3402f0741ac46d05cb572d27caa0b41e12f5ca1b Mon Sep 17 00:00:00 2001 From: Nicholas Bishop Date: Sat, 13 Jan 2024 13:08:17 -0500 Subject: Add doc and example for building a UEFI driver --- src/doc/rustc/src/platform-support/unknown-uefi.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/doc/rustc/src/platform-support/unknown-uefi.md b/src/doc/rustc/src/platform-support/unknown-uefi.md index a0bd2c502bd..8fb155e1ffa 100644 --- a/src/doc/rustc/src/platform-support/unknown-uefi.md +++ b/src/doc/rustc/src/platform-support/unknown-uefi.md @@ -82,6 +82,22 @@ rustup target add x86_64-unknown-uefi cargo build --target x86_64-unknown-uefi ``` +### Building a driver + +There are three types of UEFI executables: application, boot service +driver, and runtime driver. All of Rust's UEFI targets default to +producing applications. To build a driver instead, pass a +[`subsystem`][linker-subsystem] linker flag with a value of +`efi_boot_service_driver` or `efi_runtime_driver`. + +Example: + +```toml +# In .cargo/config.toml: +[build] +rustflags = ["-C", "link-args=/subsystem:efi_runtime_driver"] +``` + ## Testing UEFI applications can be copied into the ESP on any UEFI system and executed @@ -313,6 +329,7 @@ The current implementation of std makes `BootServices` unavailable once `ExitBoo Note: It should be noted that it is up to the user to drop all allocated memory before `ExitBootServices` is called. [efi-crate]: https://github.com/gurry/efi +[linker-subsystem]: https://learn.microsoft.com/en-us/cpp/build/reference/subsystem [r-efi]: https://github.com/r-efi/r-efi [uefi-rs]: https://github.com/rust-osdev/uefi-rs [uefi-run]: https://github.com/Richard-W/uefi-run -- cgit 1.4.1-3-g733a5 From ff84ecd68c330874352a36acfff45cfdb6bb4a2b Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sat, 13 Jan 2024 19:49:39 +0100 Subject: Allow unauthorized users to user the has-merge-commits label So they can remove it after they've removed the merge commit. --- triagebot.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/triagebot.toml b/triagebot.toml index 4a84f3caa95..72a7cf758a0 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -21,6 +21,7 @@ allow-unauthenticated = [ "perf-*", "AsyncAwait-OnDeck", "needs-triage", + "has-merge-commits", ] [glacier] -- cgit 1.4.1-3-g733a5