Rust support
Subsystems (14)
Miguel Ojeda
maintainerv10 cover Rust support
Rust support
This is the patch series (v10) to add support for Rust as a second language to the Linux kernel.
If you are interested in following this effort, please join us in the mailing list at:
and take a look at the project itself at:
https://github.com/Rust-for-Linux
As usual, special thanks go to ISRG (Internet Security Research Group) and Google for their financial support on this endeavor.
Cheers,
Miguel
--
# Rust support
This cover letter explains the major changes and updates done since the previous ones. For those, please see:
RFC: https://lore.kernel.org/lkml/[email protected]/ v1: https://lore.kernel.org/lkml/[email protected]/ v2: https://lore.kernel.org/lkml/[email protected]/ v3: https://lore.kernel.org/lkml/[email protected]/ v4: https://lore.kernel.org/lkml/[email protected]/ v5: https://lore.kernel.org/lkml/[email protected]/ v6: https://lore.kernel.org/lkml/[email protected]/ v7: https://lore.kernel.org/lkml/[email protected]/ v8: https://lore.kernel.org/lkml/[email protected]/ v9: https://lore.kernel.org/lkml/[email protected]/
This is v9 with only minimal/trivial changes, intended for v6.1:
- scripts/kallsyms.c: replaced sizeof with ARRAY_SIZE.
- scripts/kallsyms.c: added a comment on KSYM_NAME_LEN_BUFFER to clarify why the _Static_assert is needed.
- Makefile: added a comment on export RUSTC_BOOTSTRAP := 1 to explain that it enables unstable features in the stable compiler.
- Moved min-tool-version.sh changes to commit "scripts: add
`rust_is_available.sh`".
- Reworded commit "rust: import upstream alloc crate" to add a script snippet to verify that the contents match upstream.
- Reworded commit "rust: add C helpers" to explain that the file will grow over time.
- Picked Reviewed-by and Tested-by tags.
- Rebased on top of v6.0-rc7, which clears a few conflicts.
Most of the code has been around in linux-next for some months now. In particular, v9 has been 7 weeks there.
## Patch series status
The Rust support is still to be considered experimental. However, support is good enough that kernel developers can start working on the Rust abstractions for subsystems and write drivers and other modules.
The current series will appear in the next linux-next, as usual.
I have kept the docs as they were in v8/v9 since they showcase best what the docs would eventually look like:
https://rust-for-linux.github.io/docs/kernel/
As usual, please see the following link for the live list of unstable Rust features we are using (note that this trimmed version does not require all of them):
https://github.com/Rust-for-Linux/linux/issues/2
## Conferences, meetings and liaisons
Thanks a lot to everyone that joined us in LPC 2022 (Linux Plumbers Conference) for the Rust MC (microconference)!
https://lpc.events/event/16/sessions/150/ https://www.youtube.com/watch?v=Xw9pKeJ-4Bw
In addition, I would like to personally thank Google and ISRG (Internet Security Research Group) for sponsoring Kangrejos, the Rust for Linux workshop; and everyone that made the effort to travel to Spain before LPC:
## Acknowledgements
The signatures in the main commits correspond to the people that wrote code that has ended up in them at the present time. For details on contributions to code and discussions, please see our repository:
https://github.com/Rust-for-Linux/linux
However, we would like to give credit to everyone that has contributed in one way or another to the Rust for Linux project. Since the previous cover letter:
- Kees Cook, Nick Desaulniers, Konstantin Shelekhin and Masahiro Yamada for their reviews of some of the v9 patches.
- Matthew Wilcox, Linus Torvalds, comex, Eric W. Biederman, Greg Kroah-Hartman and Geert Stappers for their feedback on v9.
- Asahi Lina for working on her M1 GPU driver.
- FUJITA Tomonori for continuing his work on PCI, IRQ, BAR, DMA, ioremap... support for a NVMe Rust driver, as well as adding be16/32/64 and le16/32/64 types.
- Li Hongyu for working on making the get_id_info function more general so that it is not tied to platform, continuing the work on the virtio abstraction and the virtio-net driver, which includes abstractions for ethtool, scatterlist, NAPI...
- Arnaldo Carvalho de Melo for releasing pahole 1.24 with support for --lang and --lang_exclude, useful "to exclude Rust compile units while aspects of the DWARF generated for it get sorted out in a way that the kernel BPF verifier don't refuse loading the BTF generated from them".
- Martin Rodriguez Reboredo for working on USB abstractions as well as using the new pahole --lang_exclude feature to exclude Rust compilation units.
- David Gow for fixing the UML support.
- Adam Bratschi-Kaye for redoing his debugfs implementation without
`seq_file`.
- Alice Ryhl for continuing her work on adding BINDER_TYPE_PTR support.
- Philipp Gesang for updating the sysctl module to deal with commit 32927393dc1c ("sysctl: pass kernel pointers to ->proc_handler") as well as improving the module! macro to allow overriding the name of module param constants.
- Masahiro Yamada for proposing a refactor of the Kbuild support for Rust as well as removing the -v option of the rust_is_available.sh script.
- Russell Currey for making scripts/rust_is_available.sh compatible with using multiple words for $CC, e.g. for ccache.
- Jalil David Salamé Messina for marking the bit function as const so that it can be used for e.g. creating const masks.
- Jon Olson for continuing his work on a cpu module with utilities for SMP systems.
- Raghvender for working on improving a check on scripts/rust-is-available.sh.
- Angelos for working on using NonZeroI16 as the Error inner type.
- Finn Behrens for updating his work on making it possible to compile the kernel on macOS with Rust enabled.
- Kaviraj Kanagaraj for suggesting improvements to the quick start guide.
- Sergio González Collado for suggesting improvements to the Makefile to show an extra message.
- Wei Liu for taking the time to answer questions from newcomers in Zulip.
- Philip Li, Yujie Liu et al. for continuing their work on adding Rust support to the Intel 0DAY/LKP kernel test robot.
- Philip Herron and Arthur Cohen (and his supporters Open Source Security and Embecosm) et al. for their ongoing work on Rust GCC.
- Antoni Boucher (and his supporters) et al. for their ongoing work on rustc_codegen_gcc.
- Emilio Cobos Álvarez, Christian Poveda et al. for their work on bindgen, including on issues that affect the kernel.
- Mats Larsen, Marc Poulhiès et al. for their ongoing work on improving Rust support in Compiler Explorer.
- Many folks that have reported issues, tested the project, helped spread the word, joined discussions and contributed in other ways!
Please see also the acknowledgements on the previous cover letters.
Boqun Feng (2):
kallsyms: use ARRAY_SIZE instead of hardcoded size
kallsyms: avoid hardcoding buffer size
Daniel Xu (1):
scripts: add is_rust_module.sh
Gary Guo (1):
vsprintf: add new %pA format specifier
Miguel Ojeda (22):
kallsyms: add static relationship between KSYM_NAME_LEN{,_BUFFER}
kallsyms: support "big" kernel symbols
kallsyms: increase maximum kernel symbol length to 512
rust: add C helpers
rust: import upstream alloc crate
rust: adapt alloc crate to the kernel
rust: add compiler_builtins crate
rust: add macros crate
rust: add bindings crate
rust: export generated symbols
scripts: checkpatch: diagnose uses of %pA in the C side as errors
scripts: checkpatch: enable language-independent checks for Rust
scripts: decode_stacktrace: demangle Rust symbols
scripts: add generate_rust_analyzer.py
scripts: add generate_rust_target.rs
scripts: add rust_is_available.sh
rust: add .rustfmt.toml
Kbuild: add Rust support
docs: add Rust documentation
x86: enable initial Rust support
samples: add first Rust examples
MAINTAINERS: Rust
Wedson Almeida Filho (1):
rust: add kernel crate
.gitignore | 6 + .rustfmt.toml | 12 + Documentation/core-api/printk-formats.rst | 10 + Documentation/doc-guide/kernel-doc.rst | 3 + Documentation/index.rst | 1 + Documentation/kbuild/kbuild.rst | 17 + Documentation/kbuild/makefiles.rst | 50 +- Documentation/process/changes.rst | 41 + Documentation/rust/arch-support.rst | 19 + Documentation/rust/coding-guidelines.rst | 216 ++ Documentation/rust/general-information.rst | 79 + Documentation/rust/index.rst | 22 + Documentation/rust/quick-start.rst | 232 ++ MAINTAINERS | 18 + Makefile | 172 +- arch/Kconfig | 6 + arch/x86/Kconfig | 1 + arch/x86/Makefile | 10 + include/linux/compiler_types.h | 6 +- include/linux/kallsyms.h | 2 +- init/Kconfig | 46 +- kernel/configs/rust.config | 1 + kernel/kallsyms.c | 26 +- kernel/livepatch/core.c | 4 +- lib/Kconfig.debug | 34 + lib/vsprintf.c | 13 + rust/.gitignore | 8 + rust/Makefile | 381 +++ rust/alloc/README.md | 33 + rust/alloc/alloc.rs | 440 +++ rust/alloc/borrow.rs | 498 +++ rust/alloc/boxed.rs | 2028 +++++++++++ rust/alloc/collections/mod.rs | 156 + rust/alloc/lib.rs | 244 ++ rust/alloc/raw_vec.rs | 527 +++ rust/alloc/slice.rs | 1204 +++++++ rust/alloc/vec/drain.rs | 186 ++ rust/alloc/vec/drain_filter.rs | 145 + rust/alloc/vec/into_iter.rs | 366 ++ rust/alloc/vec/is_zero.rs | 120 + rust/alloc/vec/mod.rs | 3140 ++++++++++++++++++ rust/alloc/vec/partial_eq.rs | 49 + rust/bindgen_parameters | 21 + rust/bindings/bindings_helper.h | 13 + rust/bindings/lib.rs | 53 + rust/compiler_builtins.rs | 63 + rust/exports.c | 21 + rust/helpers.c | 51 + rust/kernel/allocator.rs | 64 + rust/kernel/error.rs | 59 + rust/kernel/lib.rs | 78 + rust/kernel/prelude.rs | 20 + rust/kernel/print.rs | 198 ++ rust/kernel/str.rs | 72 + rust/macros/helpers.rs | 51 + rust/macros/lib.rs | 72 + rust/macros/module.rs | 282 ++ samples/Kconfig | 2 + samples/Makefile | 1 + samples/rust/Kconfig | 30 + samples/rust/Makefile | 5 + samples/rust/hostprogs/.gitignore | 3 + samples/rust/hostprogs/Makefile | 5 + samples/rust/hostprogs/a.rs | 7 + samples/rust/hostprogs/b.rs | 5 + samples/rust/hostprogs/single.rs | 12 + samples/rust/rust_minimal.rs | 38 + scripts/.gitignore | 1 + scripts/Kconfig.include | 6 +- scripts/Makefile | 3 + scripts/Makefile.build | 60 + scripts/Makefile.debug | 8 + scripts/Makefile.host | 34 +- scripts/Makefile.lib | 12 + scripts/Makefile.modfinal | 8 +- scripts/cc-version.sh | 12 +- scripts/checkpatch.pl | 12 +- scripts/decode_stacktrace.sh | 14 + scripts/generate_rust_analyzer.py | 135 + scripts/generate_rust_target.rs | 182 + scripts/is_rust_module.sh | 16 + scripts/kallsyms.c | 53 +- scripts/kconfig/confdata.c | 75 + scripts/min-tool-version.sh | 6 + scripts/rust_is_available.sh | 160 + scripts/rust_is_available_bindgen_libclang.h | 2 + tools/include/linux/kallsyms.h | 2 +- tools/lib/perf/include/perf/event.h | 2 +- tools/lib/symbol/kallsyms.h | 2 +- 89 files changed, 12552 insertions(+), 51 deletions(-) create mode 100644 .rustfmt.toml create mode 100644 Documentation/rust/arch-support.rst create mode 100644 Documentation/rust/coding-guidelines.rst create mode 100644 Documentation/rust/general-information.rst create mode 100644 Documentation/rust/index.rst create mode 100644 Documentation/rust/quick-start.rst create mode 100644 kernel/configs/rust.config create mode 100644 rust/.gitignore create mode 100644 rust/Makefile create mode 100644 rust/alloc/README.md create mode 100644 rust/alloc/alloc.rs create mode 100644 rust/alloc/borrow.rs create mode 100644 rust/alloc/boxed.rs create mode 100644 rust/alloc/collections/mod.rs create mode 100644 rust/alloc/lib.rs create mode 100644 rust/alloc/raw_vec.rs create mode 100644 rust/alloc/slice.rs create mode 100644 rust/alloc/vec/drain.rs create mode 100644 rust/alloc/vec/drain_filter.rs create mode 100644 rust/alloc/vec/into_iter.rs create mode 100644 rust/alloc/vec/is_zero.rs create mode 100644 rust/alloc/vec/mod.rs create mode 100644 rust/alloc/vec/partial_eq.rs create mode 100644 rust/bindgen_parameters create mode 100644 rust/bindings/bindings_helper.h create mode 100644 rust/bindings/lib.rs create mode 100644 rust/compiler_builtins.rs create mode 100644 rust/exports.c create mode 100644 rust/helpers.c create mode 100644 rust/kernel/allocator.rs create mode 100644 rust/kernel/error.rs create mode 100644 rust/kernel/lib.rs create mode 100644 rust/kernel/prelude.rs create mode 100644 rust/kernel/print.rs create mode 100644 rust/kernel/str.rs create mode 100644 rust/macros/helpers.rs create mode 100644 rust/macros/lib.rs create mode 100644 rust/macros/module.rs create mode 100644 samples/rust/Kconfig create mode 100644 samples/rust/Makefile create mode 100644 samples/rust/hostprogs/.gitignore create mode 100644 samples/rust/hostprogs/Makefile create mode 100644 samples/rust/hostprogs/a.rs create mode 100644 samples/rust/hostprogs/b.rs create mode 100644 samples/rust/hostprogs/single.rs create mode 100644 samples/rust/rust_minimal.rs create mode 100755 scripts/generate_rust_analyzer.py create mode 100644 scripts/generate_rust_target.rs create mode 100755 scripts/is_rust_module.sh create mode 100755 scripts/rust_is_available.sh create mode 100644 scripts/rust_is_available_bindgen_libclang.h
base-commit: f76349cf41451c5c42a99f18a9163377e4b364ff
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 1/27 kallsyms: use `ARRAY_SIZE` instead of hardcoded size
From: Boqun Feng <[email protected]>
This removes one place where the 500 constant is hardcoded.
--- scripts/kallsyms.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/kallsyms.c +1 -1
@@ -206,7 +206,7 @@ static struct sym_entry *read_symbol(FILE *in) rc =fscanf (in,"%llx %c %499s\n" , &addr, &type, name);if (rc !=3 ) { -if (rc !=EOF &&fgets (name,500 , in) ==NULL ) +if (rc !=EOF &&fgets (name,ARRAY_SIZE (name), in) ==NULL )fprintf (stderr,"Read error or end of file.\n" );return NULL ; }
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 2/27 kallsyms: avoid hardcoding buffer size
In reply to Miguel OjedaFrom: Boqun Feng <[email protected]>
This introduces KSYM_NAME_LEN_BUFFER in place of the previously hardcoded size of the input buffer.
It will also make it easier to update the size in a single place in a later patch.
--- scripts/kallsyms.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
scripts/kallsyms.c +8 -2
@@ -27,8 +27,14 @@#define ARRAY_SIZE (arr) (sizeof(arr) / sizeof(arr[0])) +#define _stringify_1 (x) #x +#define _stringify (x) _stringify_1(x) +#define KSYM_NAME_LEN 128 +/* A substantially bigger size than the current maximum. */ +#define KSYM_NAME_LEN_BUFFER 499 +struct sym_entry {unsigned long long addr;unsigned int len;
@@ -198,13 +204,13 @@ static void check_symbol_range(const char *sym, unsigned long long addr,static struct sym_entry *read_symbol (FILE *in) { -char name[500 ], type; +char name[KSYM_NAME_LEN_BUFFER +1 ], type;unsigned long long addr;unsigned int len;struct sym_entry *sym;int rc; - rc =fscanf (in,"%llx %c %499s\n" , &addr, &type, name); + rc = fscanf(in, "%llx %c %" _stringify(KSYM_NAME_LEN_BUFFER) "s\n", &addr, &type, name);if (rc !=3 ) {if (rc !=EOF &&fgets (name,ARRAY_SIZE (name), in) ==NULL )fprintf (stderr,"Read error or end of file.\n" );
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 3/27 kallsyms: add static relationship between `KSYM_NAME_LEN{,_BUFFER}`
In reply to Miguel OjedaThis adds a static assert to ensure KSYM_NAME_LEN_BUFFER gets updated when KSYM_NAME_LEN changes.
The relationship used is one that keeps the new size (512+1) close to the original buffer size (500).
--- scripts/kallsyms.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
scripts/kallsyms.c +12 -2
@@ -32,8 +32,18 @@#define KSYM_NAME_LEN 128 -/* A substantially bigger size than the current maximum. */ -#define KSYM_NAME_LEN_BUFFER 499 +/* +* A substantially bigger size than the current maximum. +* +* It cannot be defined as an expression because it gets stringified +* for the fscanf() format string. Therefore, a _Static_assert() is +* used instead to maintain the relationship with KSYM_NAME_LEN. +*/ +#define KSYM_NAME_LEN_BUFFER 512 +_Static_assert ( +KSYM_NAME_LEN_BUFFER ==KSYM_NAME_LEN *4 , +"Please keep KSYM_NAME_LEN_BUFFER in sync with KSYM_NAME_LEN" +);struct sym_entry {unsigned long long addr;
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 4/27 kallsyms: support "big" kernel symbols
In reply to Miguel OjedaRust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc.
Increasing to 255 is not enough in some cases, therefore introduce longer lengths to the symbol table.
In order to avoid increasing all lengths to 2 bytes (since most of them are small, including many Rust ones), use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.
--- kernel/kallsyms.c | 26 ++++++++++++++++++++++---- scripts/kallsyms.c | 29 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-)
kernel/kallsyms.c +22 -4
@@ -50,12 +50,20 @@ static unsigned int kallsyms_expand_symbol(unsigned int off, data = &kallsyms_names[off]; len = *data; data++; + off++; + +/* If MSB is 1, it is a "big" symbol, so needs an additional byte. */ +if ((len &0x80 ) !=0 ) { + len = (len &0x7F ) | (*data <<7 ); + data++; + off++; + }/* * Update the offset to return the offset for the next symbol on * the compressed stream. */ - off += len +1 ; + off += len;/* * For every byte on the compressed symbol data, copy the table
@@ -108,7 +116,7 @@ static char kallsyms_get_symbol_type(unsigned int off)static unsigned int get_symbol_offset (unsigned long pos) {const u8 *name; -int i; +int i, len;/* * Use the closest marker we have. We have markers every 256 positions,
@@ -122,8 +130,18 @@ static unsigned int get_symbol_offset(unsigned long pos)* so we just need to add the len to the current pointer for every * symbol we wish to skip. */ -for (i =0 ; i < (pos &0xFF ); i++) - name = name + (*name) +1 ; +for (i =0 ; i < (pos &0xFF ); i++) { + len = *name; + +/* +* If MSB is 1, it is a "big" symbol, so we need to look into +* the next byte (and skip it, too). +*/ +if ((len &0x80 ) !=0 ) + len = ((len &0x7F ) | (name[1 ] <<7 )) +1 ; + + name = name + len +1 ; + }return name - kallsyms_names; }
scripts/kallsyms.c +26 -3
@@ -487,12 +487,35 @@ static void write_src(void)if ((i &0xFF ) ==0 ) markers[i >>8 ] = off; -printf ("\t.byte 0x%02x" , table[i]->len); +/* There cannot be any symbol of length zero. */ +if (table[i]->len ==0 ) { +fprintf (stderr,"kallsyms failure: " +"unexpected zero symbol length\n" ); +exit (EXIT_FAILURE ); + } + +/* Only lengths that fit in up-to-two-byte ULEB128 are supported. */ +if (table[i]->len >0x3FFF ) { +fprintf (stderr,"kallsyms failure: " +"unexpected huge symbol length\n" ); +exit (EXIT_FAILURE ); + } + +/* Encode length with ULEB128. */ +if (table[i]->len <=0x7F ) { +/* Most symbols use a single byte for the length. */ +printf ("\t.byte 0x%02x" , table[i]->len); + off += table[i]->len +1 ; + }else { +/* "Big" symbols use two bytes. */ +printf ("\t.byte 0x%02x, 0x%02x" , + (table[i]->len &0x7F ) |0x80 , + (table[i]->len >>7 ) &0x7F ); + off += table[i]->len +2 ; + }for (k =0 ; k < table[i]->len; k++)printf (", 0x%02x" , table[i]->sym[k]);printf ("\n" ); - - off += table[i]->len +1 ; }printf ("\n" );
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 5/27 kallsyms: increase maximum kernel symbol length to 512
In reply to Miguel OjedaRust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc. For instance, the following code:
pub mod my_module {
pub struct MyType;
pub struct MyGenericType<T>(T);
pub trait MyTrait {
fn my_method() -> u32;
}
impl MyTrait for MyGenericType<MyType> {
fn my_method() -> u32 {
42
}
}
}generates a symbol of length 96 when using the upcoming v0 mangling scheme:
_RNvXNtCshGpAVYOtgW1_7example9my_moduleINtB2_13MyGenericTypeNtB2_6MyTypeENtB2_7MyTrait9my_method
At the moment, Rust symbols may reach up to 300 in length. Setting 512 as the maximum seems like a reasonable choice to keep some headroom.
--- include/linux/kallsyms.h | 2 +- kernel/livepatch/core.c | 4 ++-- scripts/kallsyms.c | 4 ++-- tools/include/linux/kallsyms.h | 2 +- tools/lib/perf/include/perf/event.h | 2 +- tools/lib/symbol/kallsyms.h | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-)
include/linux/kallsyms.h +1 -1
@@ -15,7 +15,7 @@#include <asm/sections.h> -#define KSYM_NAME_LEN 128 +#define KSYM_NAME_LEN 512#define KSYM_SYMBOL_LEN (sizeof("%s+%#lx/%#lx [%s %s]") + \ (KSYM_NAME_LEN - 1) + \ 2*(BITS_PER_LONG*3/10) + (MODULE_NAME_LEN - 1) + \
kernel/livepatch/core.c +2 -2
@@ -213,7 +213,7 @@ static int klp_resolve_symbols(Elf_Shdr *sechdrs, const char *strtab,* we use the smallest/strictest upper bound possible (56, based on * the current definition of MODULE_NAME_LEN) to prevent overflows. */ -BUILD_BUG_ON (MODULE_NAME_LEN <56 ||KSYM_NAME_LEN !=128 ); +BUILD_BUG_ON (MODULE_NAME_LEN <56 ||KSYM_NAME_LEN !=512 ); relas = (Elf_Rela *) relasec->sh_addr;/* For each rela in this klp relocation section */
@@ -227,7 +227,7 @@ static int klp_resolve_symbols(Elf_Shdr *sechdrs, const char *strtab,/* Format: .klp.sym.sym_objname.sym_name,sympos */ cnt =sscanf (strtab + sym->st_name, -".klp.sym.%55[^.].%127[^,],%lu" , +".klp.sym.%55[^.].%511[^,],%lu" , sym_objname, sym_name, &sympos);if (cnt !=3 ) { pr_err("symbol %s has an incorrectly formatted name\n",
scripts/kallsyms.c +2 -2
@@ -30,7 +30,7 @@#define _stringify_1 (x) #x#define _stringify (x) _stringify_1(x) -#define KSYM_NAME_LEN 128 +#define KSYM_NAME_LEN 512/* * A substantially bigger size than the current maximum.
@@ -39,7 +39,7 @@* for the fscanf() format string. Therefore, a _Static_assert() is * used instead to maintain the relationship with KSYM_NAME_LEN. */ -#define KSYM_NAME_LEN_BUFFER 512 +#define KSYM_NAME_LEN_BUFFER 2048_Static_assert (KSYM_NAME_LEN_BUFFER ==KSYM_NAME_LEN *4 , "Please keep KSYM_NAME_LEN_BUFFER in sync with KSYM_NAME_LEN"
tools/include/linux/kallsyms.h +1 -1
@@ -6,7 +6,7 @@#include <stdio.h> #include <unistd.h> -#define KSYM_NAME_LEN 128 +#define KSYM_NAME_LEN 512struct module ;
tools/lib/perf/include/perf/event.h +1 -1
@@ -97,7 +97,7 @@ struct perf_record_throttle { };#ifndef KSYM_NAME_LEN -#define KSYM_NAME_LEN 256 +#define KSYM_NAME_LEN 512#endif struct perf_record_ksymbol {
tools/lib/symbol/kallsyms.h +1 -1
@@ -7,7 +7,7 @@#include <linux/types.h> #ifndef KSYM_NAME_LEN -#define KSYM_NAME_LEN 256 +#define KSYM_NAME_LEN 512#endif static inline u8 kallsyms2elf_binding (char type)
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 6/27 rust: add C helpers
In reply to Miguel OjedaIntroduces the source file that will contain forwarders to C macros and inlined functions.
Initially this only contains a single helper, but will gain more as more functionality is added to the kernel crate in the future.
--- rust/helpers.c | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 rust/helpers.c
rust/helpers.c new file +51 -0
@@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Non-trivial C macros cannot be used in Rust. Similarly, inlined C functions +* cannot be called either. This file explicitly creates functions ("helpers") +* that wrap those so that they can be called from Rust. +* +* Even though Rust kernel modules should never use directly the bindings, some +* of these helpers need to be exported because Rust generics and inlined +* functions may not get their code generated in the crate where they are +* defined. Other helpers, called from non-inline functions, may not be +* exported, in principle. However, in general, the Rust compiler does not +* guarantee codegen will be performed for a non-inline function either. +* Therefore, this file exports all the helpers. In the future, this may be +* revisited to reduce the number of exports after the compiler is informed +* about the places codegen is required. +* +* All symbols are exported as GPL-only to guarantee no GPL-only feature is +* accidentally exposed. +*/ + +#include <linux/bug.h> +#include <linux/build_bug.h> + +__noreturn void rust_helper_BUG (void ) +{ +BUG (); +} +EXPORT_SYMBOL_GPL (rust_helper_BUG); + +/* +* We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type +* as the Rust `usize` type, so we can use it in contexts where Rust +* expects a `usize` like slice (array) indices. `usize` is defined to be +* the same as C's `uintptr_t` type (can hold any pointer) but not +* necessarily the same as `size_t` (can hold the size of any single +* object). Most modern platforms use the same concrete integer type for +* both of them, but in case we find ourselves on a platform where +* that's not true, fail early instead of risking ABI or +* integer-overflow issues. +* +* If your platform fails this assertion, it means that you are in +* danger of integer-overflow bugs (even if you attempt to remove +* `--size_t-is-usize`). It may be easiest to change the kernel ABI on +* your platform such that `size_t` matches `uintptr_t` (i.e., to increase +* `size_t`, because `uintptr_t` has to be at least as big as `size_t`). +*/ +static_assert ( +sizeof (size_t ) ==sizeof (uintptr_t ) && + __alignof__(size_t ) == __alignof__(uintptr_t ), +"Rust code expects C `size_t` to match Rust `usize`" +);
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 7/27 rust: import upstream `alloc` crate
In reply to Miguel OjedaThis is a subset of the Rust standard library alloc crate, version 1.62.0, licensed under "Apache-2.0 OR MIT", from:
https://github.com/rust-lang/rust/tree/1.62.0/library/alloc/src
The files are copied as-is, with no modifications whatsoever (not even adding the SPDX identifiers).
For copyright details, please see:
https://github.com/rust-lang/rust/blob/1.62.0/COPYRIGHT
The next patch modifies these files as needed for use within the kernel. This patch split allows reviewers to double-check the import and to clearly see the differences introduced.
Vendoring alloc, at least for the moment, allows us to have fallible allocations support (i.e. the try_* versions of methods which return a Result instead of panicking) early on. It also gives a bit more freedom to experiment with new interfaces and to iterate quickly.
Eventually, the goal is to have everything the kernel needs in upstream alloc and drop it from the kernel tree.
For a summary of work on alloc happening upstream, please see:
https://github.com/Rust-for-Linux/linux/issues/408
The following script may be used to verify the contents:
for path in $(cd rust/alloc/ && find . -type f -name '*.rs'); do
curl --silent --show-error --location \
https://github.com/rust-lang/rust/raw/1.62.0/library/alloc/src/$path \
| diff --unified rust/alloc/$path - && echo $path: OK
done--- rust/alloc/alloc.rs | 438 +++++ rust/alloc/borrow.rs | 496 +++++ rust/alloc/boxed.rs | 2024 +++++++++++++++++++++ rust/alloc/collections/mod.rs | 154 ++ rust/alloc/lib.rs | 236 +++ rust/alloc/raw_vec.rs | 518 ++++++ rust/alloc/slice.rs | 1202 ++++++++++++ rust/alloc/vec/drain.rs | 184 ++ rust/alloc/vec/drain_filter.rs | 143 ++ rust/alloc/vec/into_iter.rs | 362 ++++ rust/alloc/vec/is_zero.rs | 118 ++ rust/alloc/vec/mod.rs | 3115 ++++++++++++++++++++++++++++++++ rust/alloc/vec/partial_eq.rs | 47 + 13 files changed, 9037 insertions(+) create mode 100644 rust/alloc/alloc.rs create mode 100644 rust/alloc/borrow.rs create mode 100644 rust/alloc/boxed.rs create mode 100644 rust/alloc/collections/mod.rs create mode 100644 rust/alloc/lib.rs create mode 100644 rust/alloc/raw_vec.rs create mode 100644 rust/alloc/slice.rs create mode 100644 rust/alloc/vec/drain.rs create mode 100644 rust/alloc/vec/drain_filter.rs create mode 100644 rust/alloc/vec/into_iter.rs create mode 100644 rust/alloc/vec/is_zero.rs create mode 100644 rust/alloc/vec/mod.rs create mode 100644 rust/alloc/vec/partial_eq.rs
rust/alloc/alloc.rs new file +438 -0
@@ -0,0 +1,438 @@ +//! Memory allocation APIs + +#![stable(feature = "alloc_module" , since = "1.28.0" )] + +#[cfg(not(test))] +use core::intrinsics; +use core::intrinsics::{min_align_of_val, size_of_val}; + +use core::ptr::Unique ; +#[cfg(not(test))] +use core::ptr::{self,NonNull }; + +#[stable(feature = "alloc_module" , since = "1.28.0" )] +#[doc(inline)] +pub use core::alloc::*; + +use core::marker::Destruct ; + +#[cfg(test)] +mod tests; + +extern "Rust" { +// These are the magic symbols to call the global allocator. rustc generates +// them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute +// (the code expanding that attribute macro generates those functions), or to call +// the default implementations in libstd (`__rdl_alloc` etc. in `library/std/src/alloc.rs`) +// otherwise. +// The rustc fork of LLVM also special-cases these function names to be able to optimize them +// like `malloc`, `realloc`, and `free`, respectively. +#[rustc_allocator] +#[rustc_allocator_nounwind] +fn __rust_alloc (size:usize , align:usize ) -> *mut u8 ; +#[rustc_allocator_nounwind] +fn __rust_dealloc (ptr: *mut u8 , size:usize , align:usize ); +#[rustc_allocator_nounwind] +fn __rust_realloc (ptr: *mut u8 , old_size:usize , align:usize , new_size:usize ) -> *mut u8 ; +#[rustc_allocator_nounwind] +fn __rust_alloc_zeroed (size:usize , align:usize ) -> *mut u8 ; +} + +/// The global memory allocator. +/// +/// This type implements the [`Allocator`] trait by forwarding calls +/// to the allocator registered with the `#[global_allocator]` attribute +/// if there is one, or the `std` crate’s default. +/// +/// Note: while this type is unstable, the functionality it provides can be +/// accessed through the [free functions in `alloc`](self#functions). +#[unstable(feature = "allocator_api" , issue = "32838" )] +#[derive( Copy , Clone , Default , Debug )] +#[cfg(not(test))] +pub struct Global ; + +#[cfg(test)] +pub use std::alloc::Global ; + +/// Allocate memory with the global allocator. +/// +/// This function forwards calls to the [`GlobalAlloc::alloc`] method +/// of the allocator registered with the `#[global_allocator]` attribute +/// if there is one, or the `std` crate’s default. +/// +/// This function is expected to be deprecated in favor of the `alloc` method +/// of the [`Global`] type when it and the [`Allocator`] trait become stable. +/// +/// # Safety +/// +/// See [`GlobalAlloc::alloc`]. +/// +/// # Examples +/// +/// ``` +/// use std::alloc::{alloc, dealloc, Layout}; +/// +/// unsafe { +/// let layout = Layout::new::<u16>(); +/// let ptr = alloc(layout); +/// +/// *(ptr as *mut u16) = 42; +/// assert_eq!(*(ptr as *mut u16), 42); +/// +/// dealloc(ptr, layout); +/// } +/// ``` +#[stable(feature = "global_alloc" , since = "1.28.0" )] +#[must_use = "losing the pointer will leak memory" ] +#[inline] +pub unsafe fn alloc (layout:Layout ) -> *mut u8 { +unsafe {__rust_alloc (layout.size (), layout.align ()) } +} + +/// Deallocate memory with the global allocator. +/// +/// This function forwards calls to the [`GlobalAlloc::dealloc`] method +/// of the allocator registered with the `#[global_allocator]` attribute +/// if there is one, or the `std` crate’s default. +/// +/// This function is expected to be deprecated in favor of the `dealloc` method +/// of the [`Global`] type when it and the [`Allocator`] trait become stable. +/// +/// # Safety +/// +/// See [`GlobalAlloc::dealloc`]. +#[stable(feature = "global_alloc" , since = "1.28.0" )] +#[inline] +pub unsafe fn dealloc (ptr: *mut u8 , layout:Layout ) { +unsafe {__rust_dealloc (ptr, layout.size (), layout.align ()) } +} + +/// Reallocate memory with the global allocator. +/// +/// This function forwards calls to the [`GlobalAlloc::realloc`] method +/// of the allocator registered with the `#[global_allocator]` attribute +/// if there is one, or the `std` crate’s default. +/// +/// This function is expected to be deprecated in favor of the `realloc` method +/// of the [`Global`] type when it and the [`Allocator`] trait become stable. +/// +/// # Safety +/// +/// See [`GlobalAlloc::realloc`]. +#[stable(feature = "global_alloc" , since = "1.28.0" )] +#[must_use = "losing the pointer will leak memory" ] +#[inline] +pub unsafe fn realloc (ptr: *mut u8 , layout:Layout , new_size:usize ) -> *mut u8 { +unsafe {__rust_realloc (ptr, layout.size (), layout.align (), new_size) } +} + +/// Allocate zero-initialized memory with the global allocator. +/// +/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method +/// of the allocator registered with the `#[global_allocator]` attribute +/// if there is one, or the `std` crate’s default. +/// +/// This function is expected to be deprecated in favor of the `alloc_zeroed` method +/// of the [`Global`] type when it and the [`Allocator`] trait become stable. +/// +/// # Safety +/// +/// See [`GlobalAlloc::alloc_zeroed`]. +/// +/// # Examples +/// +/// ``` +/// use std::alloc::{alloc_zeroed, dealloc, Layout}; +/// +/// unsafe { +/// let layout = Layout::new::<u16>(); +/// let ptr = alloc_zeroed(layout); +/// +/// assert_eq!(*(ptr as *mut u16), 0); +/// +/// dealloc(ptr, layout); +/// } +/// ``` +#[stable(feature = "global_alloc" , since = "1.28.0" )] +#[must_use = "losing the pointer will leak memory" ] +#[inline] +pub unsafe fn alloc_zeroed (layout:Layout ) -> *mut u8 { +unsafe {__rust_alloc_zeroed (layout.size (), layout.align ()) } +} + +#[cfg(not(test))] +impl Global { +#[inline] +fn alloc_impl (&self, layout:Layout , zeroed:bool ) ->Result <NonNull <[u8 ]>,AllocError > { +match layout.size () { +0 =>Ok (NonNull ::slice_from_raw_parts (layout.dangling (),0 )), +// SAFETY: `layout` is non-zero in size, + size =>unsafe { +let raw_ptr =if zeroed {alloc_zeroed (layout) }else {alloc (layout) }; +let ptr =NonNull ::new (raw_ptr).ok_or (AllocError )?; +Ok (NonNull ::slice_from_raw_parts (ptr, size)) + }, + } + } + +// SAFETY: Same as `Allocator::grow` +#[inline] +unsafe fn grow_impl ( + &self, + ptr:NonNull <u8 >, + old_layout:Layout , + new_layout:Layout , + zeroed:bool , + ) ->Result <NonNull <[u8 ]>,AllocError > { +debug_assert! ( + new_layout.size () >= old_layout.size (), +"`new_layout.size()` must be greater than or equal to `old_layout.size()`" + ); + +match old_layout.size () { +0 => self.alloc_impl (new_layout, zeroed), + +// SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size` +// as required by safety conditions. Other conditions must be upheld by the caller + old_sizeif old_layout.align () == new_layout.align () =>unsafe { +let new_size = new_layout.size (); + +// `realloc` probably checks for `new_size >= old_layout.size()` or something similar. + intrinsics::assume (new_size >= old_layout.size ()); + +let raw_ptr =realloc (ptr.as_ptr (), old_layout, new_size); +let ptr =NonNull ::new (raw_ptr).ok_or (AllocError )?; +if zeroed { + raw_ptr.add (old_size).write_bytes (0 , new_size - old_size); + } +Ok (NonNull ::slice_from_raw_parts (ptr, new_size)) + }, + +// SAFETY: because `new_layout.size()` must be greater than or equal to `old_size`, +// both the old and new memory allocation are valid for reads and writes for `old_size` +// bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap +// `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract +// for `dealloc` must be upheld by the caller. + old_size =>unsafe { +let new_ptr = self.alloc_impl (new_layout, zeroed)?; + ptr::copy_nonoverlapping (ptr.as_ptr (), new_ptr.as_mut_ptr (), old_size); + self.deallocate (ptr, old_layout); +Ok (new_ptr) + }, + } + } +} + +#[unstable(feature = "allocator_api" , issue = "32838" )] +#[cfg(not(test))] +unsafe impl Allocator for Global { +#[inline] +fn allocate (&self, layout:Layout ) ->Result <NonNull <[u8 ]>,AllocError > { + self.alloc_impl (layout,false ) + } + +#[inline] +fn allocate_zeroed (&self, layout:Layout ) ->Result <NonNull <[u8 ]>,AllocError > { + self.alloc_impl (layout,true ) + } + +#[inline] +unsafe fn deallocate (&self, ptr:NonNull <u8 >, layout:Layout ) { +if layout.size () !=0 { +// SAFETY: `layout` is non-zero in size, +// other conditions must be upheld by the caller +unsafe {dealloc (ptr.as_ptr (), layout) } + } + } + +#[inline] +unsafe fn grow ( + &self, + ptr:NonNull <u8 >, + old_layout:Layout , + new_layout:Layout , + ) ->Result <NonNull <[u8 ]>,AllocError > { +// SAFETY: all conditions must be upheld by the caller +unsafe { self.grow_impl (ptr, old_layout, new_layout,false ) } + } + +#[inline] +unsafe fn grow_zeroed ( + &self, + ptr:NonNull <u8 >, + old_layout:Layout , + new_layout:Layout , + ) ->Result <NonNull <[u8 ]>,AllocError > { +// SAFETY: all conditions must be upheld by the caller +unsafe { self.grow_impl (ptr, old_layout, new_layout,true ) } + } + +#[inline] +unsafe fn shrink ( + &self, + ptr:NonNull <u8 >, + old_layout:Layout , + new_layout:Layout , + ) ->Result <NonNull <[u8 ]>,AllocError > { +debug_assert! ( + new_layout.size () <= old_layout.size (), +"`new_layout.size()` must be smaller than or equal to `old_layout.size()`" + ); + +match new_layout.size () { +// SAFETY: conditions must be upheld by the caller +0 =>unsafe { + self.deallocate (ptr, old_layout); +Ok (NonNull ::slice_from_raw_parts (new_layout.dangling (),0 )) + }, + +// SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller + new_sizeif old_layout.align () == new_layout.align () =>unsafe { +// `realloc` probably checks for `new_size <= old_layout.size()` or something similar. + intrinsics::assume (new_size <= old_layout.size ()); + +let raw_ptr =realloc (ptr.as_ptr (), old_layout, new_size); +let ptr =NonNull ::new (raw_ptr).ok_or (AllocError )?; +Ok (NonNull ::slice_from_raw_parts (ptr, new_size)) + }, + +// SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`, +// both the old and new memory allocation are valid for reads and writes for `new_size` +// bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap +// `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract +// for `dealloc` must be upheld by the caller. + new_size =>unsafe { +let new_ptr = self.allocate (new_layout)?; + ptr::copy_nonoverlapping (ptr.as_ptr (), new_ptr.as_mut_ptr (), new_size); + self.deallocate (ptr, old_layout); +Ok (new_ptr) + }, + } + } +} + +/// The allocator for unique pointers. +#[cfg(all(not(no_global_oom_handling), not(test)))] +#[lang = "exchange_malloc" ] +#[inline] +unsafe fn exchange_malloc (size:usize , align:usize ) -> *mut u8 { +let layout =unsafe {Layout ::from_size_align_unchecked (size, align) }; +match Global .allocate (layout) { +Ok (ptr) => ptr.as_mut_ptr (), +Err (_) =>handle_alloc_error (layout), + } +} + +#[cfg_attr(not(test), lang = "box_free" )] +#[inline] +#[rustc_const_unstable(feature = "const_box" , issue = "92521" )] +// This signature has to be the same as `Box`, otherwise an ICE will happen. +// When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as +// well. +// For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`, +// this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well. +pub(crate) const unsafe fn box_free<T: ?Sized, A: ~const Allocator + ~const Destruct>( + ptr:Unique <T >, + alloc:A , +) { +unsafe { +let size =size_of_val (ptr.as_ref ()); +let align =min_align_of_val (ptr.as_ref ()); +let layout =Layout ::from_size_align_unchecked (size, align); + alloc.deallocate (From ::from (ptr.cast ()), layout) + } +} + +// # Allocation error handler + +#[cfg(not(no_global_oom_handling))] +extern "Rust" { +// This is the magic symbol to call the global alloc error handler. rustc generates +// it to call `__rg_oom` if there is a `#[alloc_error_handler]`, or to call the +// default implementations below (`__rdl_oom`) otherwise. +fn __rust_alloc_error_handler (size:usize , align:usize ) -> !; +} + +/// Abort on memory allocation error or failure. +/// +/// Callers of memory allocation APIs wishing to abort computation +/// in response to an allocation error are encouraged to call this function, +/// rather than directly invoking `panic!` or similar. +/// +/// The default behavior of this function is to print a message to standard error +/// and abort the process. +/// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`]. +/// +/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html +/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html +#[stable(feature = "global_alloc" , since = "1.28.0" )] +#[rustc_const_unstable(feature = "const_alloc_error" , issue = "92523" )] +#[cfg(all(not(no_global_oom_handling), not(test)))] +#[cold] +pub const fn handle_alloc_error (layout:Layout ) -> ! { +const fn ct_error (_:Layout ) -> ! { +panic! ("allocation failed" ); + } + +fn rt_error (layout:Layout ) -> ! { +unsafe { +__rust_alloc_error_handler (layout.size (), layout.align ()); + } + } + +unsafe { core::intrinsics::const_eval_select ((layout,), ct_error, rt_error) } +} + +// For alloc test `std::alloc::handle_alloc_error` can be used directly. +#[cfg(all(not(no_global_oom_handling), test))] +pub use std::alloc::handle_alloc_error; + +#[cfg(all(not(no_global_oom_handling), not(test)))] +#[doc(hidden)] +#[allow(unused_attributes)] +#[unstable(feature = "alloc_internals" , issue = "none" )] +pub mod __alloc_error_handler { +use crate ::alloc::Layout ; + +// called via generated `__rust_alloc_error_handler` + +// if there is no `#[alloc_error_handler]` +#[rustc_std_internal_symbol] +pub unsafe extern "C-unwind" fn __rdl_oom (size:usize , _align:usize ) -> ! { +panic! ("memory allocation of {size} bytes failed" ) + } + +// if there is an `#[alloc_error_handler]` +#[rustc_std_internal_symbol] +pub unsafe extern "C-unwind" fn __rg_oom (size:usize , align:usize ) -> ! { +let layout =unsafe {Layout ::from_size_align_unchecked (size, align) }; +extern "Rust" { +#[lang = "oom" ] +fn oom_impl (layout:Layout ) -> !; + } +unsafe {oom_impl (layout) } + } +} + +/// Specialize clones into pre-allocated, uninitialized memory. +/// Used by `Box::clone` and `Rc`/`Arc::make_mut`. +pub (crate )trait WriteCloneIntoRaw :Sized { +unsafe fn write_clone_into_raw (&self, target: *mut Self ); +} + +impl <T :Clone >WriteCloneIntoRaw for T { +#[inline] +default unsafe fn write_clone_into_raw (&self, target: *mut Self ) { +// Having allocated *first* may allow the optimizer to create +// the cloned value in-place, skipping the local and move. +unsafe { target.write (self.clone ()) }; + } +} + +impl <T :Copy >WriteCloneIntoRaw for T { +#[inline] +unsafe fn write_clone_into_raw (&self, target: *mut Self ) { +// We can always copy in-place, without ever involving a local value. +unsafe { target.copy_from_nonoverlapping (self,1 ) }; + } +}
rust/alloc/borrow.rs new file +496 -0
496 lines not on this page · raw message
rust/alloc/boxed.rs new file +2024 -0
2,024 lines not on this page · raw message
rust/alloc/collections/mod.rs new file +154 -0
42 lines not on this page · raw message
rust/alloc/lib.rs new file +236 -0
236 lines not on this page · raw message
rust/alloc/raw_vec.rs new file +518 -0
518 lines not on this page · raw message
rust/alloc/slice.rs new file +1202 -0
1,202 lines not on this page · raw message
rust/alloc/vec/drain.rs new file +184 -0
184 lines not on this page · raw message
rust/alloc/vec/drain_filter.rs new file +143 -0
143 lines not on this page · raw message
rust/alloc/vec/into_iter.rs new file +362 -0
362 lines not on this page · raw message
rust/alloc/vec/is_zero.rs new file +118 -0
118 lines not on this page · raw message
rust/alloc/vec/mod.rs new file +3115 -0
3,115 lines not on this page · raw message
rust/alloc/vec/partial_eq.rs new file +47 -0
47 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.37.3
Part of the diff is not shown here. View the raw message.
Miguel Ojeda
maintainerPATCH v10 8/27 rust: adapt `alloc` crate to the kernel
In reply to Miguel OjedaThis customizes the subset of the Rust standard library alloc that was just imported as-is, mainly by:
- Adding SPDX license identifiers.
- Skipping modules (e.g. rc and sync) via new cfgs.
- Adding fallible (try_*) versions of existing infallible methods (i.e. returning a Result instead of panicking).
Since the standard library requires stable/unstable attributes, these additions are annotated with:
#[stable(feature = "kernel", since = "1.0.0")]
Using "kernel" as the feature allows to have the additions clearly marked. The "1.0.0" version is just a placeholder.
(At the moment, only one is needed, but in the future more fallible methods will be added).
--- rust/alloc/README.md | 33 +++++++++++++++++++++++++++++++++ rust/alloc/alloc.rs | 2 ++ rust/alloc/borrow.rs | 4 +++- rust/alloc/boxed.rs | 4 ++++ rust/alloc/collections/mod.rs | 2 ++ rust/alloc/lib.rs | 8 ++++++++ rust/alloc/raw_vec.rs | 9 +++++++++ rust/alloc/slice.rs | 2 ++ rust/alloc/vec/drain.rs | 2 ++ rust/alloc/vec/drain_filter.rs | 2 ++ rust/alloc/vec/into_iter.rs | 4 ++++ rust/alloc/vec/is_zero.rs | 2 ++ rust/alloc/vec/mod.rs | 25 +++++++++++++++++++++++++ rust/alloc/vec/partial_eq.rs | 2 ++ 14 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 rust/alloc/README.md
rust/alloc/README.md new file +33 -0
@@ -0,0 +1,33 @@ +# `alloc` + +These source files come from the Rust standard library, hosted in +the <https://github.com/rust-lang/rust> repository, licensed under +"Apache-2.0 OR MIT" and adapted for kernel use. For copyright details, +see <https://github.com/rust-lang/rust/blob/master/COPYRIGHT>. + +Please note that these files should be kept as close as possible to +upstream. In general, only additions should be performed (e.g. new +methods). Eventually, changes should make it into upstream so that, +at some point, this fork can be dropped from the kernel tree. + + +## Rationale + +On one hand, kernel folks wanted to keep `alloc` in-tree to have more +freedom in both workflow and actual features if actually needed +(e.g. receiver types if we ended up using them), which is reasonable. + +On the other hand, Rust folks wanted to keep `alloc` as close as +upstream as possible and avoid as much divergence as possible, which +is also reasonable. + +We agreed on a middle-ground: we would keep a subset of `alloc` +in-tree that would be as small and as close as possible to upstream. +Then, upstream can start adding the functions that we add to `alloc` +etc., until we reach a point where the kernel already knows exactly +what it needs in `alloc` and all the new methods are merged into +upstream, so that we can drop `alloc` from the kernel tree and go back +to using the upstream one. + +By doing this, the kernel can go a bit faster now, and Rust can +slowly incorporate and discuss the changes as needed.
rust/alloc/alloc.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! Memory allocation APIs #![stable(feature = "alloc_module" , since = "1.28.0" )]
rust/alloc/borrow.rs +3 -1
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! A module for working with borrowed data. #![stable(feature = "rust1" , since = "1.0.0" )]
@@ -11,7 +13,7 @@ use core::ops::{Add, AddAssign};#[stable(feature = "rust1" , since = "1.0.0" )] pub use core::borrow::{Borrow ,BorrowMut }; -use crate ::fmt; +use core::fmt;#[cfg(not(no_global_oom_handling))] use crate ::string::String ;
rust/alloc/boxed.rs +4 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! A pointer type for heap allocation. //! //! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
@@ -163,9 +165,11 @@ use crate::str::from_boxed_utf8_unchecked;#[cfg(not(no_global_oom_handling))] use crate ::vec::Vec ; +#[cfg(not(no_thin))] #[unstable(feature = "thin_box" , issue = "92791" )] pub use thin::ThinBox ; +#[cfg(not(no_thin))] mod thin;/// A pointer type for heap allocation.
rust/alloc/collections/mod.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! Collection types. #![stable(feature = "rust1" , since = "1.0.0" )]
rust/alloc/lib.rs +8 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! # The Rust core allocation and collections library //! //! This library provides smart pointers and collections for managing
@@ -192,6 +194,7 @@ extern crate std;extern crate test;// Module with internal macros used by other modules (needs to be included before other modules). +#[cfg(not(no_macros))] #[macro_use] mod macros;
@@ -216,11 +219,16 @@ pub mod borrow;pub mod collections;#[cfg(not(no_global_oom_handling))] pub mod ffi; +#[cfg(not(no_fmt))] pub mod fmt; +#[cfg(not(no_rc))] pub mod rc;pub mod slice; +#[cfg(not(no_str))] pub mod str; +#[cfg(not(no_string))] pub mod string; +#[cfg(not(no_sync))] #[cfg(target_has_atomic = "ptr" )] pub mod sync;#[cfg(all(not(no_global_oom_handling), target_has_atomic = "ptr" ))]
rust/alloc/raw_vec.rs +9 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +#![unstable(feature = "raw_vec_internals" , reason = "unstable const warnings" , issue = "none" )] use core::alloc::LayoutError ;
@@ -307,6 +309,12 @@ impl<T, A: Allocator> RawVec<T, A> { } } +/// The same as `reserve_for_push`, but returns on errors instead of panicking or aborting. +#[inline(never)] +pub fn try_reserve_for_push (&mut self, len:usize ) ->Result <(),TryReserveError > { + self.grow_amortized (len,1 ) + } +/// Ensures that the buffer contains at least enough space to hold `len + /// additional` elements. If it doesn't already, will reallocate the /// minimum possible amount of memory necessary. Generally this will be
@@ -421,6 +429,7 @@ impl<T, A: Allocator> RawVec<T, A> {Ok (()) } +#[allow(dead_code)] fn shrink (&mut self, cap:usize ) ->Result <(),TryReserveError > {assert! (cap <= self.capacity (),"Tried to shrink to a larger capacity" );
rust/alloc/slice.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! A dynamically-sized view into a contiguous sequence, `[T]`. //! //! *[See also the slice primitive type](slice).*
rust/alloc/vec/drain.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +use crate ::alloc::{Allocator ,Global };use core::fmt;use core::iter::{FusedIterator ,TrustedLen };
rust/alloc/vec/drain_filter.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +use crate ::alloc::{Allocator ,Global };use core::ptr::{self};use core::slice::{self};
rust/alloc/vec/into_iter.rs +4 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +#[cfg(not(no_global_oom_handling))] use super ::AsVecIntoIter ;use crate ::alloc::{Allocator ,Global };
@@ -9,6 +11,7 @@ use core::iter::{ };use core::marker::PhantomData ;use core::mem::{self,ManuallyDrop }; +#[cfg(not(no_global_oom_handling))] use core::ops::Deref ;use core::ptr::{self,NonNull };use core::slice::{self};
@@ -123,6 +126,7 @@ impl<T, A: Allocator> IntoIter<T, A> { }/// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed. +#[allow(dead_code)] pub (crate )fn forget_remaining_elements (&mut self) { self.ptr = self.end; }
rust/alloc/vec/is_zero.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +use crate ::boxed::Box ;#[rustc_specialization_trait]
rust/alloc/vec/mod.rs +25 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! A contiguous growable array type with heap-allocated contents, written //! `Vec<T>`. //!
@@ -1739,6 +1741,29 @@ impl<T, A: Allocator> Vec<T, A> { } } +/// Tries to append an element to the back of a collection. +/// +/// # Examples +/// +/// ``` +/// let mut vec = vec![1, 2]; +/// vec.try_push(3).unwrap(); +/// assert_eq!(vec, [1, 2, 3]); +/// ``` +#[inline] +#[stable(feature = "kernel" , since = "1.0.0" )] +pub fn try_push (&mut self, value:T ) ->Result <(),TryReserveError > { +if self.len == self.buf.capacity () { + self.buf.try_reserve_for_push (self.len)?; + } +unsafe { +let end = self.as_mut_ptr ().add (self.len); + ptr::write (end, value); + self.len +=1 ; + } +Ok (()) + } +/// Removes the last element from a vector and returns it, or [`None`] if it /// is empty. ///
rust/alloc/vec/partial_eq.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +use crate ::alloc::Allocator ;#[cfg(not(no_global_oom_handling))] use crate ::borrow::Cow ;
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 9/27 rust: add `compiler_builtins` crate
In reply to Miguel OjedaRust provides compiler_builtins as a port of LLVM's compiler-rt. Since we do not need the vast majority of them, we avoid the dependency by providing our own crate.
--- rust/compiler_builtins.rs | 63 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 rust/compiler_builtins.rs
rust/compiler_builtins.rs new file +63 -0
@@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Our own `compiler_builtins`. +//! +//! Rust provides [`compiler_builtins`] as a port of LLVM's [`compiler-rt`]. +//! Since we do not need the vast majority of them, we avoid the dependency +//! by providing this file. +//! +//! At the moment, some builtins are required that should not be. For instance, +//! [`core`] has 128-bit integers functionality which we should not be compiling +//! in. We will work with upstream [`core`] to provide feature flags to disable +//! the parts we do not need. For the moment, we define them to [`panic!`] at +//! runtime for simplicity to catch mistakes, instead of performing surgery +//! on `core.o`. +//! +//! In any case, all these symbols are weakened to ensure we do not override +//! those that may be provided by the rest of the kernel. +//! +//! [`compiler_builtins`]: https://github.com/rust-lang/compiler-builtins +//! [`compiler-rt`]: https://compiler-rt.llvm.org/ + +#![feature(compiler_builtins)] +#![compiler_builtins] +#![no_builtins] +#![no_std] + +macro_rules! define_panicking_intrinsics( + ($reason: tt, { $($ident: ident, )* }) => { + $( +#[doc(hidden)] +#[no_mangle] +pub extern"C" fn $ident() { +panic! ($reason); + } + )* + } +); + +define_panicking_intrinsics! ("`f32` should not be used" , { + __eqsf2, + __gesf2, + __lesf2, + __nesf2, + __unordsf2, +}); + +define_panicking_intrinsics! ("`f64` should not be used" , { + __unorddf2, +}); + +define_panicking_intrinsics! ("`i128` should not be used" , { + __ashrti3, + __muloti4, + __multi3, +}); + +define_panicking_intrinsics! ("`u128` should not be used" , { + __ashlti3, + __lshrti3, + __udivmodti4, + __udivti3, + __umodti3, +});
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 10/27 rust: add `macros` crate
In reply to Miguel OjedaThis crate contains all the procedural macros ("proc macros") shared by all the kernel.
Procedural macros allow to create syntax extensions. They run at compile-time and can consume as well as produce Rust syntax.
For instance, the module! macro that is used by Rust modules is implemented here. It allows to easily declare the equivalent information to the MODULE_* macros in C modules, e.g.:
module! {
type: RustMinimal,
name: b"rust_minimal",
author: b"Rust for Linux Contributors",
description: b"Rust minimal sample",
license: b"GPL",
}
--- rust/macros/helpers.rs | 51 ++++++++ rust/macros/lib.rs | 72 +++++++++++ rust/macros/module.rs | 282 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 405 insertions(+) create mode 100644 rust/macros/helpers.rs create mode 100644 rust/macros/lib.rs create mode 100644 rust/macros/module.rs
rust/macros/helpers.rs new file +51 -0
@@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro::{token_stream,TokenTree }; + +pub (crate )fn try_ident (it: &mut token_stream::IntoIter ) ->Option <String > { +if let Some (TokenTree ::Ident (ident)) = it.next () { +Some (ident.to_string ()) + }else { +None + } +} + +pub (crate )fn try_literal (it: &mut token_stream::IntoIter ) ->Option <String > { +if let Some (TokenTree ::Literal (literal)) = it.next () { +Some (literal.to_string ()) + }else { +None + } +} + +pub (crate )fn try_byte_string (it: &mut token_stream::IntoIter ) ->Option <String > { +try_literal (it).and_then (|byte_string| { +if byte_string.starts_with ("b\"" ) && byte_string.ends_with ('\"' ) { +Some (byte_string[2 ..byte_string.len () -1 ].to_string ()) + }else { +None + } + }) +} + +pub (crate )fn expect_ident (it: &mut token_stream::IntoIter ) ->String { +try_ident (it).expect ("Expected Ident" ) +} + +pub (crate )fn expect_punct (it: &mut token_stream::IntoIter ) ->char { +if let TokenTree ::Punct (punct) = it.next ().expect ("Reached end of token stream for Punct" ) { + punct.as_char () + }else { +panic! ("Expected Punct" ); + } +} + +pub (crate )fn expect_byte_string (it: &mut token_stream::IntoIter ) ->String { +try_byte_string (it).expect ("Expected byte string" ) +} + +pub (crate )fn expect_end (it: &mut token_stream::IntoIter ) { +if it.next ().is_some () { +panic! ("Expected end" ); + } +}
rust/macros/lib.rs new file +72 -0
72 lines not on this page · raw message
rust/macros/module.rs new file +282 -0
282 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 11/27 rust: add `bindings` crate
In reply to Miguel OjedaThis crate contains the bindings to the C side of the kernel.
Calling C (in general, FFI) is assumed to be unsafe in Rust and, in many cases, this is accurate. For instance, virtually all C functions that take a pointer are unsafe since, typically, it will be dereferenced at some point (and in most cases there is no way for the callee to check its validity beforehand).
Since one of the goals of using Rust in the kernel is precisely to avoid unsafe code in "leaf" kernel modules (e.g. drivers), these bindings should not be used directly by them.
Instead, these bindings need to be wrapped into safe abstractions. These abstractions provide a safe API that kernel modules can use. In this way, unsafe code in kernel modules is minimized.
--- rust/bindings/bindings_helper.h | 13 ++++++++ rust/bindings/lib.rs | 53 +++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 rust/bindings/bindings_helper.h create mode 100644 rust/bindings/lib.rs
rust/bindings/bindings_helper.h new file +13 -0
@@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Header that contains the code (mostly headers) for which Rust bindings +* will be automatically generated by `bindgen`. +* +* Sorted alphabetically. +*/ + +#include <linux/slab.h> + +/* `bindgen` gets confused at certain things. */ +const gfp_t BINDINGS_GFP_KERNEL =GFP_KERNEL ; +const gfp_t BINDINGS___GFP_ZERO = __GFP_ZERO;
rust/bindings/lib.rs new file +53 -0
53 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 12/27 rust: add `kernel` crate
In reply to Miguel OjedaFrom: Wedson Almeida Filho <[email protected]>
The kernel crate currently includes all the abstractions that wrap kernel features written in C.
These abstractions call the C side of the kernel via the generated bindings with the bindgen tool. Modules developed in Rust should never call the bindings themselves.
In the future, as the abstractions grow in number, we may need to split this crate into several, possibly following a similar subdivision in subsystems as the kernel itself and/or moving the code to the actual subsystems.
--- rust/kernel/allocator.rs | 64 +++++++++++++ rust/kernel/error.rs | 59 ++++++++++++ rust/kernel/lib.rs | 78 +++++++++++++++ rust/kernel/prelude.rs | 20 ++++ rust/kernel/print.rs | 198 +++++++++++++++++++++++++++++++++++++++ rust/kernel/str.rs | 72 ++++++++++++++ 6 files changed, 491 insertions(+) create mode 100644 rust/kernel/allocator.rs create mode 100644 rust/kernel/error.rs create mode 100644 rust/kernel/lib.rs create mode 100644 rust/kernel/prelude.rs create mode 100644 rust/kernel/print.rs create mode 100644 rust/kernel/str.rs
rust/kernel/allocator.rs new file +64 -0
@@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Allocator support. + +use core::alloc::{GlobalAlloc ,Layout }; +use core::ptr; + +use crate ::bindings; + +struct KernelAllocator ; + +unsafe impl GlobalAlloc for KernelAllocator { +unsafe fn alloc (&self, layout:Layout ) -> *mut u8 { +// `krealloc()` is used instead of `kmalloc()` because the latter is +// an inline function and cannot be bound to as a result. +unsafe { bindings::krealloc (ptr::null (), layout.size (), bindings::GFP_KERNEL )as *mut u8 } + } + +unsafe fn dealloc (&self, ptr: *mut u8 , _layout:Layout ) { +unsafe { + bindings::kfree (ptras *const core::ffi::c_void ); + } + } +} + +#[global_allocator] +static ALLOCATOR :KernelAllocator =KernelAllocator ; + +// `rustc` only generates these for some crate types. Even then, we would need +// to extract the object file that has them from the archive. For the moment, +// let's generate them ourselves instead. +// +// Note that `#[no_mangle]` implies exported too, nowadays. +#[no_mangle] +fn __rust_alloc (size:usize , _align:usize ) -> *mut u8 { +unsafe { bindings::krealloc (core::ptr::null (), size, bindings::GFP_KERNEL )as *mut u8 } +} + +#[no_mangle] +fn __rust_dealloc (ptr: *mut u8 , _size:usize , _align:usize ) { +unsafe { bindings::kfree (ptras *const core::ffi::c_void ) }; +} + +#[no_mangle] +fn __rust_realloc (ptr: *mut u8 , _old_size:usize , _align:usize , new_size:usize ) -> *mut u8 { +unsafe { + bindings::krealloc ( + ptras *const core::ffi::c_void , + new_size, + bindings::GFP_KERNEL , + )as *mut u8 + } +} + +#[no_mangle] +fn __rust_alloc_zeroed (size:usize , _align:usize ) -> *mut u8 { +unsafe { + bindings::krealloc ( + core::ptr::null (), + size, + bindings::GFP_KERNEL | bindings::__GFP_ZERO, + )as *mut u8 + } +}
rust/kernel/error.rs new file +59 -0
59 lines not on this page · raw message
rust/kernel/lib.rs new file +78 -0
78 lines not on this page · raw message
rust/kernel/prelude.rs new file +20 -0
@@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! The `kernel` prelude. +//! +//! These are the most common items used by Rust code in the kernel, +//! intended to be imported by all Rust code, for convenience. +//! +//! # Examples +//! +//! ``` +//! use kernel::prelude::*; +//! ``` + +pub use super ::{ + error::{Error ,Result }, + pr_emerg, pr_info,ThisModule , +}; +pub use alloc::{boxed::Box , vec::Vec }; +pub use core::pin::Pin ; +pub use macros::module;
rust/kernel/print.rs new file +198 -0
198 lines not on this page · raw message
rust/kernel/str.rs new file +72 -0
72 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 13/27 rust: export generated symbols
In reply to Miguel OjedaAll symbols are reexported reusing the EXPORT_SYMBOL_GPL macro from C. The lists of symbols are generated on the fly.
There are three main sets of symbols to distinguish:
- The ones from the core and alloc crates (from the Rust standard library). The code is licensed as Apache/MIT.
- The ones from our abstractions in the kernel crate.
- The helpers (already exported since they are not generated).
We export everything as GPL. This ensures we do not mistakenly expose GPL kernel symbols/features as non-GPL, even indirectly.
--- rust/exports.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 rust/exports.c
rust/exports.c new file +21 -0
@@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* A hack to export Rust symbols for loadable modules without having to redo +* the entire `include/linux/export.h` logic in Rust. +* +* This requires the Rust's new/future `v0` mangling scheme because the default +* one ("legacy") uses invalid characters for C identifiers (thus we cannot use +* the `EXPORT_SYMBOL_*` macros). +* +* All symbols are exported as GPL-only to guarantee no GPL-only feature is +* accidentally exposed. +*/ + +#include <linux/module.h> + +#define EXPORT_SYMBOL_RUST_GPL (sym) extern int sym; EXPORT_SYMBOL_GPL(sym) + +#include "exports_core_generated.h" +#include "exports_alloc_generated.h" +#include "exports_bindings_generated.h" +#include "exports_kernel_generated.h"
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 14/27 vsprintf: add new `%pA` format specifier
In reply to Miguel OjedaFrom: Gary Guo <[email protected]>
This patch adds a format specifier %pA to vsprintf which formats a pointer as core::fmt::Arguments. Doing so allows us to directly format to the internal buffer of printf, so we do not have to use a temporary buffer on the stack to pre-assemble the message on the Rust side.
This specifier is intended only to be used from Rust and not for C, so checkpatch.pl is intentionally unchanged to catch any misuse.
--- Documentation/core-api/printk-formats.rst | 10 ++++++++++ lib/vsprintf.c | 13 +++++++++++++ 2 files changed, 23 insertions(+)
Documentation/core-api/printk-formats.rst +10 -0
@@ -625,6 +625,16 @@ Examples:: %p4cc Y10 little-endian (0x20303159) %p4cc NV12 big-endian (0xb231564e) +Rust +---- + +:: + + %pA + +Only intended to be used from Rust code to format ``core::fmt::Arguments``. +Do *not* use it from C. + Thanks ======
lib/vsprintf.c +13 -0
@@ -2246,6 +2246,9 @@ int __init no_hash_pointers_enable(char *str) }early_param ("no_hash_pointers" , no_hash_pointers_enable); +/* Used for Rust formatting ('%pA'). */ +char *rust_fmt_argument (char *buf,char *end,void *ptr); +/* * Show a '%p' thing. A kernel extension is that the '%p' is followed * by an extra set of alphanumeric characters that are extended format
@@ -2372,6 +2375,10 @@ early_param("no_hash_pointers", no_hash_pointers_enable);* * Note: The default behaviour (unadorned %p) is to hash the address, * rendering it useful as a unique identifier. +* +* There is also a '%pA' format specifier, but it is only intended to be used +* from Rust code to format core::fmt::Arguments. Do *not* use it from C. +* See rust/kernel/print.rs for details. */ static noinline_for_stack char *pointer(const char *fmt, char *buf, char *end, void *ptr,
@@ -2444,6 +2451,12 @@ char *pointer(const char *fmt, char *buf, char *end, void *ptr,return device_node_string (buf, end, ptr, spec, fmt +1 );case 'f' :return fwnode_string (buf, end, ptr, spec, fmt +1 ); +case 'A' : +if (!IS_ENABLED (CONFIG_RUST )) { +WARN_ONCE (1 ,"Please remove %%pA from non-Rust code\n" ); +return error_string (buf, end,"(%pA?)" , spec); + } +return rust_fmt_argument (buf, end, ptr);case 'x' :return pointer_string (buf, end, ptr, spec);case 'e' :
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 15/27 scripts: checkpatch: diagnose uses of `%pA` in the C side as errors
In reply to Miguel OjedaThe %pA format specifier is only intended to be used from Rust.
checkpatch.pl already gives a warning for invalid specificers:
WARNING: Invalid vsprintf pointer extension '%pA'
This makes it an error and introduces an explanatory message:
ERROR: Invalid vsprintf pointer extension '%pA' - '%pA' is only intended to be used from Rust code
--- scripts/checkpatch.pl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
scripts/checkpatch.pl +6 -2
@@ -6783,15 +6783,19 @@ sub process { } if ($bad_specifier ne "") { my $stat_real = get_stat_real($linenr, $lc); + my $msg_level = \&WARN; my $ext_type = "Invalid"; my $use = ""; if ($bad_specifier =~ /p[Ff]/) { $use = " - use %pS instead"; $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/); + } elsif ($bad_specifier =~ /pA/) { + $use = " - '%pA' is only intended to be used from Rust code"; + $msg_level = \&ERROR; } - WARN("VSPRINTF_POINTER_EXTENSION", - "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n"); + &{$msg_level}("VSPRINTF_POINTER_EXTENSION", + "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n"); } } }
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 16/27 scripts: checkpatch: enable language-independent checks for Rust
In reply to Miguel OjedaInclude Rust in the "source code files" category, so that the language-independent tests are checked for Rust too, and teach checkpatch about the comment style for Rust files.
This enables the malformed SPDX check, the misplaced SPDX license tag check, the long line checks, the lines without a newline check and the embedded filename check.
--- scripts/checkpatch.pl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
scripts/checkpatch.pl +2 -2
@@ -3616,7 +3616,7 @@ sub process { my $comment = ""; if ($realfile =~ /\.(h|s|S)$/) { $comment = '/*'; - } elsif ($realfile =~ /\.(c|dts|dtsi)$/) { + } elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) { $comment = '//'; } elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) { $comment = '#';
@@ -3664,7 +3664,7 @@ sub process { } # check we are in a valid source file if not then ignore this hunk - next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/); + next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/); # check for using SPDX-License-Identifier on the wrong line number if ($realline != $checklicenseline &&
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 17/27 scripts: decode_stacktrace: demangle Rust symbols
In reply to Miguel OjedaRecent versions of both Binutils (c++filt) and LLVM (llvm-cxxfilt) provide Rust v0 mangling support.
--- scripts/decode_stacktrace.sh | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
scripts/decode_stacktrace.sh +14 -0
@@ -8,6 +8,14 @@ usage() { echo " $0 -r <release> | <vmlinux> [<base path>|auto] [<modules path>]" } +# Try to find a Rust demangler +if type llvm-cxxfilt >/dev/null 2>&1 ; then + cppfilt=llvm-cxxfilt +elif type c++filt >/dev/null 2>&1 ; then + cppfilt=c++filt + cppfilt_opts=-i +fi + if [[ $1 == "-r" ]] ; then vmlinux="" basepath="auto"
@@ -180,6 +188,12 @@ parse_symbol() { # In the case of inlines, move everything to same line code=${code//$'\n'/' '} + # Demangle if the name looks like a Rust symbol and if + # we got a Rust demangler + if [[ $name =~ ^_R && $cppfilt != "" ]] ; then + name=$("$cppfilt" "$cppfilt_opts" "$name") + fi + # Replace old address with pretty line numbers symbol="$segment$name ($code)" }
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 18/27 scripts: add `generate_rust_analyzer.py`
In reply to Miguel OjedaThe generate_rust_analyzer.py script generates the configuration file (rust-project.json) for rust-analyzer.
rust-analyzer is a modular compiler frontend for the Rust language. It provides an LSP server which can be used in editors such as VS Code, Emacs or Vim.
--- .gitignore | 3 + scripts/generate_rust_analyzer.py | 135 ++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100755 scripts/generate_rust_analyzer.py
.gitignore +3 -0
@@ -162,3 +162,6 @@ x509.genkey # Documentation toolchain sphinx_*/ + +# Rust analyzer configuration +/rust-project.json
scripts/generate_rust_analyzer.py new file +135 -0
135 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 19/27 scripts: add `generate_rust_target.rs`
In reply to Miguel OjedaThis script takes care of generating the custom target specification file for rustc, based on the kernel configuration.
It also serves as an example of a Rust host program.
A dummy architecture is kept in this patch so that a later patch adds x86 support on top with as few changes as possible.
--- scripts/.gitignore | 1 + scripts/generate_rust_target.rs | 171 ++++++++++++++++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 scripts/generate_rust_target.rs
scripts/.gitignore +1 -0
@@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only /asn1_compiler /bin2c +/generate_rust_target /insert-sys-cert /kallsyms /module.lds
scripts/generate_rust_target.rs new file +171 -0
171 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 20/27 scripts: add `rust_is_available.sh`
In reply to Miguel OjedaThis script tests whether the Rust toolchain requirements are in place to enable Rust support. It uses min-tool-version.sh to fetch the version numbers.
The build system will call it to set CONFIG_RUST_IS_AVAILABLE in a later patch.
It also has an option (-v) to explain what is missing, which is useful to set up the development environment. This is used via the make rustavailable target added in a later patch.
--- scripts/min-tool-version.sh | 6 + scripts/rust_is_available.sh | 160 +++++++++++++++++++ scripts/rust_is_available_bindgen_libclang.h | 2 + 3 files changed, 168 insertions(+) create mode 100755 scripts/rust_is_available.sh create mode 100644 scripts/rust_is_available_bindgen_libclang.h
scripts/min-tool-version.sh +6 -0
@@ -30,6 +30,12 @@ llvm) echo 11.0.0 fi ;; +rustc) + echo 1.62.0 + ;; +bindgen) + echo 0.56.0 + ;; *) echo "$1: unknown tool" >&2 exit 1
scripts/rust_is_available.sh new file +160 -0
160 lines not on this page · raw message
scripts/rust_is_available_bindgen_libclang.h new file +2 -0
@@ -0,0 +1,2 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#pragma message("clang version " __clang_version__)
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 21/27 scripts: add `is_rust_module.sh`
In reply to Miguel OjedaFrom: Daniel Xu <[email protected]>
This script is used to detect whether a kernel module is written in Rust.
It will later be used to disable BTF generation on Rust modules as BTF does not yet support Rust.
--- scripts/is_rust_module.sh | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100755 scripts/is_rust_module.sh
scripts/is_rust_module.sh new file +16 -0
@@ -0,0 +1,16 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# +# is_rust_module.sh module.ko +# +# Returns `0` if `module.ko` is a Rust module, `1` otherwise. + +set -e + +# Using the `16_` prefix ensures other symbols with the same substring +# are not picked up (even if it would be unlikely). The last part is +# used just in case LLVM decides to use the `.` suffix. +# +# In the future, checking for the `.comment` section may be another +# option, see https://github.com/rust-lang/rust/pull/97550. +${NM} "$*" | grep -qE '^[0-9a-fA-F]+ r _R[^[:space:]]+16___IS_RUST_MODULE[^[:space:]]*$'
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 22/27 rust: add `.rustfmt.toml`
In reply to Miguel OjedaThis is the configuration file for the rustfmt tool.
rustfmt is a tool for formatting Rust code according to style guidelines. It is very commonly used across Rust projects.
The default configuration options are used.
--- .gitignore | 1 + .rustfmt.toml | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 .rustfmt.toml
.gitignore +1 -0
@@ -97,6 +97,7 @@ modules.order !.gitattributes !.gitignore !.mailmap +!.rustfmt.toml # # Generated include files
.rustfmt.toml new file +12 -0
@@ -0,0 +1,12 @@ +edition = "2021" +newline_style = "Unix" + +# Unstable options that help catching some mistakes in formatting and that we may want to enable +# when they become stable. +# +# They are kept here since they are useful to run from time to time. +#format_code_in_doc_comments = true +#reorder_impl_items = true +#comment_width = 100 +#wrap_comments = true +#normalize_comments = true
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 23/27 Kbuild: add Rust support
In reply to Miguel OjedaHaving most of the new files in place, we now enable Rust support in the build system, including Kconfig entries related to Rust, the Rust configuration printer and a few other bits.
--- .gitignore | 2 + Makefile | 172 ++++++++++++++- arch/Kconfig | 6 + include/linux/compiler_types.h | 6 +- init/Kconfig | 46 +++- kernel/configs/rust.config | 1 + lib/Kconfig.debug | 34 +++ rust/.gitignore | 8 + rust/Makefile | 381 +++++++++++++++++++++++++++++++++ rust/bindgen_parameters | 21 ++ scripts/Kconfig.include | 6 +- scripts/Makefile | 3 + scripts/Makefile.build | 60 ++++++ scripts/Makefile.debug | 8 + scripts/Makefile.host | 34 ++- scripts/Makefile.lib | 12 ++ scripts/Makefile.modfinal | 8 +- scripts/cc-version.sh | 12 +- scripts/kconfig/confdata.c | 75 +++++++ 19 files changed, 869 insertions(+), 26 deletions(-) create mode 100644 kernel/configs/rust.config create mode 100644 rust/.gitignore create mode 100644 rust/Makefile create mode 100644 rust/bindgen_parameters
.gitignore +2 -0
@@ -37,6 +37,8 @@ *.o *.o.* *.patch +*.rmeta +*.rsi *.s *.so *.so.dbg
Makefile +163 -9
340 lines not on this page · raw message
arch/Kconfig +6 -0
@@ -355,6 +355,12 @@ config HAVE_RSEQ This symbol should be selected by an architecture if it supports an implementation of restartable sequences. +config HAVE_RUST + bool + help + This symbol should be selected by an architecture if it + supports Rust. + config HAVE_FUNCTION_ARG_ACCESS_API bool help
include/linux/compiler_types.h +5 -1
@@ -4,8 +4,12 @@#ifndef __ASSEMBLY__ +/* +* Skipped when running bindgen due to a libclang issue; +* see https://github.com/rust-lang/rust-bindgen/issues/2244. +*/ #if defined(CONFIG_DEBUG_INFO_BTF ) && defined(CONFIG_PAHOLE_HAS_BTF_TAG ) && \ -__has_attribute (btf_type_tag) +__has_attribute (btf_type_tag) && !defined(__BINDGEN__)# define BTF_TYPE_TAG (value) __attribute__((btf_type_tag(#value)))#else # define BTF_TYPE_TAG (value)/* nothing */
init/Kconfig +45 -1
64 lines not on this page · raw message
kernel/configs/rust.config new file +1 -0
@@ -0,0 +1 @@ +CONFIG_RUST=y
lib/Kconfig.debug +34 -0
@@ -2710,6 +2710,40 @@ config HYPERV_TESTING endmenu # "Kernel Testing and Coverage" +menu "Rust hacking" + +config RUST_DEBUG_ASSERTIONS + bool "Debug assertions" + depends on RUST + help + Enables rustc's `-Cdebug-assertions` codegen option. + + This flag lets you turn `cfg(debug_assertions)` conditional + compilation on or off. This can be used to enable extra debugging + code in development but not in production. For example, it controls + the behavior of the standard library's `debug_assert!` macro. + + Note that this will apply to all Rust code, including `core`. + + If unsure, say N. + +config RUST_OVERFLOW_CHECKS + bool "Overflow checks" + default y + depends on RUST + help + Enables rustc's `-Coverflow-checks` codegen option. + + This flag allows you to control the behavior of runtime integer + overflow. When overflow-checks are enabled, a Rust panic will occur + on overflow. + + Note that this will apply to all Rust code, including `core`. + + If unsure, say Y. + +endmenu # "Rust" + source "Documentation/Kconfig" endmenu # Kernel hacking
rust/.gitignore new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0 + +target.json +bindings_generated.rs +bindings_helpers_generated.rs +exports_*_generated.h +doc/ +test/
rust/Makefile new file +381 -0
381 lines not on this page · raw message
rust/bindgen_parameters new file +21 -0
@@ -0,0 +1,21 @@ +# SPDX-License-Identifier: GPL-2.0 + +--opaque-type xregs_state +--opaque-type desc_struct +--opaque-type arch_lbr_state +--opaque-type local_apic + +# Packed type cannot transitively contain a `#[repr(align)]` type. +--opaque-type x86_msi_data +--opaque-type x86_msi_addr_lo + +# `try` is a reserved keyword since Rust 2018; solved in `bindgen` v0.59.2, +# commit 2aed6b021680 ("context: Escape the try keyword properly"). +--opaque-type kunit_try_catch + +# If SMP is disabled, `arch_spinlock_t` is defined as a ZST which triggers a Rust +# warning. We don't need to peek into it anyway. +--opaque-type spinlock + +# `seccomp`'s comment gets understood as a doctest +--no-doc-comments
scripts/Kconfig.include +3 -3
@@ -36,12 +36,12 @@ ld-option = $(success,$(LD) -v $(1)) as-instr = $(success,printf "%b\n" "$(1)" | $(CC) $(CLANG_FLAGS) -c -x assembler -o /dev/null -) # check if $(CC) and $(LD) exist -$(error-if,$(failure,command -v $(CC)),compiler '$(CC)' not found) +$(error-if,$(failure,command -v $(CC)),C compiler '$(CC)' not found) $(error-if,$(failure,command -v $(LD)),linker '$(LD)' not found) -# Get the compiler name, version, and error out if it is not supported. +# Get the C compiler name, version, and error out if it is not supported. cc-info := $(shell,$(srctree)/scripts/cc-version.sh $(CC)) -$(error-if,$(success,test -z "$(cc-info)"),Sorry$(comma) this compiler is not supported.) +$(error-if,$(success,test -z "$(cc-info)"),Sorry$(comma) this C compiler is not supported.) cc-name := $(shell,set -- $(cc-info) && echo $1) cc-version := $(shell,set -- $(cc-info) && echo $2)
scripts/Makefile +3 -0
@@ -10,6 +10,9 @@ hostprogs-always-$(CONFIG_BUILDTIME_TABLE_SORT) += sorttable hostprogs-always-$(CONFIG_ASN1) += asn1_compiler hostprogs-always-$(CONFIG_MODULE_SIG_FORMAT) += sign-file hostprogs-always-$(CONFIG_SYSTEM_EXTRA_CERTIFICATE) += insert-sys-cert +hostprogs-always-$(CONFIG_RUST) += generate_rust_target + +generate_rust_target-rust := y HOSTCFLAGS_sorttable.o = -I$(srctree)/tools/include HOSTLDLIBS_sorttable = -lpthread
scripts/Makefile.build +60 -0
72 lines not on this page · raw message
scripts/Makefile.debug +8 -0
@@ -1,4 +1,6 @@ DEBUG_CFLAGS := +DEBUG_RUSTFLAGS := + debug-flags-y := -g ifdef CONFIG_DEBUG_INFO_SPLIT
@@ -17,9 +19,12 @@ KBUILD_AFLAGS += $(debug-flags-y) ifdef CONFIG_DEBUG_INFO_REDUCED DEBUG_CFLAGS += -fno-var-tracking +DEBUG_RUSTFLAGS += -Cdebuginfo=1 ifdef CONFIG_CC_IS_GCC DEBUG_CFLAGS += -femit-struct-debug-baseonly endif +else +DEBUG_RUSTFLAGS += -Cdebuginfo=2 endif ifdef CONFIG_DEBUG_INFO_COMPRESSED
@@ -30,3 +35,6 @@ endif KBUILD_CFLAGS += $(DEBUG_CFLAGS) export DEBUG_CFLAGS + +KBUILD_RUSTFLAGS += $(DEBUG_RUSTFLAGS) +export DEBUG_RUSTFLAGS
scripts/Makefile.host +31 -3
@@ -22,6 +22,8 @@ $(obj)/%.tab.c $(obj)/%.tab.h: $(src)/%.y FORCE # to preprocess a data file. # # Both C and C++ are supported, but preferred language is C for such utilities. +# Rust is also supported, but it may only be used in scenarios where a Rust +# toolchain is required to be available (e.g. when `CONFIG_RUST` is enabled). # # Sample syntax (see Documentation/kbuild/makefiles.rst for reference) # hostprogs := bin2hex
@@ -37,15 +39,20 @@ $(obj)/%.tab.c $(obj)/%.tab.h: $(src)/%.y FORCE # qconf-objs := menu.o # Will compile qconf as a C++ program, and menu as a C program. # They are linked as C++ code to the executable qconf +# +# hostprogs := target +# target-rust := y +# Will compile `target` as a Rust program, using `target.rs` as the crate root. +# The crate may consist of several source files. # C code # Executables compiled from a single .c file host-csingle := $(foreach m,$(hostprogs), \ - $(if $($(m)-objs)$($(m)-cxxobjs),,$(m))) + $(if $($(m)-objs)$($(m)-cxxobjs)$($(m)-rust),,$(m))) # C executables linked based on several .o files host-cmulti := $(foreach m,$(hostprogs),\ - $(if $($(m)-cxxobjs),,$(if $($(m)-objs),$(m)))) + $(if $($(m)-cxxobjs)$($(m)-rust),,$(if $($(m)-objs),$(m)))) # Object (.o) files compiled from .c files host-cobjs := $(sort $(foreach m,$(hostprogs),$($(m)-objs)))
@@ -58,11 +65,17 @@ host-cxxmulti := $(foreach m,$(hostprogs),$(if $($(m)-cxxobjs),$(m))) # C++ Object (.o) files compiled from .cc files host-cxxobjs := $(sort $(foreach m,$(host-cxxmulti),$($(m)-cxxobjs))) +# Rust code +# Executables compiled from a single Rust crate (which may consist of +# one or more .rs files) +host-rust := $(foreach m,$(hostprogs),$(if $($(m)-rust),$(m))) + host-csingle := $(addprefix $(obj)/,$(host-csingle)) host-cmulti := $(addprefix $(obj)/,$(host-cmulti)) host-cobjs := $(addprefix $(obj)/,$(host-cobjs)) host-cxxmulti := $(addprefix $(obj)/,$(host-cxxmulti)) host-cxxobjs := $(addprefix $(obj)/,$(host-cxxobjs)) +host-rust := $(addprefix $(obj)/,$(host-rust)) ##### # Handle options to gcc. Support building with separate output directory
@@ -71,6 +84,8 @@ _hostc_flags = $(KBUILD_HOSTCFLAGS) $(HOST_EXTRACFLAGS) \ $(HOSTCFLAGS_$(target-stem).o) _hostcxx_flags = $(KBUILD_HOSTCXXFLAGS) $(HOST_EXTRACXXFLAGS) \ $(HOSTCXXFLAGS_$(target-stem).o) +_hostrust_flags = $(KBUILD_HOSTRUSTFLAGS) $(HOST_EXTRARUSTFLAGS) \ + $(HOSTRUSTFLAGS_$(target-stem)) # $(objtree)/$(obj) for including generated headers from checkin source files ifeq ($(KBUILD_EXTMOD),)
@@ -82,6 +97,7 @@ endif hostc_flags = -Wp,-MMD,$(depfile) $(_hostc_flags) hostcxx_flags = -Wp,-MMD,$(depfile) $(_hostcxx_flags) +hostrust_flags = $(_hostrust_flags) ##### # Compile programs on the host
@@ -128,5 +144,17 @@ quiet_cmd_host-cxxobjs = HOSTCXX $@ $(host-cxxobjs): $(obj)/%.o: $(src)/%.cc FORCE $(call if_changed_dep,host-cxxobjs) +# Create executable from a single Rust crate (which may consist of +# one or more `.rs` files) +# host-rust -> Executable +quiet_cmd_host-rust = HOSTRUSTC $@ + cmd_host-rust = \ + $(HOSTRUSTC) $(hostrust_flags) --emit=dep-info,link \ + --out-dir=$(obj)/ $<; \ + mv $(obj)/$(target-stem).d $(depfile); \ + sed -i '/^\#/d' $(depfile) +$(host-rust): $(obj)/%: $(src)/%.rs FORCE + $(call if_changed_dep,host-rust) + targets += $(host-csingle) $(host-cmulti) $(host-cobjs) \ - $(host-cxxmulti) $(host-cxxobjs) + $(host-cxxmulti) $(host-cxxobjs) $(host-rust)
scripts/Makefile.lib +12 -0
@@ -8,6 +8,7 @@ ldflags-y += $(EXTRA_LDFLAGS) # flags that take effect in current and sub directories KBUILD_AFLAGS += $(subdir-asflags-y) KBUILD_CFLAGS += $(subdir-ccflags-y) +KBUILD_RUSTFLAGS += $(subdir-rustflags-y) # Figure out what we need to build from the various variables # ===========================================================================
@@ -128,6 +129,10 @@ _c_flags = $(filter-out $(CFLAGS_REMOVE_$(target-stem).o), \ $(filter-out $(ccflags-remove-y), \ $(KBUILD_CPPFLAGS) $(KBUILD_CFLAGS) $(ccflags-y)) \ $(CFLAGS_$(target-stem).o)) +_rust_flags = $(filter-out $(RUSTFLAGS_REMOVE_$(target-stem).o), \ + $(filter-out $(rustflags-remove-y), \ + $(KBUILD_RUSTFLAGS) $(rustflags-y)) \ + $(RUSTFLAGS_$(target-stem).o)) _a_flags = $(filter-out $(AFLAGS_REMOVE_$(target-stem).o), \ $(filter-out $(asflags-remove-y), \ $(KBUILD_CPPFLAGS) $(KBUILD_AFLAGS) $(asflags-y)) \
@@ -202,6 +207,11 @@ modkern_cflags = \ $(KBUILD_CFLAGS_MODULE) $(CFLAGS_MODULE), \ $(KBUILD_CFLAGS_KERNEL) $(CFLAGS_KERNEL) $(modfile_flags)) +modkern_rustflags = \ + $(if $(part-of-module), \ + $(KBUILD_RUSTFLAGS_MODULE) $(RUSTFLAGS_MODULE), \ + $(KBUILD_RUSTFLAGS_KERNEL) $(RUSTFLAGS_KERNEL)) + modkern_aflags = $(if $(part-of-module), \ $(KBUILD_AFLAGS_MODULE) $(AFLAGS_MODULE), \ $(KBUILD_AFLAGS_KERNEL) $(AFLAGS_KERNEL))
@@ -211,6 +221,8 @@ c_flags = -Wp,-MMD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE) \ $(_c_flags) $(modkern_cflags) \ $(basename_flags) $(modname_flags) +rust_flags = $(_rust_flags) $(modkern_rustflags) @$(objtree)/include/generated/rustc_cfg + a_flags = -Wp,-MMD,$(depfile) $(NOSTDINC_FLAGS) $(LINUXINCLUDE) \ $(_a_flags) $(modkern_aflags)
scripts/Makefile.modfinal +5 -3
@@ -39,11 +39,13 @@ quiet_cmd_ld_ko_o = LD [M] $@ quiet_cmd_btf_ko = BTF [M] $@ cmd_btf_ko = \ - if [ -f vmlinux ]; then \ + if [ ! -f vmlinux ]; then \ + printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \ + elif [ -n "$(CONFIG_RUST)" ] && $(srctree)/scripts/is_rust_module.sh $@; then \ + printf "Skipping BTF generation for %s because it's a Rust module\n" $@ 1>&2; \ + else \ LLVM_OBJCOPY="$(OBJCOPY)" $(PAHOLE) -J $(PAHOLE_FLAGS) --btf_base vmlinux $@; \ $(RESOLVE_BTFIDS) -b vmlinux $@; \ - else \ - printf "Skipping BTF generation for %s due to unavailability of vmlinux\n" $@ 1>&2; \ fi; # Same as newer-prereqs, but allows to exclude specified extra dependencies
scripts/cc-version.sh +6 -6
@@ -1,13 +1,13 @@ #!/bin/sh # SPDX-License-Identifier: GPL-2.0 # -# Print the compiler name and its version in a 5 or 6-digit form. +# Print the C compiler name and its version in a 5 or 6-digit form. # Also, perform the minimum version check. set -e -# Print the compiler name and some version components. -get_compiler_info() +# Print the C compiler name and some version components. +get_c_compiler_info() { cat <<- EOF | "$@" -E -P -x c - 2>/dev/null #if defined(__clang__)
@@ -32,7 +32,7 @@ get_canonical_version() # $@ instead of $1 because multiple words might be given, e.g. CC="ccache gcc". orig_args="$@" -set -- $(get_compiler_info "$@") +set -- $(get_c_compiler_info "$@") name=$1
@@ -52,7 +52,7 @@ ICC) min_version=$($min_tool_version icc) ;; *) - echo "$orig_args: unknown compiler" >&2 + echo "$orig_args: unknown C compiler" >&2 exit 1 ;; esac
@@ -62,7 +62,7 @@ min_cversion=$(get_canonical_version $min_version) if [ "$cversion" -lt "$min_cversion" ]; then echo >&2 "***" - echo >&2 "*** Compiler is too old." + echo >&2 "*** C compiler is too old." echo >&2 "*** Your $name version: $version" echo >&2 "*** Minimum $name version: $min_version" echo >&2 "***"
scripts/kconfig/confdata.c +75 -0
99 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 24/27 docs: add Rust documentation
In reply to Miguel OjedaMost of the documentation for Rust is written within the source code itself, as it is idiomatic for Rust projects. This applies to both the shared infrastructure at rust/ as well as any other Rust module (e.g. drivers) written across the kernel.
However, these documents contain general information that does not fit particularly well in the source code, like the Quick Start guide.
It also contains a few other small changes elsewhere in the documentation folder.
--- Documentation/doc-guide/kernel-doc.rst | 3 + Documentation/index.rst | 1 + Documentation/kbuild/kbuild.rst | 17 ++ Documentation/kbuild/makefiles.rst | 50 ++++- Documentation/process/changes.rst | 41 ++++ Documentation/rust/arch-support.rst | 18 ++ Documentation/rust/coding-guidelines.rst | 216 +++++++++++++++++++ Documentation/rust/general-information.rst | 79 +++++++ Documentation/rust/index.rst | 22 ++ Documentation/rust/quick-start.rst | 232 +++++++++++++++++++++ 10 files changed, 675 insertions(+), 4 deletions(-) create mode 100644 Documentation/rust/arch-support.rst create mode 100644 Documentation/rust/coding-guidelines.rst create mode 100644 Documentation/rust/general-information.rst create mode 100644 Documentation/rust/index.rst create mode 100644 Documentation/rust/quick-start.rst
Documentation/doc-guide/kernel-doc.rst +3 -0
@@ -14,6 +14,9 @@ when it is embedded in source files. reasons. The kernel source contains tens of thousands of kernel-doc comments. Please stick to the style described here. +.. note:: kernel-doc does not cover Rust code: please see + Documentation/rust/general-information.rst instead. + The kernel-doc structure is extracted from the comments, and proper `Sphinx C Domain`_ function and type descriptions with anchors are generated from them. The descriptions are filtered for special kernel-doc
Documentation/index.rst +1 -0
@@ -82,6 +82,7 @@ merged much easier. maintainer/index fault-injection/index livepatch/index + rust/index Kernel API documentation
Documentation/kbuild/kbuild.rst +17 -0
@@ -48,6 +48,10 @@ KCFLAGS ------- Additional options to the C compiler (for built-in and modules). +KRUSTFLAGS +---------- +Additional options to the Rust compiler (for built-in and modules). + CFLAGS_KERNEL ------------- Additional options for $(CC) when used to compile
@@ -57,6 +61,15 @@ CFLAGS_MODULE ------------- Additional module specific options to use for $(CC). +RUSTFLAGS_KERNEL +---------------- +Additional options for $(RUSTC) when used to compile +code that is compiled as built-in. + +RUSTFLAGS_MODULE +---------------- +Additional module specific options to use for $(RUSTC). + LDFLAGS_MODULE -------------- Additional options used for $(LD) when linking modules.
@@ -69,6 +82,10 @@ HOSTCXXFLAGS ------------ Additional flags to be passed to $(HOSTCXX) when building host programs. +HOSTRUSTFLAGS +------------- +Additional flags to be passed to $(HOSTRUSTC) when building host programs. + HOSTLDFLAGS ----------- Additional flags to be passed when linking host programs.
Documentation/kbuild/makefiles.rst +46 -4
80 lines not on this page · raw message
Documentation/process/changes.rst +41 -0
65 lines not on this page · raw message
Documentation/rust/arch-support.rst new file +18 -0
@@ -0,0 +1,18 @@ +.. SPDX-License-Identifier: GPL-2.0 + +Arch Support +============ + +Currently, the Rust compiler (``rustc``) uses LLVM for code generation, +which limits the supported architectures that can be targeted. In addition, +support for building the kernel with LLVM/Clang varies (please see +Documentation/kbuild/llvm.rst). This support is needed for ``bindgen`` +which uses ``libclang``. + +Below is a general summary of architectures that currently work. Level of +support corresponds to ``S`` values in the ``MAINTAINERS`` file. + +============ ================ ============================================== +Architecture Level of support Constraints +============ ================ ============================================== +============ ================ ==============================================
Documentation/rust/coding-guidelines.rst new file +216 -0
216 lines not on this page · raw message
Documentation/rust/general-information.rst new file +79 -0
79 lines not on this page · raw message
Documentation/rust/index.rst new file +22 -0
@@ -0,0 +1,22 @@ +.. SPDX-License-Identifier: GPL-2.0 + +Rust +==== + +Documentation related to Rust within the kernel. To start using Rust +in the kernel, please read the quick-start.rst guide. + +.. toctree:: + :maxdepth: 1 + + quick-start + general-information + coding-guidelines + arch-support + +.. only:: subproject and html + + Indices + ======= + + * :ref:`genindex`
Documentation/rust/quick-start.rst new file +232 -0
232 lines not on this page · raw message
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 25/27 x86: enable initial Rust support
In reply to Miguel OjedaNote that only x86_64 is covered and not all features nor mitigations are handled, but it is enough as a starting point and showcases the basics needed to add Rust support for a new architecture.
--- Documentation/rust/arch-support.rst | 1 + arch/x86/Kconfig | 1 + arch/x86/Makefile | 10 ++++++++++ scripts/generate_rust_target.rs | 15 +++++++++++++-- 4 files changed, 25 insertions(+), 2 deletions(-)
Documentation/rust/arch-support.rst +1 -0
@@ -15,4 +15,5 @@ support corresponds to ``S`` values in the ``MAINTAINERS`` file. ============ ================ ============================================== Architecture Level of support Constraints ============ ================ ============================================== +``x86`` Maintained ``x86_64`` only. ============ ================ ==============================================
arch/x86/Kconfig +1 -0
@@ -257,6 +257,7 @@ config X86 select HAVE_STATIC_CALL_INLINE if HAVE_OBJTOOL select HAVE_PREEMPT_DYNAMIC_CALL select HAVE_RSEQ + select HAVE_RUST if X86_64 select HAVE_SYSCALL_TRACEPOINTS select HAVE_UACCESS_VALIDATION if HAVE_OBJTOOL select HAVE_UNSTABLE_SCHED_CLOCK
arch/x86/Makefile +10 -0
@@ -68,6 +68,7 @@ export BITS # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53383 # KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx +KBUILD_RUSTFLAGS += -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2 ifeq ($(CONFIG_X86_KERNEL_IBT),y) #
@@ -155,8 +156,17 @@ else cflags-$(CONFIG_GENERIC_CPU) += -mtune=generic KBUILD_CFLAGS += $(cflags-y) + rustflags-$(CONFIG_MK8) += -Ctarget-cpu=k8 + rustflags-$(CONFIG_MPSC) += -Ctarget-cpu=nocona + rustflags-$(CONFIG_MCORE2) += -Ctarget-cpu=core2 + rustflags-$(CONFIG_MATOM) += -Ctarget-cpu=atom + rustflags-$(CONFIG_GENERIC_CPU) += -Ztune-cpu=generic + KBUILD_RUSTFLAGS += $(rustflags-y) + KBUILD_CFLAGS += -mno-red-zone KBUILD_CFLAGS += -mcmodel=kernel + KBUILD_RUSTFLAGS += -Cno-redzone=y + KBUILD_RUSTFLAGS += -Ccode-model=kernel endif #
scripts/generate_rust_target.rs +13 -2
@@ -148,8 +148,19 @@ fn main() {let mut ts =TargetSpec ::new ();// `llvm-target`s are taken from `scripts/Makefile.clang`. -if cfg.has ("DUMMY_ARCH" ) { - ts.push ("arch" ,"dummy_arch" ); +if cfg.has ("X86_64" ) { + ts.push ("arch" ,"x86_64" ); + ts.push ( +"data-layout" , +"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" , + ); +let mut features ="-3dnow,-3dnowa,-mmx,+soft-float" .to_string (); +if cfg.has ("RETPOLINE" ) { + features +=",+retpoline-external-thunk" ; + } + ts.push ("features" , features); + ts.push ("llvm-target" ,"x86_64-linux-gnu" ); + ts.push ("target-pointer-width" ,"64" ); }else {panic! ("Unsupported architecture" ); }
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 26/27 samples: add first Rust examples
In reply to Miguel OjedaThe beginning of a set of Rust modules that showcase how Rust modules look like and how to use the abstracted kernel features.
It also includes an example of a Rust host program with several modules.
These samples also double as tests in the CI.
--- samples/Kconfig | 2 ++ samples/Makefile | 1 + samples/rust/Kconfig | 30 ++++++++++++++++++++++++ samples/rust/Makefile | 5 ++++ samples/rust/hostprogs/.gitignore | 3 +++ samples/rust/hostprogs/Makefile | 5 ++++ samples/rust/hostprogs/a.rs | 7 ++++++ samples/rust/hostprogs/b.rs | 5 ++++ samples/rust/hostprogs/single.rs | 12 ++++++++++ samples/rust/rust_minimal.rs | 38 +++++++++++++++++++++++++++++++ 10 files changed, 108 insertions(+) create mode 100644 samples/rust/Kconfig create mode 100644 samples/rust/Makefile create mode 100644 samples/rust/hostprogs/.gitignore create mode 100644 samples/rust/hostprogs/Makefile create mode 100644 samples/rust/hostprogs/a.rs create mode 100644 samples/rust/hostprogs/b.rs create mode 100644 samples/rust/hostprogs/single.rs create mode 100644 samples/rust/rust_minimal.rs
samples/Kconfig +2 -0
@@ -263,6 +263,8 @@ config SAMPLE_CORESIGHT_SYSCFG This demonstrates how a user may create their own CoreSight configurations and easily load them into the system at runtime. +source "samples/rust/Kconfig" + endif # SAMPLES config HAVE_SAMPLE_FTRACE_DIRECT
samples/Makefile +1 -0
@@ -35,3 +35,4 @@ subdir-$(CONFIG_SAMPLE_WATCH_QUEUE) += watch_queue obj-$(CONFIG_DEBUG_KMEMLEAK_TEST) += kmemleak/ obj-$(CONFIG_SAMPLE_CORESIGHT_SYSCFG) += coresight/ obj-$(CONFIG_SAMPLE_FPROBE) += fprobe/ +obj-$(CONFIG_SAMPLES_RUST) += rust/
samples/rust/Kconfig new file +30 -0
@@ -0,0 +1,30 @@ +# SPDX-License-Identifier: GPL-2.0 + +menuconfig SAMPLES_RUST + bool "Rust samples" + depends on RUST + help + You can build sample Rust kernel code here. + + If unsure, say N. + +if SAMPLES_RUST + +config SAMPLE_RUST_MINIMAL + tristate "Minimal" + help + This option builds the Rust minimal module sample. + + To compile this as a module, choose M here: + the module will be called rust_minimal. + + If unsure, say N. + +config SAMPLE_RUST_HOSTPROGS + bool "Host programs" + help + This option builds the Rust host program samples. + + If unsure, say N. + +endif # SAMPLES_RUST
samples/rust/Makefile new file +5 -0
@@ -0,0 +1,5 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o + +subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS) += hostprogs
samples/rust/hostprogs/.gitignore new file +3 -0
@@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0 + +single
samples/rust/hostprogs/Makefile new file +5 -0
@@ -0,0 +1,5 @@ +# SPDX-License-Identifier: GPL-2.0 + +hostprogs-always-y := single + +single-rust := y
samples/rust/hostprogs/a.rs new file +7 -0
@@ -0,0 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust single host program sample: module `a`. + +pub (crate )fn f (x:i32 ) { +println! ("The number is {}." , x); +}
samples/rust/hostprogs/b.rs new file +5 -0
@@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust single host program sample: module `b`. + +pub (crate )const CONSTANT :i32 =42 ;
samples/rust/hostprogs/single.rs new file +12 -0
@@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust single host program sample. + +mod a; +mod b; + +fn main () { +println! ("Hello world!" ); + + a::f (b::CONSTANT ); +}
samples/rust/rust_minimal.rs new file +38 -0
@@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust minimal sample. + +use kernel::prelude::*; + +module! { +type :RustMinimal , +name :b"rust_minimal" , + author:b"Rust for Linux Contributors" , + description:b"Rust minimal sample" , + license:b"GPL" , +} + +struct RustMinimal { + numbers:Vec <i32 >, +} + +impl kernel::Module for RustMinimal { +fn init (_module: &'staticThisModule ) ->Result <Self > { +pr_info! ("Rust minimal sample (init)\n" ); +pr_info! ("Am I built-in? {}\n" , !cfg! (MODULE )); + +let mut numbers =Vec ::new (); + numbers.try_push (72 )?; + numbers.try_push (108 )?; + numbers.try_push (200 )?; + +Ok (RustMinimal { numbers }) + } +} + +impl Drop for RustMinimal { +fn drop (&mut self) { +pr_info! ("My numbers are {:?}\n" , self.numbers); +pr_info! ("Rust minimal sample (exit)\n" ); + } +}
Signature · 1 line
2.37.3
Miguel Ojeda
maintainerPATCH v10 27/27 MAINTAINERS: Rust
In reply to Miguel OjedaMiguel, Alex and Wedson will be maintaining the Rust support.
Boqun, Gary and Björn will be reviewers.
--- MAINTAINERS | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)
MAINTAINERS +18 -0
@@ -17758,6 +17758,24 @@ F: include/rv/ F: kernel/trace/rv/ F: tools/verification/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[email protected]> +R: Boqun Feng <[email protected]> +R: Gary Guo <[email protected]> +R: Björn Roy Baron <[email protected]> +L: [email protected] +S: Supported +W: https://github.com/Rust-for-Linux/linux +B: https://github.com/Rust-for-Linux/linux/issues +T: git https://github.com/Rust-for-Linux/linux.git rust-next +F: Documentation/rust/ +F: rust/ +F: samples/rust/ +F: scripts/*rust* +K: \b(?i:rust)\b + RXRPC SOCKETS (AF_RXRPC) M: David Howells <[email protected]> M: Marc Dionne <[email protected]>
Signature · 1 line
2.37.3
Re: [PATCH v10 10/27] rust: add `macros` crate
In reply to Miguel OjedaOn Tue, Sep 27, 2022 at 03:14:41PM +0200, Miguel Ojeda wrote:
[...]
Quoted 11 lines
For instance, the
module!macro that is used by Rust modules is implemented here. It allows to easily declare the equivalent information to theMODULE_*macros in C modules, e.g.:module! {
type: RustMinimal,
name: b"rust_minimal",
author: b"Rust for Linux Contributors",
description: b"Rust minimal sample",
license: b"GPL",
}
[...]
I remember that there was a switch from &u8 to &str on master branch a while ago. Why this patch was reverted? Strings are really better here.
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
In reply to Miguel OjedaOn Tue, Sep 27, 2022 at 03:14:39PM +0200, Miguel Ojeda wrote:
[...]
Quoted 12 lines
rust/alloc/vec/mod.rs +12
-0+/// Tries to append an element to the back of a collection. +/// +/// # Examples +/// +/// ``` +/// let mut vec = vec![1, 2]; +/// vec.try_push(3).unwrap(); +/// assert_eq!(vec, [1, 2, 3]); +/// ``` +#[inline] +#[stable(feature = "kernel" , since = "1.0.0" )] +pub fn try_push (&mut self, value:T ) ->Result <(),TryReserveError > {
rust/alloc/vec/mod.rs impl<T, A: Allocator> Vec<T, A> { · line 1765
Quoted 10 lines
rust/alloc/vec/mod.rs +10
-0+if self.len == self.buf.capacity () { + self.buf.try_reserve_for_push (self.len)?; + } +unsafe { +let end = self.as_mut_ptr ().add (self.len); + ptr::write (end, value); + self.len +=1 ; + } +Ok (()) + }
[...]
Not being able to pass GFP flags here kinda limits the scope of Rust in kernel. I think that it must be supported in the final version that gets in.
Re: [PATCH v10 10/27] rust: add `macros` crate
In reply to Konstantin ShelekhinQuoted 3 lines · Konstantin Shelekhin
I remember that there was a switch from &u8 to &str on master branch a while ago. Why this patch was reverted? Strings are really better here.
It was not reverted; but it was merged right after v8. Then v9 was a trimmed v8 and v10 is intended to resolve a few last nits from v9.
In other words, there are many changes (including the vast majority of the kernel crate) that will come afterwards.
Please see the cover letter(s) for details.
Cheers,
Miguel
Re: [PATCH v10 10/27] rust: add `macros` crate
In reply to Konstantin ShelekhinQuoted 13 lines · Konstantin Shelekhin
On Tue, Sep 27, 2022 at 03:14:41PM +0200, Miguel Ojeda wrote:
[...]Quoted 11 lines
For instance, the
module!macro that is used by Rust modules is implemented here. It allows to easily declare the equivalent information to theMODULE_*macros in C modules, e.g.:module! {
type: RustMinimal,
name: b"rust_minimal",
author: b"Rust for Linux Contributors",
description: b"Rust minimal sample",
license: b"GPL",
}
Quoted 4 lines
[...]
I remember that there was a switch from &u8 to &str on master branch a while ago. Why this patch was reverted? Strings are really better here.
ASCII versus UTF8
Groeten
Geert Stappers
Signature · 1 line
Silence is hard to parse
Re: [PATCH v10 01/27] kallsyms: use `ARRAY_SIZE` instead of hardcoded size
In reply to Miguel OjedaQuoted 28 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This removes one place where the
500constant is hardcoded.Reviewed-by Kees Cook <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- scripts/kallsyms.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)scripts/kallsyms.c +1
-1@@ -206,7 +206,7 @@ static struct sym_entry *read_symbol(FILE *in) rc =fscanf (in,"%llx %c %499s\n" , &addr, &type, name);if (rc !=3 ) { -if (rc !=EOF &&fgets (name,500 , in) ==NULL ) +if (rc !=EOF &&fgets (name,ARRAY_SIZE (name), in) ==NULL )fprintf (stderr,"Read error or end of file.\n" );return NULL ; }Signature · 1 line
2.37.3
Regards
Geert Stappers
Hopes to see the kallsyms patches getting accepted, that they don't show up in v11 of the Rust patch serie.
Signature · 1 line
Silence is hard to parse
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
In reply to Konstantin ShelekhinQuoted 4 lines · Konstantin Shelekhin
Not being able to pass GFP flags here kinda limits the scope of Rust in kernel. I think that it must be supported in the final version that gets in.
Flags will be supported one way or the other in the future, but I was requested to do v10 as a v9 with the last nits resolved.
Please see the cover letter for details.
Cheers,
Miguel
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Miguel OjedaQuoted 19 lines · Miguel Ojeda
Miguel, Alex and Wedson will be maintaining the Rust support.
Boqun, Gary and Björn will be reviewers.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- MAINTAINERS | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)MAINTAINERS +0
-0
MAINTAINERS F: include/rv/ · line 17764
Quoted 7 lines
MAINTAINERS +4
-0@@ -17758,6 +17758,24 @@ F: include/rv/ F: kernel/trace/rv/ F: tools/verification/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[email protected]>
<screenshot from="response of a reply-to-all that I just did">
** Address not found **
Your message wasn't delivered to [email protected] because the address couldn't be found, or is unable to receive mail.
Learn more here: https://support.google.com/mail/answer/6596
The response was:
The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/answer/6596
</screenshot>
Quoted 18 lines
MAINTAINERS +14
-1+R: Boqun Feng <[email protected]> +R: Gary Guo <[email protected]> +R: Björn Roy Baron <[email protected]> +L: [email protected] +S: Supported +W: https://github.com/Rust-for-Linux/linux +B: https://github.com/Rust-for-Linux/linux/issues +T: git https://github.com/Rust-for-Linux/linux.git rust-next +F: Documentation/rust/ +F: rust/ +F: samples/rust/ +F: scripts/*rust* +K: \b(?i:rust)\b + RXRPC SOCKETS (AF_RXRPC) M: David Howells <[email protected]> M: Marc Dionne <[email protected]> --
Quoted 2 lines
2.37.3
Groeten
Geert Stappers
--
Silence is hard to parse
Re: [PATCH v10 01/27] kallsyms: use `ARRAY_SIZE` instead of hardcoded size
In reply to Miguel OjedaQuoted 11 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This removes one place where the
500constant is hardcoded.Reviewed-by Kees Cook <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- scripts/kallsyms.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
Re: [PATCH v10 02/27] kallsyms: avoid hardcoding buffer size
In reply to Miguel OjedaQuoted 8 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This introduces
KSYM_NAME_LEN_BUFFERin place of the previously hardcoded size of the input buffer.It will also make it easier to update the size in a single place in a later patch.
Quoted 8 lines
Reviewed-by Kees Cook <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- scripts/kallsyms.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
Re: [PATCH v10 03/27] kallsyms: add static relationship between `KSYM_NAME_LEN{,_BUFFER}`
In reply to Miguel OjedaQuoted 25 lines · Miguel Ojeda
This adds a static assert to ensure
KSYM_NAME_LEN_BUFFERgets updated whenKSYM_NAME_LENchanges.The relationship used is one that keeps the new size (512+1) close to the original buffer size (500).
Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- scripts/kallsyms.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)scripts/kallsyms.c +2
-2@@ -32,8 +32,18 @@#define KSYM_NAME_LEN 128 -/* A substantially bigger size than the current maximum. */ -#define KSYM_NAME_LEN_BUFFER 499 +/* +* A substantially bigger size than the current maximum.
scripts/kallsyms.c line 46
Quoted 10 lines
scripts/kallsyms.c +10
-0+* +* It cannot be defined as an expression because it gets stringified +* for the fscanf() format string. Therefore, a _Static_assert() is +* used instead to maintain the relationship with KSYM_NAME_LEN. +*/ +#define KSYM_NAME_LEN_BUFFER 512 +_Static_assert ( +KSYM_NAME_LEN_BUFFER ==KSYM_NAME_LEN *4 , +"Please keep KSYM_NAME_LEN_BUFFER in sync with KSYM_NAME_LEN" +);
Messy, but I can't think of any other way right now either :(
Re: [PATCH v10 04/27] kallsyms: support "big" kernel symbols
In reply to Miguel OjedaQuoted 22 lines · Miguel Ojeda
Rust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc.
Increasing to 255 is not enough in some cases, therefore introduce longer lengths to the symbol table.
In order to avoid increasing all lengths to 2 bytes (since most of them are small, including many Rust ones), use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Matthew Wilcox <[email protected]>Signed-off-by Matthew Wilcox <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 4 lines
--- kernel/kallsyms.c | 26 ++++++++++++++++++++++---- scripts/kallsyms.c | 29 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-)
Re: [PATCH v10 05/27] kallsyms: increase maximum kernel symbol length to 512
In reply to Miguel OjedaQuoted 38 lines · Miguel Ojeda
Rust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc. For instance, the following code:
pub mod my_module { pub struct MyType; pub struct MyGenericType<T>(T); pub trait MyTrait { fn my_method() -> u32; } impl MyTrait for MyGenericType<MyType> { fn my_method() -> u32 { 42 } } }generates a symbol of length 96 when using the upcoming v0 mangling scheme:
_RNvXNtCshGpAVYOtgW1_7example9my_moduleINtB2_13MyGenericTypeNtB2_6MyTypeENtB2_7MyTrait9my_methodAt the moment, Rust symbols may reach up to 300 in length. Setting 512 as the maximum seems like a reasonable choice to keep some headroom.
Reviewed-by Kees Cook <[email protected]>Reviewed-by Petr Mladek <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 8 lines
--- include/linux/kallsyms.h | 2 +- kernel/livepatch/core.c | 4 ++-- scripts/kallsyms.c | 4 ++-- tools/include/linux/kallsyms.h | 2 +- tools/lib/perf/include/perf/event.h | 2 +- tools/lib/symbol/kallsyms.h | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-)
Re: [PATCH v10 06/27] rust: add C helpers
In reply to Miguel OjedaQuoted 23 lines · Miguel Ojeda
Introduces the source file that will contain forwarders to C macros and inlined functions.
Initially this only contains a single helper, but will gain more as more functionality is added to the
kernelcrate in the future.Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Geoffrey Thomas <[email protected]>Signed-off-by Geoffrey Thomas <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Sven Van Asbroeck <[email protected]>Signed-off-by Sven Van Asbroeck <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Maciej Falkowski <[email protected]>Signed-off-by Maciej Falkowski <[email protected]>Co-developed-by Wei Liu <[email protected]>Signed-off-by Wei Liu <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 4 lines
--- rust/helpers.c | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 rust/helpers.c
Re: [PATCH v10 14/27] vsprintf: add new `%pA` format specifier
In reply to Miguel OjedaQuoted 20 lines · Miguel Ojeda
From: Gary Guo <[email protected]>
This patch adds a format specifier
%pAtovsprintfwhich formats a pointer ascore::fmt::Arguments. Doing so allows us to directly format to the internal buffer ofprintf, so we do not have to use a temporary buffer on the stack to pre-assemble the message on the Rust side.This specifier is intended only to be used from Rust and not for C, so
checkpatch.plis intentionally unchanged to catch any misuse.Reviewed-by Kees Cook <[email protected]>Acked-by Petr Mladek <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 4 lines
--- Documentation/core-api/printk-formats.rst | 10 ++++++++++ lib/vsprintf.c | 13 +++++++++++++ 2 files changed, 23 insertions(+)
Re: [PATCH v10 17/27] scripts: decode_stacktrace: demangle Rust symbols
In reply to Miguel OjedaQuoted 9 lines · Miguel Ojeda
Recent versions of both Binutils (
c++filt) and LLVM (llvm-cxxfilt) provide Rust v0 mangling support.Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 3 lines
--- scripts/decode_stacktrace.sh | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
Re: [PATCH v10 16/27] scripts: checkpatch: enable language-independent checks for Rust
In reply to Miguel OjedaQuoted 14 lines · Miguel Ojeda
Include Rust in the "source code files" category, so that the language-independent tests are checked for Rust too, and teach
checkpatchabout the comment style for Rust files.This enables the malformed SPDX check, the misplaced SPDX license tag check, the long line checks, the lines without a newline check and the embedded filename check.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 3 lines
--- scripts/checkpatch.pl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
Re: [PATCH v10 15/27] scripts: checkpatch: diagnose uses of `%pA` in the C side as errors
In reply to Miguel OjedaQuoted 18 lines · Miguel Ojeda
The
%pAformat specifier is only intended to be used from Rust.
checkpatch.plalready gives a warning for invalid specificers:WARNING: Invalid vsprintf pointer extension '%pA'
This makes it an error and introduces an explanatory message:
ERROR: Invalid vsprintf pointer extension '%pA' - '%pA' is only intended to be used from Rust code
Suggested-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Joe Perches <[email protected]>Signed-off-by Joe Perches <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 3 lines
--- scripts/checkpatch.pl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
In reply to Miguel OjedaQuoted 5 lines · Miguel Ojeda
«Внимание! Данное письмо от внешнего адресата!»
Quoted 1 line · Konstantin Shelekhin
Quoted 8 lines
Quoted 3 lines
Not being able to pass GFP flags here kinda limits the scope of Rust in kernel. I think that it must be supported in the final version that gets in.
Flags will be supported one way or the other in the future, but I was requested to do v10 as a v9 with the last nits resolved.
Please see the cover letter for details.
Sorry, my bad.
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Geert StappersQuoted 33 lines · Geert Stappers
Quoted 19 lines · Miguel Ojeda
Miguel, Alex and Wedson will be maintaining the Rust support.
Boqun, Gary and Björn will be reviewers.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- MAINTAINERS | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)MAINTAINERS +0
-0MAINTAINERS F: include/rv/ · line 17764
Quoted 7 lines
MAINTAINERS +4
-0@@ -17758,6 +17758,24 @@ F: include/rv/ F: kernel/trace/rv/ F: tools/verification/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[email protected]><screenshot from="response of a reply-to-all that I just did">
** Address not found **Your message wasn't delivered to [email protected] because the address couldn't be found, or is unable to receive mail.
Quoted 8 lines
Learn more here: https://support.google.com/mail/answer/6596
The response was:
The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/answer/6596
</screenshot>
Wedson, can you send (or Ack) the following patch? :)
.mailmap +1 -0
@@ -433,6 +433,7 @@ Vlad Dogaru <[email protected]> <[email protected]> Vladimir Davydov <[email protected]> <[email protected]> Vladimir Davydov <[email protected]> <[email protected]> WeiXiong Liao <[email protected]> <[email protected]> +Wedson Almeida Filho <[email protected]> <[email protected]> Will Deacon <[email protected]> <[email protected]> Wolfram Sang <[email protected]> <[email protected]> Wolfram Sang <[email protected]> <[email protected]>
Signature · 1 line
Kees Cook
Re: [PATCH v10 12/27] rust: add `kernel` crate
In reply to Miguel Ojedarust/kernel/allocator.rs line 16
Quoted 5 lines · Miguel Ojeda
rust/kernel/allocator.rs new file +5
-0+unsafe impl GlobalAlloc for KernelAllocator { +unsafe fn alloc (&self, layout:Layout ) -> *mut u8 { +// `krealloc()` is used instead of `kmalloc()` because the latter is +// an inline function and cannot be bound to as a result. +unsafe { bindings::krealloc (ptr::null (), layout.size (), bindings::GFP_KERNEL )as *mut u8 }
This feels "odd" to me. Why not just use __kmalloc() instead of krealloc()? I think that will get you the same kasan tracking, and should be a tiny bit faster (1-2 less function calls).
I guess it probably doesn't matter right now, just curious, and not a big deal at all.
Other minor comments:
rust/kernel/error.rs line 13
Quoted 5 lines
rust/kernel/error.rs new file +5
-0+/// Contains the C-compatible error codes. +pub mod code { +/// Out of memory. +pub const ENOMEM :super ::Error =super ::Error (-(crate ::bindings::ENOMEM as i32 )); +}
You'll be adding other error values here over time, right?
Quoted 11 lines
rust/kernel/error.rs new file +11
-0+/// A [`Result`] with an [`Error`] error type. +/// +/// To be used as the return type for functions that may fail. +/// +/// # Error codes in C and Rust +/// +/// In C, it is common that functions indicate success or failure through +/// their return value; modifying or returning extra data through non-`const` +/// pointer parameters. In particular, in the kernel, functions that may fail +/// typically return an `int` that represents a generic error code. We model +/// those as [`Error`].
rust/kernel/error.rs line 59
Quoted 10 lines
rust/kernel/error.rs new file +10
-0+/// +/// In Rust, it is idiomatic to model functions that may fail as returning +/// a [`Result`]. Since in the kernel many functions return an error code, +/// [`Result`] is a type alias for a [`core::result::Result`] that uses +/// [`Error`] as its error type. +/// +/// Note that even if a function does not return anything when it succeeds, +/// it should still be modeled as returning a `Result` rather than +/// just an [`Error`]. +pub type Result <T = ()> = core::result::Result <T ,Error >;
What about functions that do have return functions of:
>= 0 number of bytes read/written/consumed/whatever < 0 error code
Would that use Result or Error as a type? Or is it best just to not try to model that mess in Rust calls? :)
rust/kernel/print.rs line 198
Quoted 5 lines
rust/kernel/print.rs new file +5
-0+macro_rules! pr_info ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate ::print::format_strings::INFO , $($arg)*) + ) +);
In the long run, using "raw" print macros like this is usually not the thing to do. Drivers always have a device to reference the message to, and other things like filesystems and subsystems have a prefix to use as well.
Hopefully not many will use these as-is and we can wrap them properly later on.
Then there's the whole dynamic debug stuff, but that's a different topic.
Anyway, all looks sane to me, sorry for the noise:
Re: [PATCH v10 11/27] rust: add `bindings` crate
In reply to Miguel OjedaQuoted 33 lines · Miguel Ojeda
This crate contains the bindings to the C side of the kernel.
Calling C (in general, FFI) is assumed to be unsafe in Rust and, in many cases, this is accurate. For instance, virtually all C functions that take a pointer are unsafe since, typically, it will be dereferenced at some point (and in most cases there is no way for the callee to check its validity beforehand).
Since one of the goals of using Rust in the kernel is precisely to avoid unsafe code in "leaf" kernel modules (e.g. drivers), these bindings should not be used directly by them.
Instead, these bindings need to be wrapped into safe abstractions. These abstractions provide a safe API that kernel modules can use. In this way, unsafe code in kernel modules is minimized.
Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Finn Behrens <[email protected]>Signed-off-by Finn Behrens <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Sven Van Asbroeck <[email protected]>Signed-off-by Sven Van Asbroeck <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Maciej Falkowski <[email protected]>Signed-off-by Maciej Falkowski <[email protected]>Co-developed-by Jiapeng Chong <[email protected]>Signed-off-by Jiapeng Chong <[email protected]>Co-developed-by Björn Roy Baron <[email protected]>Signed-off-by Björn Roy Baron <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 6 lines
--- rust/bindings/bindings_helper.h | 13 ++++++++ rust/bindings/lib.rs | 53 +++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 rust/bindings/bindings_helper.h create mode 100644 rust/bindings/lib.rs
Re: [PATCH v10 26/27] samples: add first Rust examples
In reply to Miguel OjedaQuoted 8 lines · Miguel Ojeda
The beginning of a set of Rust modules that showcase how Rust modules look like and how to use the abstracted kernel features.
It also includes an example of a Rust host program with several modules.
These samples also double as tests in the CI.
Quoted 10 lines
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Finn Behrens <[email protected]>Signed-off-by Finn Behrens <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Milan Landaverde <[email protected]>Signed-off-by Milan Landaverde <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 21/27] scripts: add `is_rust_module.sh`
In reply to Miguel OjedaQuoted 16 lines · Miguel Ojeda
From: Daniel Xu <[email protected]>
This script is used to detect whether a kernel module is written in Rust.
It will later be used to disable BTF generation on Rust modules as BTF does not yet support Rust.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Daniel Xu <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 4 lines
--- scripts/is_rust_module.sh | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100755 scripts/is_rust_module.sh
Re: [PATCH v10 23/27] Kbuild: add Rust support
In reply to Miguel OjedaQuoted 55 lines · Miguel Ojeda
Having most of the new files in place, we now enable Rust support in the build system, including
Kconfigentries related to Rust, the Rust configuration printer and a few other bits.Reviewed-by Kees Cook <[email protected]>Reviewed-by Nick Desaulniers <[email protected]>Tested-by Nick Desaulniers <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Finn Behrens <[email protected]>Signed-off-by Finn Behrens <[email protected]>Co-developed-by Adam Bratschi-Kaye <[email protected]>Signed-off-by Adam Bratschi-Kaye <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Michael Ellerman <[email protected]>Signed-off-by Michael Ellerman <[email protected]>Co-developed-by Sven Van Asbroeck <[email protected]>Signed-off-by Sven Van Asbroeck <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boris-Chengbiao Zhou <[email protected]>Signed-off-by Boris-Chengbiao Zhou <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Douglas Su <[email protected]>Signed-off-by Douglas Su <[email protected]>Co-developed-by Dariusz Sosnowski <[email protected]>Signed-off-by Dariusz Sosnowski <[email protected]>Co-developed-by Antonio Terceiro <[email protected]>Signed-off-by Antonio Terceiro <[email protected]>Co-developed-by Daniel Xu <[email protected]>Signed-off-by Daniel Xu <[email protected]>Co-developed-by Björn Roy Baron <[email protected]>Signed-off-by Björn Roy Baron <[email protected]>Co-developed-by Martin Rodriguez Reboredo <[email protected]>Signed-off-by Martin Rodriguez Reboredo <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- .gitignore | 2 + Makefile | 172 ++++++++++++++- arch/Kconfig | 6 + include/linux/compiler_types.h | 6 +- init/Kconfig | 46 +++- kernel/configs/rust.config | 1 + lib/Kconfig.debug | 34 +++ rust/.gitignore | 8 + rust/Makefile | 381 +++++++++++++++++++++++++++++++++ rust/bindgen_parameters | 21 ++ scripts/Kconfig.include | 6 +- scripts/Makefile | 3 + scripts/Makefile.build | 60 ++++++ scripts/Makefile.debug | 8 + scripts/Makefile.host | 34 ++- scripts/Makefile.lib | 12 ++
Quoted 8 lines
scripts/Makefile.modfinal | 8 +- scripts/cc-version.sh | 12 +- scripts/kconfig/confdata.c | 75 +++++++ 19 files changed, 869 insertions(+), 26 deletions(-) create mode 100644 kernel/configs/rust.config create mode 100644 rust/.gitignore create mode 100644 rust/Makefile create mode 100644 rust/bindgen_parameters
Re: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Miguel OjedaQuoted 12 lines · Miguel Ojeda
Note that only
x86_64is covered and not all features nor mitigations are handled, but it is enough as a starting point and showcases the basics needed to add Rust support for a new architecture.Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by David Gow <[email protected]>Signed-off-by David Gow <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 6 lines
--- Documentation/rust/arch-support.rst | 1 + arch/x86/Kconfig | 1 + arch/x86/Makefile | 10 ++++++++++ scripts/generate_rust_target.rs | 15 +++++++++++++-- 4 files changed, 25 insertions(+), 2 deletions(-)
Re: [PATCH v10 13/27] rust: export generated symbols
In reply to Miguel OjedaQuoted 57 lines · Miguel Ojeda
All symbols are reexported reusing the
EXPORT_SYMBOL_GPLmacro from C. The lists of symbols are generated on the fly.There are three main sets of symbols to distinguish:
- The ones from the
coreandalloccrates (from the Rust standard library). The code is licensed as Apache/MIT.- The ones from our abstractions in the
kernelcrate.- The helpers (already exported since they are not generated).
We export everything as GPL. This ensures we do not mistakenly expose GPL kernel symbols/features as non-GPL, even indirectly.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Björn Roy Baron <[email protected]>Signed-off-by Björn Roy Baron <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- rust/exports.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 rust/exports.crust/exports.c new file +21
-0@@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* A hack to export Rust symbols for loadable modules without having to redo +* the entire `include/linux/export.h` logic in Rust. +* +* This requires the Rust's new/future `v0` mangling scheme because the default +* one ("legacy") uses invalid characters for C identifiers (thus we cannot use +* the `EXPORT_SYMBOL_*` macros). +* +* All symbols are exported as GPL-only to guarantee no GPL-only feature is +* accidentally exposed. +*/ + +#include <linux/module.h> + +#define EXPORT_SYMBOL_RUST_GPL (sym) extern int sym; EXPORT_SYMBOL_GPL(sym) + +#include "exports_core_generated.h" +#include "exports_alloc_generated.h" +#include "exports_bindings_generated.h" +#include "exports_kernel_generated.h" Signature · 1 line
2.37.3
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Kees CookQuoted 50 lines · Kees Cook
Quoted 33 lines · Geert Stappers
Quoted 19 lines · Miguel Ojeda
Miguel, Alex and Wedson will be maintaining the Rust support.
Boqun, Gary and Björn will be reviewers.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- MAINTAINERS | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)MAINTAINERS +0
-0MAINTAINERS F: include/rv/ · line 17764
Quoted 7 lines
MAINTAINERS +4
-0@@ -17758,6 +17758,24 @@ F: include/rv/ F: kernel/trace/rv/ F: tools/verification/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[email protected]><screenshot from="response of a reply-to-all that I just did">
** Address not found **Your message wasn't delivered to [email protected] because the address couldn't be found, or is unable to receive mail.
Quoted 8 lines
Learn more here: https://support.google.com/mail/answer/6596
The response was:
The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/answer/6596
</screenshot>Wedson, can you send (or Ack) the following patch? :)
.mailmap +0
-0
.mailmap Vlad Dogaru <[email protected]> <[email protected]> · line 436
Quoted 4 lines
.mailmap +1
-0@@ -433,6 +433,7 @@ Vlad Dogaru <[email protected]> <[email protected]> Vladimir Davydov <[email protected]> <[email protected]> Vladimir Davydov <[email protected]> <[email protected]> WeiXiong Liao <[email protected]> <[email protected]> +Wedson Almeida Filho <[email protected]> <[email protected]>
How about just fixing up the emails in these patches, which will keep us from having bouncing ones for those of us who do not use the .mailmap file.
thanks,
greg k-h
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
In reply to Miguel OjedaQuoted 30 lines · Miguel Ojeda
This customizes the subset of the Rust standard library
allocthat was just imported as-is, mainly by:- Adding SPDX license identifiers.
- Skipping modules (e.g.
rcandsync) via newcfgs.- Adding fallible (
try_*) versions of existing infallible methods (i.e. returning aResultinstead of panicking).Since the standard library requires stable/unstable attributes, these additions are annotated with:
#[stable(feature = "kernel", since = "1.0.0")]
Using "kernel" as the feature allows to have the additions clearly marked. The "1.0.0" version is just a placeholder.
(At the moment, only one is needed, but in the future more fallible methods will be added).
Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Matthew Bakhtiari <[email protected]>Signed-off-by Matthew Bakhtiari <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 1 line
---
Re: [PATCH v10 12/27] rust: add `kernel` crate
In reply to Greg Kroah-HartmanQuoted 8 lines · Greg Kroah-Hartman
rust/kernel/allocator.rs line 16
Quoted 5 lines · Miguel Ojeda
rust/kernel/allocator.rs new file +5
-0+unsafe impl GlobalAlloc for KernelAllocator { +unsafe fn alloc (&self, layout:Layout ) -> *mut u8 { +// `krealloc()` is used instead of `kmalloc()` because the latter is +// an inline function and cannot be bound to as a result. +unsafe { bindings::krealloc (ptr::null (), layout.size (), bindings::GFP_KERNEL )as *mut u8 }
Quoted 4 lines
This feels "odd" to me. Why not just use
__kmalloc()instead ofkrealloc()? I think that will get you the same kasan tracking, and should be a tiny bit faster (1-2 less function calls).
This may literally be the oldest code in the project :-). To the best of my recollection, it's krealloc simply because that seemed like a public API that worked. I don't think it even occurred to use to look at __kmalloc.
Quoted 6 lines
I guess it probably doesn't matter right now, just curious, and not a big deal at all.
Other minor comments:
Quoted 8 lines
rust/kernel/error.rs line 13
Quoted 5 lines
rust/kernel/error.rs new file +5
-0+/// Contains the C-compatible error codes. +pub mod code { +/// Out of memory. +pub const ENOMEM :super ::Error =super ::Error (-(crate ::bindings::ENOMEM as i32 )); +}You'll be adding other error values here over time, right?
Yes -- this is the most minimal set that's needed for the initial patch set. The full branch has every error constant bound.
Quoted 27 lines
Quoted 12 lines
rust/kernel/error.rs new file +11
-0+/// A [`Result`] with an [`Error`] error type. +/// +/// To be used as the return type for functions that may fail. +/// +/// # Error codes in C and Rust +/// +/// In C, it is common that functions indicate success or failure through +/// their return value; modifying or returning extra data through non-`const` +/// pointer parameters. In particular, in the kernel, functions that may fail +/// typically return an `int` that represents a generic error code. We model +/// those as [`Error`]. rust/kernel/error.rs line 59
Quoted 10 lines
rust/kernel/error.rs new file +10
-0+/// +/// In Rust, it is idiomatic to model functions that may fail as returning +/// a [`Result`]. Since in the kernel many functions return an error code, +/// [`Result`] is a type alias for a [`core::result::Result`] that uses +/// [`Error`] as its error type. +/// +/// Note that even if a function does not return anything when it succeeds, +/// it should still be modeled as returning a `Result` rather than +/// just an [`Error`]. +pub type Result <T = ()> = core::result::Result <T ,Error >;What about functions that do have return functions of:
>= 0 number of bytes read/written/consumed/whatever < 0 error code
Quoted 3 lines
Would that use Result or Error as a type? Or is it best just to not try to model that mess in Rust calls? :)
We'd model that as a Result<usize>. Negative values would become Err(EWHATEVER) and non-negative values would be Ok(n). Then at the boundaries of Rust/C code we'd convert as appropriate.
Quoted 14 lines
rust/kernel/print.rs line 198
Quoted 5 lines
rust/kernel/print.rs new file +5
-0+macro_rules! pr_info ( + ($($arg:tt)*) => ( + $crate::print_macro!($crate ::print::format_strings::INFO , $($arg)*) + ) +);In the long run, using "raw" print macros like this is usually not the thing to do. Drivers always have a device to reference the message to, and other things like filesystems and subsystems have a prefix to use as well.
Hopefully not many will use these as-is and we can wrap them properly later on.
Quoted 6 lines
Then there's the whole dynamic debug stuff, but that's a different topic.
Anyway, all looks sane to me, sorry for the noise:
Reviewed-by Greg Kroah-Hartman <[email protected]>
Cheers,
Alex
Signature · 1 line
All that is necessary for evil to succeed is for good people to do nothing.
Re: [PATCH v10 12/27] rust: add `kernel` crate
In reply to Greg Kroah-HartmanQuoted 7 lines · Greg Kroah-Hartman
This feels "odd" to me. Why not just use
__kmalloc()instead ofkrealloc()? I think that will get you the same kasan tracking, and should be a tiny bit faster (1-2 less function calls).I guess it probably doesn't matter right now, just curious, and not a big deal at all.
Yeah, nowadays I think a "C helper" could have been used instead.
Quoted 1 line
You'll be adding other error values here over time, right?
Indeed, I removed all the ones we didn't use in v8 to reduce it a bit more. Sorry for the confusion! :)
Quoted 6 lines
What about functions that do have return functions of:
>= 0 number of bytes read/written/consumed/whatever < 0 error codeWould that use Result or Error as a type? Or is it best just to not try to model that mess in Rust calls? :)
Result, i.e. the "number of bytes" part would go in the Ok variant and the "error code" in the Err variant.
The benefit is that then you have to handle them "separately", i.e. you cannot confuse the number of bytes for the error code by mistake, or vice versa.
Quoted 7 lines
In the long run, using "raw" print macros like this is usually not the thing to do. Drivers always have a device to reference the message to, and other things like filesystems and subsystems have a prefix to use as well.
Hopefully not many will use these as-is and we can wrap them properly later on.
Definitely, we will have e.g. the dev_*! ones:
https://github.com/Rust-for-Linux/linux/blob/fcad53ca9071c7bf6a412640a82e679bad6d1cd4/rust/kernel/device.rs#L479-L502
Quoted 3 lines
Anyway, all looks sane to me, sorry for the noise:
Reviewed-by Greg Kroah-Hartman <[email protected]>
Thanks a lot for taking a look!
Cheers,
Miguel
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Greg Kroah-HartmanQuoted 4 lines · Greg Kroah-Hartman
How about just fixing up the emails in these patches, which will keep us from having bouncing ones for those of us who do not use the .mailmap file.
Sorry about that...
One question: if somebody wants to keep the Signed-off-bys and/or Git authorship information using the old email for the patches (except the MAINTAINERS entry), is that OK? (e.g. maybe because they did most of the work in their previous company).
Cc'ing Maciej since I got a bounce too: is it OK using your personal address?
Thanks!
Cheers,
Miguel
Wedson Almeida Filho
Acked-byRe: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Kees CookQuoted 37 lines · Kees Cook
Quoted 35 lines · Geert Stappers
Quoted 19 lines · Miguel Ojeda
Miguel, Alex and Wedson will be maintaining the Rust support.
Boqun, Gary and Björn will be reviewers.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- MAINTAINERS | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)MAINTAINERS +0
-0MAINTAINERS F: include/rv/ · line 17764
Quoted 7 lines
MAINTAINERS +4
-0@@ -17758,6 +17758,24 @@ F: include/rv/ F: kernel/trace/rv/ F: tools/verification/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[email protected]><screenshot from="response of a reply-to-all that I just did">
** Address not found **Your message wasn't delivered to [email protected] because the address couldn't be found, or is unable to receive mail.
Learn more here: https://support.google.com/mail/answer/6596
Quoted 8 lines
Quoted 6 lines
The response was:
The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/answer/6596
</screenshot>Wedson, can you send (or Ack) the following patch? :)
Quoted 16 lines
.mailmap +1
-1@@ -433,6 +433,7 @@ Vlad Dogaru <[email protected]> <[email protected]> Vladimir Davydov <[email protected]> <[email protected]> Vladimir Davydov <[email protected]> <[email protected]> WeiXiong Liao <[email protected]> <[email protected]> +Wedson Almeida Filho <[email protected]> <[email protected]> Will Deacon <[email protected]> <[email protected]> Wolfram Sang <[email protected]> <[email protected]> Wolfram Sang <[email protected]> <[email protected]> --Kees Cook
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
In reply to Konstantin ShelekhinQuoted 2 lines · Konstantin Shelekhin
Sorry, my bad.
No apologies needed! Thanks for taking a look like in v8 and v9 :)
Cheers,
Miguel
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Miguel OjedaQuoted 19 lines · Miguel Ojeda
Miguel, Alex and Wedson will be maintaining the Rust support.
Boqun, Gary and Björn will be reviewers.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- MAINTAINERS | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)MAINTAINERS +0
-0
MAINTAINERS F: include/rv/ · line 17764
Quoted 7 lines
MAINTAINERS +4
-0@@ -17758,6 +17758,24 @@ F: include/rv/ F: kernel/trace/rv/ F: tools/verification/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[email protected]>
As was pointed out, please don't put a known-invalid email in this file.
thanks,
greg k-h
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Miguel OjedaQuoted 7 lines · Miguel Ojeda
Quoted 4 lines · Greg Kroah-Hartman
How about just fixing up the emails in these patches, which will keep us from having bouncing ones for those of us who do not use the .mailmap file.
Quoted 6 lines
Sorry about that...
One question: if somebody wants to keep the Signed-off-bys and/or Git authorship information using the old email for the patches (except the
MAINTAINERSentry), is that OK? (e.g. maybe because they did most of the work in their previous company).
For known-broken emails, it's a pain as later on invocations of scripts/get_maintainer.pl will use those emails.
So please just use known-good addresses to start with.
thanks,
greg k-h
Re: [PATCH v10 27/27] MAINTAINERS: Rust
Quoted 10 lines · Greg Kroah-Hartman
Quoted 9 lines · Miguel Ojeda
Quoted 4 lines · Greg Kroah-Hartman
How about just fixing up the emails in these patches, which will keep us from having bouncing ones for those of us who do not use the .mailmap file.
Sorry about that...
Quoted 7 lines
Quoted 4 lines
One question: if somebody wants to keep the Signed-off-bys and/or Git authorship information using the old email for the patches (except the
MAINTAINERSentry), is that OK? (e.g. maybe because they did most of the work in their previous company).For known-broken emails, it's a pain as later on invocations of
scripts/get_maintainer.plwill use those emails.
FWIW, get_maintainer.pl does use .mailmap by default already.
Quoted 1 line
So please just use known-good addresses to start with.
Sure, that makes sense here too. I just sent the .mailmap patch because Wedson does have other patches in the kernel too, so it wasn't just for this case.
Signature · 1 line
Kees Cook
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Miguel OjedaQuoted 7 lines · Miguel Ojeda
Quoted 4 lines · Greg Kroah-Hartman
How about just fixing up the emails in these patches, which will keep us from having bouncing ones for those of us who do not use the .mailmap file.
Quoted 6 lines
Sorry about that...
One question: if somebody wants to keep the Signed-off-bys and/or Git authorship information using the old email for the patches (except the
MAINTAINERSentry), is that OK? (e.g. maybe because they did most of the work in their previous company).
IMO, the S-o-b's should stand since they're historical, but fixing MAINTAINERS to be up-to-date makes sense.
Signature · 1 line
Kees Cook
Re: [PATCH v10 14/27] vsprintf: add new `%pA` format specifier
In reply to Miguel OjedaQuoted 9 lines · Miguel Ojeda
This patch adds a format specifier
%pAtovsprintfwhich formats a pointer ascore::fmt::Arguments. Doing so allows us to directly format to the internal buffer ofprintf, so we do not have to use a temporary buffer on the stack to pre-assemble the message on the Rust side.This specifier is intended only to be used from Rust and not for C, so
checkpatch.plis intentionally unchanged to catch any misuse.
Quoted 9 lines
Reviewed-by Kees Cook <[email protected]>Acked-by Petr Mladek <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 27/27] MAINTAINERS: Rust
In reply to Kees CookQuoted 11 lines · Kees Cook
Quoted 9 lines · Miguel Ojeda
Quoted 4 lines · Greg Kroah-Hartman
How about just fixing up the emails in these patches, which will keep us from having bouncing ones for those of us who do not use the .mailmap file.
Sorry about that...
Quoted 7 lines
Quoted 4 lines
One question: if somebody wants to keep the Signed-off-bys and/or Git authorship information using the old email for the patches (except the
MAINTAINERSentry), is that OK? (e.g. maybe because they did most of the work in their previous company).IMO, the S-o-b's should stand since they're historical, but fixing
MAINTAINERSto be up-to-date makes sense.
Our intent wasn't to have a known-invalid email in MAINTAINERS, it was just my mistake: after leaving Google I updated my email in a lot of places but missed this one. Apologies for that.
The patch below fixes this:
MAINTAINERS +1 -1
@@ -17913,7 +17913,7 @@ F: tools/verification/ RUST M: Miguel Ojeda <[email protected]> M: Alex Gaynor <[email protected]> -M: Wedson Almeida Filho <[email protected]> +M: Wedson Almeida Filho <[email protected]> R: Boqun Feng <[email protected]> R: Gary Guo <[email protected]> R: Björn Roy Baron <[email protected]>
Thanks,
-Wedson
Re: [PATCH v10 27/27] MAINTAINERS: Rust
Quoted 4 lines · Wedson Almeida Filho
Our intent wasn't to have a known-invalid email in
MAINTAINERS, it was just my mistake: after leaving Google I updated my email in a lot of places but missed this one. Apologies for that.
It was also mine for not realizing it! :)
Quoted 1 line
The patch below fixes this:
Thanks Wedson!
Kees and I discussed how to proceed earlier and so I updated a few hours ago the branch collecting the tags we got so far and fixing your email address in MAINTAINERS, so it is there in rust-next now:
https://github.com/Rust-for-Linux/linux/blob/fd9517a1603f083dfa88f3cf9dc67d26f6ba0ec0/MAINTAINERS#L17764
Cheers,
Miguel
Re: [PATCH v10 09/27] rust: add `compiler_builtins` crate
In reply to Miguel OjedaQuoted 4 lines · Miguel Ojeda
Rust provides
compiler_builtinsas a port of LLVM'scompiler-rt. Since we do not need the vast majority of them, we avoid the dependency by providing our own crate.
Quoted 10 lines
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Sven Van Asbroeck <[email protected]>Signed-off-by Sven Van Asbroeck <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 22/27] rust: add `.rustfmt.toml`
In reply to Miguel OjedaQuoted 5 lines · Miguel Ojeda
This is the configuration file for the
rustfmttool.
rustfmtis a tool for formatting Rust code according to style guidelines. It is very commonly used across Rust projects.
Quoted 8 lines
The default configuration options are used.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 26/27] samples: add first Rust examples
In reply to Miguel OjedaQuoted 8 lines · Miguel Ojeda
The beginning of a set of Rust modules that showcase how Rust modules look like and how to use the abstracted kernel features.
It also includes an example of a Rust host program with several modules.
These samples also double as tests in the CI.
Quoted 10 lines
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Finn Behrens <[email protected]>Signed-off-by Finn Behrens <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Milan Landaverde <[email protected]>Signed-off-by Milan Landaverde <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Miguel OjedaQuoted 46 lines · Miguel Ojeda
Note that only
x86_64is covered and not all features nor mitigations are handled, but it is enough as a starting point and showcases the basics needed to add Rust support for a new architecture.Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by David Gow <[email protected]>Signed-off-by David Gow <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>--- Documentation/rust/arch-support.rst | 1 + arch/x86/Kconfig | 1 + arch/x86/Makefile | 10 ++++++++++ scripts/generate_rust_target.rs | 15 +++++++++++++-- 4 files changed, 25 insertions(+), 2 deletions(-)Documentation/rust/arch-support.rst +1
-0@@ -15,4 +15,5 @@ support corresponds to ``S`` values in the ``MAINTAINERS`` file. ============ ================ ============================================== Architecture Level of support Constraints ============ ================ ============================================== +``x86`` Maintained ``x86_64`` only. ============ ================ ==============================================arch/x86/Kconfig +1
-0@@ -257,6 +257,7 @@ config X86 select HAVE_STATIC_CALL_INLINE if HAVE_OBJTOOL select HAVE_PREEMPT_DYNAMIC_CALL select HAVE_RSEQ + select HAVE_RUST if X86_64 select HAVE_SYSCALL_TRACEPOINTS select HAVE_UACCESS_VALIDATION if HAVE_OBJTOOL select HAVE_UNSTABLE_SCHED_CLOCKarch/x86/Makefile +0
-0
arch/x86/Makefile export BITS · line 71
Quoted 4 lines
arch/x86/Makefile +1
-0@@ -68,6 +68,7 @@ export BITS # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53383 # KBUILD_CFLAGS += -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx +KBUILD_RUSTFLAGS += -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2
I do wonder how many more things you will need to list here. As far as I can tell there is also other avx512* flags for the x86_64 target.
That said, if this works today ...
Re: [PATCH v10 20/27] scripts: add `rust_is_available.sh`
In reply to Miguel OjedaQuoted 11 lines · Miguel Ojeda
This script tests whether the Rust toolchain requirements are in place to enable Rust support. It uses
min-tool-version.shto fetch the version numbers.The build system will call it to set
CONFIG_RUST_IS_AVAILABLEin a later patch.It also has an option (
-v) to explain what is missing, which is useful to set up the development environment. This is used via themake rustavailabletarget added in a later patch.
Quoted 12 lines
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Finn Behrens <[email protected]>Signed-off-by Finn Behrens <[email protected]>Co-developed-by Miguel Cano <[email protected]>Signed-off-by Miguel Cano <[email protected]>Co-developed-by Tiago Lam <[email protected]>Signed-off-by Tiago Lam <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 23/27] Kbuild: add Rust support
In reply to Miguel OjedaQuoted 30 lines · Miguel Ojeda
Having most of the new files in place, we now enable Rust support in the build system, including
Kconfigentries related to Rust, the Rust configuration printer and a few other bits.Reviewed-by Kees Cook <[email protected]>Reviewed-by Nick Desaulniers <[email protected]>Tested-by Nick Desaulniers <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Finn Behrens <[email protected]>Signed-off-by Finn Behrens <[email protected]>Co-developed-by Adam Bratschi-Kaye <[email protected]>Signed-off-by Adam Bratschi-Kaye <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Michael Ellerman <[email protected]>Signed-off-by Michael Ellerman <[email protected]>Co-developed-by Sven Van Asbroeck <[email protected]>Signed-off-by Sven Van Asbroeck <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boris-Chengbiao Zhou <[email protected]>Signed-off-by Boris-Chengbiao Zhou <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Douglas Su <[email protected]>Signed-off-by Douglas Su <[email protected]>Co-developed-by Dariusz Sosnowski <[email protected]>Signed-off-by Dariusz Sosnowski <[email protected]>Co-developed-by Antonio Terceiro <[email protected]>
Quoted 8 lines
Signed-off-by Antonio Terceiro <[email protected]>Co-developed-by Daniel Xu <[email protected]>Signed-off-by Daniel Xu <[email protected]>Co-developed-by Björn Roy Baron <[email protected]>Signed-off-by Björn Roy Baron <[email protected]>Co-developed-by Martin Rodriguez Reboredo <[email protected]>Signed-off-by Martin Rodriguez Reboredo <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 01/27] kallsyms: use `ARRAY_SIZE` instead of hardcoded size
In reply to Miguel OjedaQuoted 8 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This removes one place where the
500constant is hardcoded.Reviewed-by Kees Cook <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Re: [PATCH v10 02/27] kallsyms: avoid hardcoding buffer size
In reply to Miguel OjedaQuoted 5 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This introduces
KSYM_NAME_LEN_BUFFERin place of the previously hardcoded size of the input buffer.
Quoted 7 lines
It will also make it easier to update the size in a single place in a later patch.
Reviewed-by Kees Cook <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>
Quoted 3 lines · Miguel Ojeda
Miguel Ojeda (22):
rust: import upstreamalloccrate
I cannot find this patch in my inbox. That's probably filtered out by the mailing list since it is too big.
I've gone to GitHub to take a look at the commit 753dece88d70a23b015e01674a662e683235c08f in the rust-next branch. It looks good to me, so feel free to add
to that patch.
Thanks,
Wei.
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
In reply to Miguel OjedaQuoted 10 lines · Miguel Ojeda
rust/alloc/vec/mod.rs +10
-0+/// Tries to append an element to the back of a collection. +/// +/// # Examples +/// +/// ``` +/// let mut vec = vec![1, 2]; +/// vec.try_push(3).unwrap(); +/// assert_eq!(vec, [1, 2, 3]); +/// ``` +#[inline]
rust/alloc/vec/mod.rs impl<T, A: Allocator> Vec<T, A> { · line 1763
Quoted 10 lines
rust/alloc/vec/mod.rs +10
-0+#[stable(feature = "kernel" , since = "1.0.0" )] +pub fn try_push (&mut self, value:T ) ->Result <(),TryReserveError > { +if self.len == self.buf.capacity () { + self.buf.try_reserve_for_push (self.len)?; + } +unsafe { +let end = self.as_mut_ptr ().add (self.len); + ptr::write (end, value); + self.len +=1 ; + }
Missing safety comment here?
With a safety comment added:
Quoted 2 lines
rust/alloc/vec/mod.rs +2
-0+Ok (()) + }
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
Quoted 2 lines · Wei Liu
Missing safety comment here?
The standard library does not provide safety comments for all blocks, and these are essentially copies of the infallible variations in the library, which I kept as close as possible to the original.
Thanks for taking a look!
Cheers,
Miguel
Re: [PATCH v10 08/27] rust: adapt `alloc` crate to the kernel
Quoted 8 lines · Miguel Ojeda
Quoted 2 lines · Wei Liu
Missing safety comment here?
The standard library does not provide safety comments for all blocks, and these are essentially copies of the infallible variations in the library, which I kept as close as possible to the original.
Okay, that's fine then. Feel free to keep the RB tag.
Re: [PATCH v10 10/27] rust: add `macros` crate
In reply to Miguel OjedaQuoted 10 lines · Miguel Ojeda
This crate contains all the procedural macros ("proc macros") shared by all the kernel.
Procedural macros allow to create syntax extensions. They run at compile-time and can consume as well as produce Rust syntax.
For instance, the
module!macro that is used by Rust modules is implemented here. It allows to easily declare the equivalent information to theMODULE_*macros in C modules, e.g.:
Quoted 7 lines
module! {
type: RustMinimal,
name: b"rust_minimal",
author: b"Rust for Linux Contributors",
description: b"Rust minimal sample",
license: b"GPL",
}
I don't use / know much of procedural macros, so I don't feel like I'm qualified to review this patch.
Just a general question: what is the house rule for adding new proc macros? They are powerful tools. I can see their value in module! because writing all that boilerplate by hand is just painful. Yet they are not straightforward to understand. It is difficult, just by looking at the macro, to fully grasp what the final code looks like (though the rsi target will help). Is there a concern that proc macro gets abused?
Thanks,
Wei.
Quoted 3 lines · Wei Liu
I cannot find this patch in my inbox. That's probably filtered out by the mailing list since it is too big.
The patch reached lore in case you want to double-check:
https://lore.kernel.org/lkml/[email protected]/
I am Cc'ing [email protected] as suggested by Konstantin to reduce the chance of problems, though I wouldn't expect to have issues now since it is fairly smaller than v8 where we hit the issue.
Cheers,
Miguel
Quoted 9 lines · Miguel Ojeda
Quoted 3 lines · Wei Liu
I cannot find this patch in my inbox. That's probably filtered out by the mailing list since it is too big.
The patch reached lore in case you want to double-check:
https://lore.kernel.org/lkml/[email protected]/
I eyeballed it. Looks like it is the same one on GitHub.
Re: [PATCH v10 10/27] rust: add `macros` crate
In reply to Wei LiuQuoted 7 lines · Wei Liu
Just a general question: what is the house rule for adding new proc macros? They are powerful tools. I can see their value in
module!because writing all that boilerplate by hand is just painful. Yet they are not straightforward to understand. It is difficult, just by looking at the macro, to fully grasp what the final code looks like (though the rsi target will help). Is there a concern that proc macro gets abused?
The rule is "use them as last resort". That is, they are not banned, but they need to be justified: if there is an alternative that is not too bad (e.g. in terms of ergonomics or implementation), then the alternative should be used instead.
Nevertheless, sometimes they are very handy. Apart from module! here, we are currently using them in the full repo for vtables [1] and the Asahi M1 GPU driver is using them for versioning [2].
It is also possible to make proc macros easier to handle, for instance if we end up deciding to allow utilities like the syn crate.
[1] https://github.com/Rust-for-Linux/linux/blob/fcad53ca9071c7bf6a412640a82e679bad6d1cd4/rust/macros/lib.rs#L99-L148
[2] https://github.com/AsahiLinux/linux/blob/3c8982e2c78c219bf96761445c8b73c2b3034fba/drivers/gpu/drm/asahi/fw/buffer.rs#L43-L56
Cheers,
Miguel
Re: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Wei LiuQuoted 3 lines · Wei Liu
I do wonder how many more things you will need to list here. As far as I can tell there is also other avx512* flags for the
x86_64target.
Yeah, there are a lot of target features, but they are not getting enabled.
Eventually, a stable target spec alternative (e.g. all relevant target feature flags) should be available, and then we can know what the guaranteed behavior will be and thus decide better which flags to keep or not depending on how explicit we want to be with respect to that.
For the moment I went for consistency with the line above, since that was enough to disable everything we needed, though as you may have noticed, 3dnow and mmx are not there, because I had to move them back to the target spec [1].
[1] https://github.com/Rust-for-Linux/linux/commit/c5eae3a6e69c63dc8d69f51f74f74b853831ec71
Cheers,
Miguel
Peter Zijlstra
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Miguel OjedaQuoted 3 lines · Miguel Ojeda
Note that only
x86_64is covered and not all features nor mitigations are handled, but it is enough as a starting point and showcases the basics needed to add Rust support for a new architecture.
Does it fail the build if required options are missing? Specifically are things like kCFI and IBT enabled? Silently not handling those will result in an unbootable image.
As to missing mitigations; does it at least visibly warn people?
I'm very *very* uncomfortable having to 'support' a half-arsed compiler like this.
Sami Tolvanen
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 9 lines · Peter Zijlstra
Quoted 3 lines · Miguel Ojeda
Note that only
x86_64is covered and not all features nor mitigations are handled, but it is enough as a starting point and showcases the basics needed to add Rust support for a new architecture.Does it fail the build if required options are missing? Specifically are things like kCFI and IBT enabled? Silently not handling those will result in an unbootable image.
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
https://github.com/rust-lang/rfcs/pull/3296
Sami
Peter Zijlstra
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 7 lines · Sami Tolvanen
Quoted 6 lines · Peter Zijlstra
Quoted 3 lines · Miguel Ojeda
Note that only
x86_64is covered and not all features nor mitigations are handled, but it is enough as a starting point and showcases the basics needed to add Rust support for a new architecture.
Quoted 8 lines
Quoted 3 lines
Does it fail the build if required options are missing? Specifically are things like kCFI and IBT enabled? Silently not handling those will result in an unbootable image.
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
Right; so where does that leave us? Are we going to force disable rust when kCFI is selected ?
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 3 lines · Peter Zijlstra
Right; so where does that leave us? Are we going to force disable rust when kCFI is selected ?
Constraining it via depends on !... or similar as needed for the moment is fine, we have a few others too.
Cheers,
Miguel
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 8 lines · Miguel Ojeda
Quoted 3 lines · Peter Zijlstra
Right; so where does that leave us? Are we going to force disable rust when kCFI is selected ?
Constraining it via
depends on !...or similar as needed for the moment is fine, we have a few others too.
Right, and Peter, we actually need your help to figure out which configs are related ;-)
Regards,
Boqun
Quoted 2 lines
Cheers,
Miguel
Re: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Sami TolvanenQuoted 7 lines · Sami Tolvanen
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
I have pinged Ramon de C Valle as he is the author of the RFC above and implementation work too; since a month or so ago he also leads the Exploit Mitigations Project Group in Rust.
Cheers,
Miguel
Sami Tolvanen
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 8 lines · Miguel Ojeda
Quoted 6 lines · Sami Tolvanen
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
Quoted 5 lines
Quoted 1 line
I have pinged Ramon de C Valle as he is the author of the RFC above and implementation work too; since a month or so ago he also leads the Exploit Mitigations Project Group in Rust.
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
Sami
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 3 lines · Sami Tolvanen
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the
Ah, that is great to hear -- thanks a lot to you both! (Cc'ing Ramon)
Quoted 2 lines
meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
ACK, thanks -- if you want to send the patch, please feel free to do so.
Cheers,
Miguel
Re: [PATCH v10 04/27] kallsyms: support "big" kernel symbols
In reply to Miguel OjedaQuoted 23 lines · Miguel Ojeda
Rust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc.
Increasing to 255 is not enough in some cases, therefore introduce longer lengths to the symbol table.
In order to avoid increasing all lengths to 2 bytes (since most of them are small, including many Rust ones), use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Matthew Wilcox <[email protected]>Signed-off-by Matthew Wilcox <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Reviewed-by Greg Kroah-Hartman <[email protected]>
Quoted 5 lines
--- kernel/kallsyms.c | 26 ++++++++++++++++++++++---- scripts/kallsyms.c | 29 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-)
This patch results in the following spurious build error.
Building powerpc:allnoconfig ... failed
--------------
Error log:
Inconsistent kallsyms data
Try make KALLSYMS_EXTRA_PASS=1 as a workaround
Symbol file differences:
10c10
< 00009720 g .rodata 00000000 kallsyms_relative_base
---
Quoted 1 line
0000971cg .rodata 00000000kallsyms_relative_base
12,16c12,16
< 00009724 g .rodata 00000000 kallsyms_num_syms < 00009728 g .rodata 00000000 kallsyms_names < 00022628 g .rodata 00000000 kallsyms_markers < 000226c0 g .rodata 00000000 kallsyms_token_table < 00022a2c g .rodata 00000000 kallsyms_token_index
---
Quoted 5 lines
00009720 g .rodata 00000000 kallsyms_num_syms 00009724 g .rodata 00000000 kallsyms_names 00022618 g .rodata 00000000 kallsyms_markers 000226b0 g .rodata 00000000 kallsyms_token_table 00022a1c g .rodata 00000000 kallsyms_token_index
This is the only difference. There are no additional symbols.
Reverting this patch fixes the problem.
Guenter
Re: [PATCH v10 04/27] kallsyms: support "big" kernel symbols
Quoted 30 lines · Guenter Roeck
Quoted 23 lines · Miguel Ojeda
Rust symbols can become quite long due to namespacing introduced by modules, types, traits, generics, etc.
Increasing to 255 is not enough in some cases, therefore introduce longer lengths to the symbol table.
In order to avoid increasing all lengths to 2 bytes (since most of them are small, including many Rust ones), use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.
Reviewed-by Kees Cook <[email protected]>Co-developed-by Alex Gaynor <[email protected]>Signed-off-by Alex Gaynor <[email protected]>Co-developed-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Co-developed-by Boqun Feng <[email protected]>Signed-off-by Boqun Feng <[email protected]>Co-developed-by Matthew Wilcox <[email protected]>Signed-off-by Matthew Wilcox <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Reviewed-by Greg Kroah-Hartman <[email protected]>Quoted 5 lines
--- kernel/kallsyms.c | 26 ++++++++++++++++++++++---- scripts/kallsyms.c | 29 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-)
Quoted 7 lines
This patch results in the following spurious build error.
Building powerpc:allnoconfig ... failed
--------------
Error log:
Inconsistent kallsyms data
Try make KALLSYMS_EXTRA_PASS=1 as a workaround
I should have added: KALLSYMS_EXTRA_PASS=1 does not help.
Guenter
Quoted 24 lines
Symbol file differences:
10c10
< 00009720 g .rodata 00000000kallsyms_relative_base
---Quoted 1 line
0000971cg .rodata 00000000kallsyms_relative_base12,16c12,16
< 00009724 g .rodata 00000000 kallsyms_num_syms < 00009728 g .rodata 00000000 kallsyms_names < 00022628 g .rodata 00000000 kallsyms_markers < 000226c0 g .rodata 00000000 kallsyms_token_table < 00022a2c g .rodata 00000000 kallsyms_token_index---
Quoted 5 lines
00009720 g .rodata 00000000 kallsyms_num_syms 00009724 g .rodata 00000000 kallsyms_names 00022618 g .rodata 00000000 kallsyms_markers 000226b0 g .rodata 00000000 kallsyms_token_table 00022a1c g .rodata 00000000 kallsyms_token_indexThis is the only difference. There are no additional symbols.
Reverting this patch fixes the problem.
Guenter
Re: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Miguel OjedaI have a patchset enabling support for both KCFI and IBT in the kernel, but it uses changes not yet landed in stable rustc, which is why I haven't sent it to the list yet:
https://github.com/Rust-for-Linux/linux/pull/1034
We've backported the changes to rustc that need to be present onto the Android copy of the compiler, but it will take 6-12 weeks for them to hit stable rustc, which is what general Linux is using.
If the IBT part would be helpful by itself immediately, I can split that out - it's only the KCFI portion that won't currently work.
Quoted 15 lines · Miguel Ojeda
Quoted 3 lines · Sami Tolvanen
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the
Ah, that is great to hear -- thanks a lot to you both! (Cc'ing Ramon)
Quoted 2 lines
meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
ACK, thanks -- if you want to send the patch, please feel free to do so.
Cheers,
Miguel
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 3 lines · Matthew Maurer
If the IBT part would be helpful by itself immediately, I can split that out - it's only the KCFI portion that won't currently work.
Thanks Matthew. I don't think we are in a rush, but if it is not too much work to split it, that would be great, instead of adding the restriction.
For retthunk, by the way, I forgot to mention to Greg above that (in the original discussion with PeterZ) that I did a quick test back then to hack the equivalent of -mfunction-return=thunk-extern into rustc to show that the compiler could use it via LLVM (by passing the attribute in the IR). At least at a basic level it seemed to work:
I got a userspace program to count the times that it went through the return thunk. I didn't try to do anything on the kernel side, but at least for the compiler side, it seemed OK. So it may be way easier (on the compiler side) than the CFI work?
Cheers,
Miguel
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 9 lines · Miguel Ojeda
Quoted 3 lines · Matthew Maurer
If the IBT part would be helpful by itself immediately, I can split that out - it's only the KCFI portion that won't currently work.
Thanks Matthew. I don't think we are in a rush, but if it is not too much work to split it, that would be great, instead of adding the restriction.
Quoted 9 lines
For retthunk, by the way, I forgot to mention to Greg above that (in the original discussion with PeterZ) that I did a quick test back then to hack the equivalent of
-mfunction-return=thunk-externintorustcto show that the compiler could use it via LLVM (by passing the attribute in the IR). At least at a basic level it seemed to work:
I got a userspace program to count the times that it went through the return thunk. I didn't try to do anything on the kernel side, but at least for the compiler side, it seemed OK. So it may be way easier (on the compiler side) than the CFI work?
It should hopefully be much easier than CFI, it was a much simpler change to gcc and clang when it landed.
thanks,
greg k-h
Peter Zijlstra
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
In reply to Sami TolvanenQuoted 12 lines · Sami Tolvanen
Quoted 10 lines · Miguel Ojeda
Quoted 7 lines · Sami Tolvanen
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
Quoted 8 lines
Quoted 3 lines
I have pinged Ramon de C Valle as he is the author of the RFC above and implementation work too; since a month or so ago he also leads the Exploit Mitigations Project Group in Rust.
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
Having just read up on the thing it looks like the KCFI thing is resolved.
I'm not sure I understand most of the objections in that thread through -- enabling CFI *will* break stuff, so what.
Squashing the integer types seems a workable compromise I suppose. One thing that's been floated in the past is adding a 'seed' attribute to some functions in order to distinguish functions of otherwise identical signature.
The Rust thing would then also need to support this attribute.
Are there any concrete plans for this? It would allow, for example, to differentiate address_space_operations::swap_deactivate() from any other random function that takes only a file argument, say:locks_remove_file().
Sami Tolvanen
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 34 lines · Peter Zijlstra
Quoted 12 lines · Sami Tolvanen
Quoted 10 lines · Miguel Ojeda
Quoted 7 lines · Sami Tolvanen
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
Quoted 8 lines
Quoted 3 lines
I have pinged Ramon de C Valle as he is the author of the RFC above and implementation work too; since a month or so ago he also leads the Exploit Mitigations Project Group in Rust.
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
Having just read up on the thing it looks like the KCFI thing is resolved.
I'm not sure I understand most of the objections in that thread through -- enabling CFI *will* break stuff, so what.
Squashing the integer types seems a workable compromise I suppose. One thing that's been floated in the past is adding a 'seed' attribute to some functions in order to distinguish functions of otherwise identical signature.
Quoted 6 lines
The Rust thing would then also need to support this attribute.
Are there any concrete plans for this? It would allow, for example, to differentiate
address_space_operations::swap_deactivate()from any other random function that takes only a file argument, say:locks_remove_file().
I haven't really had time to look into it, so no concrete plans yet. Adding an attribute shouldn't be terribly difficult, but Kees expressed interest in automatic salting as well, which might be a more involved project:
https://github.com/ClangBuiltLinux/linux/issues/1736
Sami
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 42 lines · Sami Tolvanen
Quoted 34 lines · Peter Zijlstra
Quoted 12 lines · Sami Tolvanen
Quoted 10 lines · Miguel Ojeda
Quoted 7 lines · Sami Tolvanen
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
Quoted 8 lines
Quoted 3 lines
I have pinged Ramon de C Valle as he is the author of the RFC above and implementation work too; since a month or so ago he also leads the Exploit Mitigations Project Group in Rust.
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
Having just read up on the thing it looks like the KCFI thing is resolved.
I'm not sure I understand most of the objections in that thread through -- enabling CFI *will* break stuff, so what.
Squashing the integer types seems a workable compromise I suppose. One thing that's been floated in the past is adding a 'seed' attribute to some functions in order to distinguish functions of otherwise identical signature.
Quoted 6 lines
The Rust thing would then also need to support this attribute.
Are there any concrete plans for this? It would allow, for example, to differentiate
address_space_operations::swap_deactivate()from any other random function that takes only a file argument, say:locks_remove_file().
Quoted 6 lines
I haven't really had time to look into it, so no concrete plans yet. Adding an attribute shouldn't be terribly difficult, but Kees expressed interest in automatic salting as well, which might be a more involved project:
Automatic would be nice, but having an attribute would let us at least start the process manually (or apply salting from static analysis output, etc).
-Kees
Signature · 1 line
Kees Cook
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 49 lines · Kees Cook
Quoted 47 lines · Sami Tolvanen
Quoted 34 lines · Peter Zijlstra
Quoted 12 lines · Sami Tolvanen
Quoted 10 lines · Miguel Ojeda
Quoted 7 lines · Sami Tolvanen
Rust supports IBT with -Z cf-protection=branch, but I don't see this option being enabled in the kernel yet. Cross-language CFI is going to require a lot more work though because the type systems are not quite compatible:
Quoted 8 lines
Quoted 3 lines
I have pinged Ramon de C Valle as he is the author of the RFC above and implementation work too; since a month or so ago he also leads the Exploit Mitigations Project Group in Rust.
Thanks, Miguel. I also talked to Ramon about KCFI earlier this week and he expressed interest in helping with rustc support for it. In the meanwhile, I think we can just add a depends on !CFI_CLANG to avoid issues here.
Having just read up on the thing it looks like the KCFI thing is resolved.
I'm not sure I understand most of the objections in that thread through -- enabling CFI *will* break stuff, so what.
Squashing the integer types seems a workable compromise I suppose. One thing that's been floated in the past is adding a 'seed' attribute to some functions in order to distinguish functions of otherwise identical signature.
Quoted 6 lines
The Rust thing would then also need to support this attribute.
Are there any concrete plans for this? It would allow, for example, to differentiate
address_space_operations::swap_deactivate()from any other random function that takes only a file argument, say:locks_remove_file().I haven't really had time to look into it, so no concrete plans yet. Adding an attribute shouldn't be terribly difficult, but Kees expressed interest in automatic salting as well, which might be a more involved project:
Quoted 5 lines
Quoted 1 line
Automatic would be nice, but having an attribute would let us at least start the process manually (or apply salting from static analysis output, etc).
An idea would be to add something like the Rust cfi_encoding attribute[1] and use it with something similar to the Newtype Pattern[2], but in C[3], for aggregating function pointers that otherwise would be aggregated in the same group in different groups.
[1]: https://doc.rust-lang.org/nightly/unstable-book/language-features/cfi-encoding.html
[2]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#using-the-newtype-pattern-for-type-safety-and-abstraction
[3]: Wrapping a type in a struct should achieve something similar even
without using the cfi_encoding attribute since the encoding for
structs is <length><name>, where <name> is <unscoped-name>.
Peter Zijlstra
maintainerRe: [PATCH v10 25/27] x86: enable initial Rust support
In reply to a message not in the archiveQuoted 2 lines · Ramon de C Valle
[1]:
https://doc.rust-lang.org/nightly/unstable-book/language-features/cfi-encoding.html
I'm sorry, but that looks like a comment from where I'm sitting :-( Worst part is it being on a line of it's own and thus unrelated to anything.
This rust syntax is horrific..
Quoted 2 lines
I don't speak enough rust to even begin following this :/
Quoted 3 lines
[3]: Wrapping a type in a struct should achieve something similar even without using the
cfi_encodingattribute since the encoding for structs in both are <length><name>, where <name> is <unscoped-name>.
You're not talking about C, right?
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 11 lines · Peter Zijlstra
Quoted 2 lines · Ramon de C Valle
[1]:
https://doc.rust-lang.org/nightly/unstable-book/language-features/cfi-encoding.htmlI'm sorry, but that looks like a comment from where I'm sitting :-( Worst part is it being on a line of it's own and thus unrelated to anything.
This rust syntax is horrific..
I understand where you're coming from. I'm still getting used to Rust syntax.
Quoted 5 lines
Quoted 7 lines
I don't speak enough rust to even begin following this :/
Quoted 3 lines
[3]: Wrapping a type in a struct should achieve something similar even without using the
cfi_encodingattribute since the encoding for structs in both are <length><name>, where <name> is <unscoped-name>.You're not talking about C, right?
Both C and repr(C) Rust structs have this encoding, but I understand the problems with doing this in C since it doesn't have repr(transparent) structs so there would be a lot of casting back and forth. Maybe there is an alternative or this could be done for less used function pairs?
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 6 lines · Ramon de C Valle
Both C and repr(C) Rust structs have this encoding, but I understand the problems with doing this in C since it doesn't have repr(transparent) structs so there would be a lot of casting back and forth. Maybe there is an alternative or this could be done for less used function pairs?
We actually have some C variations of what I think people want to use "repr(transparent) struct" for in Rust.
Of course, that is depending on what kind of context you want to use it for, and I might have lost some background. But I'm assuming you're talking about the situation where you want to treat two or more types as being "compatible" within certain contexts.
There's the actual standard C "_Generic()" alternative, which allows you to make macros etc that use different types transparently.
It's not very widely used in the kernel, because we only fairly recently moved to require recent enough compiler versions, but we do use it now in a couple of places.
And there's the much more traditional gcc extension in the form of the __attribute__((__transparent_union__)) thing. In the kernel, that one is even less used, and that one use is likely going away since the need for it is going away.
But while it's not standard C, it's actually been supported by relevant compilers for much longer than "_Generic" has, and is designed exactly for the "I have a function that can take arguments of different types", either because the types are bitwise identical (even if _conceptually_ not the same), or simply because you have a different argument that describes the type (the traditional C union model).
I suspect, for example, that we *should* have used those transparent unions for the "this function can take either a folio or a page" case, instead of duplicating functions for the two uses.
But probably because few people aren familiar with the syntax, that's not what happened.
Linus
H. Peter Anvin
reviewerRe: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 36 lines · Linus Torvalds
Quoted 6 lines · Ramon de C Valle
Both C and repr(C) Rust structs have this encoding, but I understand the problems with doing this in C since it doesn't have repr(transparent) structs so there would be a lot of casting back and forth. Maybe there is an alternative or this could be done for less used function pairs?
We actually have some C variations of what I think people want to use "repr(transparent) struct" for in Rust.
Of course, that is depending on what kind of context you want to use it for, and I might have lost some background. But I'm assuming you're talking about the situation where you want to treat two or more types as being "compatible" within certain contexts.
There's the actual standard C "
_Generic()" alternative, which allows you to make macros etc that use different types transparently.It's not very widely used in the kernel, because we only fairly recently moved to require recent enough compiler versions, but we do use it now in a couple of places.
And there's the much more traditional gcc extension in the form of the __attribute__((__transparent_union__)) thing. In the kernel, that one is even less used, and that one use is likely going away since the need for it is going away.
But while it's not standard C, it's actually been supported by relevant compilers for much longer than "
_Generic" has, and is designed exactly for the "I have a function that can take arguments of different types", either because the types are bitwise identical (even if _conceptually_ not the same), or simply because you have a different argument that describes the type (the traditional C union model).
Quoted 8 lines
I suspect, for example, that we *should* have used those transparent unions for the "this function can take either a folio or a page" case, instead of duplicating functions for the two uses.
But probably because few people aren familiar with the syntax, that's not what happened.
Linus
Transparent unions have been standard C since C99.
Re: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 2 lines · H. Peter Anvin
Transparent unions have been standard C since C99.
Ahh, I didn't realize they made it into the standard.
In gcc, they've been usable for a lot longer (ie --std=gnu89 certainly is happy with them), but the kernel never really picked up on them.
I think they've mainly been used by glibc for a couple of functions that can take a couple of different types without complaining.
Linus
Re: [PATCH v10 25/27] x86: enable initial Rust support
In reply to H. Peter AnvinQuoted 5 lines · H. Peter Anvin
Transparent unions have been standard C since C99.
I don’t think that’s right. Certainly __attribute__((transparent_union)) is not standard C; are you referring to a different feature?
H. Peter Anvin
reviewerRe: [PATCH v10 25/27] x86: enable initial Rust support
Quoted 8 lines · comex
Quoted 5 lines · H. Peter Anvin
Transparent unions have been standard C since C99.
I don’t think that’s right. Certainly __attribute__((transparent_union)) is not standard C; are you referring to a different feature?
My mistake... I was thinking about anonymous unions.