Rust support
Subsystems (32)
Miguel Ojeda
maintainerv7 cover Rust support
Rust support
This is the patch series (v7) 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]/
This is a small round to address the comments made in v6 plus a few related changes:
- Added %pA to Documentation/core-api/printk-formats.rst.
- Added checkpatch.pl patch to search for %pA in C code.
- Added checkpatch.pl patch to enable language-independent checks.
- Added UML (x86_64) support, for KUnit (thanks David Gow!).
- Added inline licensing information ("Apache-2.0 OR MIT") in the commit message of the alloc patch, as well as in rust/alloc/README.md in the following patch.
- Added SPDX license identifiers to Documentation/rust/.
- Reformatted Documentation/rust/arch-support.rst list table into simple table.
- Removed logo from documentation patch; used Linux GIF one for the Rust generated docs in its place (to be replaced with the SVG one once available).
- Used "GPL" instead of "GPL v2" for the license field of the module! macro.
- Moved module_misc_device! macro in samples/rust/rust_random.rs to the top of the file in samples/rust/ for consistency.
- Sorted #include lists in rust/kernel/bindings_helper.h and rust/helpers.c.
- Fixed some English typos.
- Made the patches more checkpatch.pl-clean overall.
- Picked up Reviewed-by and Acked-by tags.
## 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 has just arrived in linux-next, as usual. Similarly, the preview docs for this series can be seen at:
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:
https://github.com/Rust-for-Linux/linux/issues/2
## Conferences, meetings and liaisons
We would like to remind everyone about the Rust MC (microconference) of LPC 2022 (Linux Plumbers Conference):
https://lpc.events/event/16/contributions/1159/
The Rust MC intends to cover talks and discussions on both Rust for Linux as well as other non-kernel Rust topics. The Call for Proposals is open!
## 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 for his reviews of some of the v6 patches.
- David Gow and Brendan Higgins for their reviews of the KUnit prerequisite patch and their feedback.
- Jonathan Corbet and Akira Yokosawa for their review of the documentation patch and feedback on documentation rules.
- Gary Guo for working on improvements to the Rust compiler that could make our static_assert! macro applicable in more cases.
- bjorn3 for working on making rustc_parse_format compile on a stable Rust compiler so that it may be used by lightweight formatting systems (for instance, by the kernel).
- As usual, bjorn3 and Gary Guo for all the input on Rust compiler details, reviews and suggestions.
- Esteban Blanc, Arthur Cohen and Martin Schmidt for rebasing their SPI abstraction work.
- Maciej Falkowski for continuing his work on the Samsung Exynos TRNG driver and the required abstractions around it, such as adding delay, ktime and iopoll abstractions, new methods to platform::Device and run-time power management abstractions.
- Yuheng Su for working on cleaning up the Module::init interface.
- Peng Hao for working on wrapping mm_struct.
- Sergio González Collado for continuing his work on the GitHub CI problem matchers.
- 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 GCC Rust.
- Antoni Boucher (and his supporters) et al. for their ongoing work on rustc_codegen_gcc.
- 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 (1):
kallsyms: avoid hardcoding the buffer size
Gary Guo (2):
rust: add build_error crate
vsprintf: add new %pA format specifier
Miguel Ojeda (18):
kallsyms: support "big" kernel symbols
kallsyms: increase maximum kernel symbol length to 512
kunit: take kunit_assert as const
rust: add C helpers
rust: add compiler_builtins crate
rust: import upstream alloc crate
rust: adapt alloc crate to the kernel
rust: add macros crate
rust: export generated symbols
scripts: checkpatch: diagnose uses of %pA in the C side
scripts: checkpatch: enable language-independent checks for Rust
scripts: add rustdoc_test_{builder,gen}.py scripts
scripts: add generate_rust_analyzer.py scripts
scripts: decode_stacktrace: demangle Rust symbols
docs: add Rust documentation
Kbuild: add Rust support
samples: add Rust examples
MAINTAINERS: Rust
Wedson Almeida Filho (4):
rust: add kernel crate's sync module
rust: add kernel crate
[RFC] drivers: gpio: PrimeCell PL061 in Rust
[RFC] drivers: android: Binder IPC in Rust
.gitignore | 5 + .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 | 25 + Documentation/rust/coding-guidelines.rst | 216 ++ Documentation/rust/general-information.rst | 79 + Documentation/rust/index.rst | 22 + Documentation/rust/quick-start.rst | 232 ++ MAINTAINERS | 15 + Makefile | 175 +- arch/Kconfig | 6 + arch/arm/Kconfig | 1 + arch/arm64/Kconfig | 1 + arch/powerpc/Kconfig | 1 + arch/riscv/Kconfig | 1 + arch/riscv/Makefile | 5 + arch/um/Kconfig | 1 + arch/x86/Kconfig | 1 + arch/x86/Makefile | 14 + drivers/android/Kconfig | 6 + drivers/android/Makefile | 2 + drivers/android/allocation.rs | 266 ++ drivers/android/context.rs | 80 + drivers/android/defs.rs | 99 + drivers/android/node.rs | 476 +++ drivers/android/process.rs | 960 +++++ drivers/android/range_alloc.rs | 189 + drivers/android/rust_binder.rs | 111 + drivers/android/thread.rs | 870 +++++ drivers/android/transaction.rs | 326 ++ drivers/gpio/Kconfig | 8 + drivers/gpio/Makefile | 1 + drivers/gpio/gpio_pl061_rust.rs | 370 ++ include/kunit/test.h | 2 +- include/linux/kallsyms.h | 2 +- include/linux/spinlock.h | 25 +- include/uapi/linux/android/binder.h | 28 +- init/Kconfig | 45 +- kernel/kallsyms.c | 26 +- kernel/livepatch/core.c | 4 +- lib/Kconfig.debug | 155 + lib/kunit/test.c | 4 +- lib/vsprintf.c | 13 + rust/.gitignore | 10 + rust/Makefile | 398 +++ rust/alloc/README.md | 33 + rust/alloc/alloc.rs | 438 +++ rust/alloc/borrow.rs | 498 +++ rust/alloc/boxed.rs | 2007 +++++++++++ rust/alloc/collections/mod.rs | 156 + rust/alloc/fmt.rs | 601 ++++ rust/alloc/lib.rs | 226 ++ rust/alloc/macros.rs | 127 + rust/alloc/raw_vec.rs | 567 +++ rust/alloc/slice.rs | 1282 +++++++ rust/alloc/str.rs | 632 ++++ rust/alloc/string.rs | 2869 +++++++++++++++ rust/alloc/vec/drain.rs | 186 + rust/alloc/vec/drain_filter.rs | 145 + rust/alloc/vec/into_iter.rs | 356 ++ rust/alloc/vec/is_zero.rs | 106 + rust/alloc/vec/mod.rs | 3362 ++++++++++++++++++ rust/alloc/vec/partial_eq.rs | 49 + rust/alloc/vec/set_len_on_drop.rs | 30 + rust/alloc/vec/spec_extend.rs | 174 + rust/bindgen_parameters | 17 + rust/build_error.rs | 29 + rust/compiler_builtins.rs | 57 + rust/exports.c | 20 + rust/helpers.c | 644 ++++ rust/kernel/allocator.rs | 65 + rust/kernel/amba.rs | 257 ++ rust/kernel/bindings.rs | 47 + rust/kernel/bindings_helper.h | 46 + rust/kernel/build_assert.rs | 82 + rust/kernel/c_types.rs | 119 + rust/kernel/chrdev.rs | 207 ++ rust/kernel/clk.rs | 79 + rust/kernel/cred.rs | 46 + rust/kernel/device.rs | 546 +++ rust/kernel/driver.rs | 442 +++ rust/kernel/error.rs | 565 +++ rust/kernel/file.rs | 860 +++++ rust/kernel/gpio.rs | 478 +++ rust/kernel/hwrng.rs | 242 ++ rust/kernel/io_buffer.rs | 153 + rust/kernel/io_mem.rs | 275 ++ rust/kernel/iov_iter.rs | 81 + rust/kernel/irq.rs | 411 +++ rust/kernel/kasync.rs | 6 + rust/kernel/kasync/net.rs | 322 ++ rust/kernel/kunit.rs | 91 + rust/kernel/lib.rs | 261 ++ rust/kernel/linked_list.rs | 247 ++ rust/kernel/miscdev.rs | 291 ++ rust/kernel/mm.rs | 149 + rust/kernel/module_param.rs | 498 +++ rust/kernel/net.rs | 392 ++ rust/kernel/net/filter.rs | 447 +++ rust/kernel/of.rs | 63 + rust/kernel/pages.rs | 144 + rust/kernel/platform.rs | 223 ++ rust/kernel/power.rs | 118 + rust/kernel/prelude.rs | 36 + rust/kernel/print.rs | 405 +++ rust/kernel/random.rs | 42 + rust/kernel/raw_list.rs | 361 ++ rust/kernel/rbtree.rs | 563 +++ rust/kernel/revocable.rs | 161 + rust/kernel/security.rs | 38 + rust/kernel/static_assert.rs | 38 + rust/kernel/std_vendor.rs | 160 + rust/kernel/str.rs | 597 ++++ rust/kernel/sync.rs | 161 + rust/kernel/sync/arc.rs | 503 +++ rust/kernel/sync/condvar.rs | 138 + rust/kernel/sync/guard.rs | 169 + rust/kernel/sync/locked_by.rs | 111 + rust/kernel/sync/mutex.rs | 153 + rust/kernel/sync/nowait.rs | 188 + rust/kernel/sync/revocable.rs | 250 ++ rust/kernel/sync/rwsem.rs | 197 + rust/kernel/sync/seqlock.rs | 202 ++ rust/kernel/sync/smutex.rs | 295 ++ rust/kernel/sync/spinlock.rs | 360 ++ rust/kernel/sysctl.rs | 199 ++ rust/kernel/task.rs | 175 + rust/kernel/types.rs | 679 ++++ rust/kernel/user_ptr.rs | 175 + rust/macros/helpers.rs | 79 + rust/macros/lib.rs | 94 + rust/macros/module.rs | 631 ++++ samples/Kconfig | 2 + samples/Makefile | 1 + samples/rust/Kconfig | 140 + samples/rust/Makefile | 16 + 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_chrdev.rs | 50 + samples/rust/rust_minimal.rs | 35 + samples/rust/rust_miscdev.rs | 143 + samples/rust/rust_module_parameters.rs | 69 + samples/rust/rust_netfilter.rs | 54 + samples/rust/rust_platform.rs | 22 + samples/rust/rust_print.rs | 54 + samples/rust/rust_random.rs | 60 + samples/rust/rust_semaphore.rs | 171 + samples/rust/rust_semaphore_c.c | 212 ++ samples/rust/rust_stack_probing.rs | 36 + samples/rust/rust_sync.rs | 93 + scripts/.gitignore | 1 + scripts/Kconfig.include | 6 +- scripts/Makefile | 3 + scripts/Makefile.build | 60 + scripts/Makefile.debug | 10 + scripts/Makefile.host | 34 +- scripts/Makefile.lib | 12 + scripts/Makefile.modfinal | 8 +- scripts/cc-version.sh | 12 +- scripts/checkpatch.pl | 8 +- scripts/decode_stacktrace.sh | 14 + scripts/generate_rust_analyzer.py | 134 + scripts/generate_rust_target.rs | 227 ++ scripts/is_rust_module.sh | 13 + scripts/kallsyms.c | 47 +- scripts/kconfig/confdata.c | 75 + scripts/min-tool-version.sh | 6 + scripts/rust-is-available-bindgen-libclang.h | 2 + scripts/rust-is-available.sh | 158 + scripts/rustdoc_test_builder.py | 59 + scripts/rustdoc_test_gen.py | 164 + tools/include/linux/kallsyms.h | 2 +- tools/lib/perf/include/perf/event.h | 2 +- tools/lib/symbol/kallsyms.h | 2 +- 182 files changed, 37614 insertions(+), 69 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 drivers/android/allocation.rs create mode 100644 drivers/android/context.rs create mode 100644 drivers/android/defs.rs create mode 100644 drivers/android/node.rs create mode 100644 drivers/android/process.rs create mode 100644 drivers/android/range_alloc.rs create mode 100644 drivers/android/rust_binder.rs create mode 100644 drivers/android/thread.rs create mode 100644 drivers/android/transaction.rs create mode 100644 drivers/gpio/gpio_pl061_rust.rs 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/fmt.rs create mode 100644 rust/alloc/lib.rs create mode 100644 rust/alloc/macros.rs create mode 100644 rust/alloc/raw_vec.rs create mode 100644 rust/alloc/slice.rs create mode 100644 rust/alloc/str.rs create mode 100644 rust/alloc/string.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/alloc/vec/set_len_on_drop.rs create mode 100644 rust/alloc/vec/spec_extend.rs create mode 100644 rust/bindgen_parameters create mode 100644 rust/build_error.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/amba.rs create mode 100644 rust/kernel/bindings.rs create mode 100644 rust/kernel/bindings_helper.h create mode 100644 rust/kernel/build_assert.rs create mode 100644 rust/kernel/c_types.rs create mode 100644 rust/kernel/chrdev.rs create mode 100644 rust/kernel/clk.rs create mode 100644 rust/kernel/cred.rs create mode 100644 rust/kernel/device.rs create mode 100644 rust/kernel/driver.rs create mode 100644 rust/kernel/error.rs create mode 100644 rust/kernel/file.rs create mode 100644 rust/kernel/gpio.rs create mode 100644 rust/kernel/hwrng.rs create mode 100644 rust/kernel/io_buffer.rs create mode 100644 rust/kernel/io_mem.rs create mode 100644 rust/kernel/iov_iter.rs create mode 100644 rust/kernel/irq.rs create mode 100644 rust/kernel/kasync.rs create mode 100644 rust/kernel/kasync/net.rs create mode 100644 rust/kernel/kunit.rs create mode 100644 rust/kernel/lib.rs create mode 100644 rust/kernel/linked_list.rs create mode 100644 rust/kernel/miscdev.rs create mode 100644 rust/kernel/mm.rs create mode 100644 rust/kernel/module_param.rs create mode 100644 rust/kernel/net.rs create mode 100644 rust/kernel/net/filter.rs create mode 100644 rust/kernel/of.rs create mode 100644 rust/kernel/pages.rs create mode 100644 rust/kernel/platform.rs create mode 100644 rust/kernel/power.rs create mode 100644 rust/kernel/prelude.rs create mode 100644 rust/kernel/print.rs create mode 100644 rust/kernel/random.rs create mode 100644 rust/kernel/raw_list.rs create mode 100644 rust/kernel/rbtree.rs create mode 100644 rust/kernel/revocable.rs create mode 100644 rust/kernel/security.rs create mode 100644 rust/kernel/static_assert.rs create mode 100644 rust/kernel/std_vendor.rs create mode 100644 rust/kernel/str.rs create mode 100644 rust/kernel/sync.rs create mode 100644 rust/kernel/sync/arc.rs create mode 100644 rust/kernel/sync/condvar.rs create mode 100644 rust/kernel/sync/guard.rs create mode 100644 rust/kernel/sync/locked_by.rs create mode 100644 rust/kernel/sync/mutex.rs create mode 100644 rust/kernel/sync/nowait.rs create mode 100644 rust/kernel/sync/revocable.rs create mode 100644 rust/kernel/sync/rwsem.rs create mode 100644 rust/kernel/sync/seqlock.rs create mode 100644 rust/kernel/sync/smutex.rs create mode 100644 rust/kernel/sync/spinlock.rs create mode 100644 rust/kernel/sysctl.rs create mode 100644 rust/kernel/task.rs create mode 100644 rust/kernel/types.rs create mode 100644 rust/kernel/user_ptr.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_chrdev.rs create mode 100644 samples/rust/rust_minimal.rs create mode 100644 samples/rust/rust_miscdev.rs create mode 100644 samples/rust/rust_module_parameters.rs create mode 100644 samples/rust/rust_netfilter.rs create mode 100644 samples/rust/rust_platform.rs create mode 100644 samples/rust/rust_print.rs create mode 100644 samples/rust/rust_random.rs create mode 100644 samples/rust/rust_semaphore.rs create mode 100644 samples/rust/rust_semaphore_c.c create mode 100644 samples/rust/rust_stack_probing.rs create mode 100644 samples/rust/rust_sync.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 100644 scripts/rust-is-available-bindgen-libclang.h create mode 100755 scripts/rust-is-available.sh create mode 100755 scripts/rustdoc_test_builder.py create mode 100755 scripts/rustdoc_test_gen.py
base-commit: 4b0986a3613c92f4ec1bdc7f60ec66fea135991f
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 21/25 Kbuild: add Rust support
Having all the new files in place, we now enable Rust support in the build system, including Kconfig entries related to Rust, the Rust configuration printer, the target specification generation script, the version detection script and a few other bits.
--- .gitignore | 5 + .rustfmt.toml | 12 + Makefile | 175 +++++++- arch/Kconfig | 6 + arch/arm/Kconfig | 1 + arch/arm64/Kconfig | 1 + arch/powerpc/Kconfig | 1 + arch/riscv/Kconfig | 1 + arch/riscv/Makefile | 5 + arch/um/Kconfig | 1 + arch/x86/Kconfig | 1 + arch/x86/Makefile | 14 + init/Kconfig | 45 ++- lib/Kconfig.debug | 155 ++++++++ rust/.gitignore | 10 + rust/Makefile | 398 +++++++++++++++++++ rust/bindgen_parameters | 17 + scripts/.gitignore | 1 + scripts/Kconfig.include | 6 +- scripts/Makefile | 3 + scripts/Makefile.build | 60 +++ scripts/Makefile.debug | 10 + scripts/Makefile.host | 34 +- scripts/Makefile.lib | 12 + scripts/Makefile.modfinal | 8 +- scripts/cc-version.sh | 12 +- scripts/generate_rust_target.rs | 227 +++++++++++ scripts/is_rust_module.sh | 13 + scripts/kconfig/confdata.c | 75 ++++ scripts/min-tool-version.sh | 6 + scripts/rust-is-available-bindgen-libclang.h | 2 + scripts/rust-is-available.sh | 158 ++++++++ 32 files changed, 1452 insertions(+), 23 deletions(-) create mode 100644 .rustfmt.toml create mode 100644 rust/.gitignore create mode 100644 rust/Makefile create mode 100644 rust/bindgen_parameters create mode 100644 scripts/generate_rust_target.rs create mode 100755 scripts/is_rust_module.sh create mode 100644 scripts/rust-is-available-bindgen-libclang.h create mode 100755 scripts/rust-is-available.sh
.gitignore +5 -0
@@ -37,6 +37,7 @@ *.o *.o.* *.patch +*.rmeta *.s *.so *.so.dbg
@@ -96,6 +97,7 @@ modules.order !.gitattributes !.gitignore !.mailmap +!.rustfmt.toml # # Generated include files
@@ -161,3 +163,6 @@ x509.genkey # Documentation toolchain sphinx_*/ + +# Rust analyzer configuration +/rust-project.json
.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
Makefile +168 -7
333 lines not on this page · raw message
arch/Kconfig +6 -0
@@ -344,6 +344,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
arch/arm/Kconfig +1 -0
@@ -116,6 +116,7 @@ config ARM select MMU_GATHER_RCU_TABLE_FREE if SMP && ARM_LPAE select HAVE_REGS_AND_STACK_ACCESS_API select HAVE_RSEQ + select HAVE_RUST if CPU_32v6 || CPU_32v6K select HAVE_STACKPROTECTOR select HAVE_SYSCALL_TRACEPOINTS select HAVE_UID16
arch/arm64/Kconfig +1 -0
@@ -198,6 +198,7 @@ config ARM64 select HAVE_FUNCTION_ARG_ACCESS_API select MMU_GATHER_RCU_TABLE_FREE select HAVE_RSEQ + select HAVE_RUST select HAVE_STACKPROTECTOR select HAVE_SYSCALL_TRACEPOINTS select HAVE_KPROBES
arch/powerpc/Kconfig +1 -0
@@ -239,6 +239,7 @@ config PPC select HAVE_REGS_AND_STACK_ACCESS_API select HAVE_RELIABLE_STACKTRACE select HAVE_RSEQ + select HAVE_RUST if PPC64 && CPU_LITTLE_ENDIAN select HAVE_SETUP_PER_CPU_AREA if PPC64 select HAVE_SOFTIRQ_ON_OWN_STACK select HAVE_STACKPROTECTOR if PPC32 && $(cc-option,-mstack-protector-guard=tls -mstack-protector-guard-reg=r2)
arch/riscv/Kconfig +1 -0
@@ -101,6 +101,7 @@ config RISCV select HAVE_PERF_REGS select HAVE_PERF_USER_STACK_DUMP select HAVE_REGS_AND_STACK_ACCESS_API + select HAVE_RUST if 64BIT select HAVE_FUNCTION_ARG_ACCESS_API select HAVE_STACKPROTECTOR select HAVE_SYSCALL_TRACEPOINTS
arch/riscv/Makefile +5 -0
@@ -26,6 +26,8 @@ ifeq ($(CONFIG_ARCH_RV64I),y) KBUILD_CFLAGS += -mabi=lp64 KBUILD_AFLAGS += -mabi=lp64 + KBUILD_RUSTFLAGS += -Ctarget-cpu=generic-rv64 + KBUILD_LDFLAGS += -melf64lriscv else BITS := 32
@@ -33,6 +35,9 @@ else KBUILD_CFLAGS += -mabi=ilp32 KBUILD_AFLAGS += -mabi=ilp32 + + KBUILD_RUSTFLAGS += -Ctarget-cpu=generic-rv32 + KBUILD_LDFLAGS += -melf32lriscv endif
arch/um/Kconfig +1 -0
@@ -24,6 +24,7 @@ config UML select TRACE_IRQFLAGS_SUPPORT select TTY # Needed for line.c select HAVE_ARCH_VMAP_STACK + select HAVE_RUST if X86_64 config MMU bool
arch/x86/Kconfig +1 -0
@@ -252,6 +252,7 @@ config X86 select HAVE_STATIC_CALL_INLINE if HAVE_STACK_VALIDATION select HAVE_PREEMPT_DYNAMIC_CALL select HAVE_RSEQ + select HAVE_RUST if X86_64 select HAVE_SYSCALL_TRACEPOINTS select HAVE_UNSTABLE_SCHED_CLOCK select HAVE_USER_RETURN_NOTIFIER
arch/x86/Makefile +14 -0
@@ -21,6 +21,8 @@ ifdef CONFIG_CC_IS_CLANG RETPOLINE_CFLAGS := -mretpoline-external-thunk RETPOLINE_VDSO_CFLAGS := -mretpoline endif +RETPOLINE_RUSTFLAGS := -Ctarget-feature=+retpoline-external-thunk + export RETPOLINE_CFLAGS export RETPOLINE_VDSO_CFLAGS
@@ -61,6 +63,8 @@ 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=-mmx,-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2 +KBUILD_RUSTFLAGS += -Ctarget-feature=-3dnow,-3dnowa,-avx,-avx2,+soft-float ifeq ($(CONFIG_X86_KERNEL_IBT),y) #
@@ -148,8 +152,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 #
@@ -185,6 +198,7 @@ ifdef CONFIG_RETPOLINE ifndef CONFIG_CC_IS_CLANG KBUILD_CFLAGS += -fno-jump-tables endif + KBUILD_RUSTFLAGS += $(RETPOLINE_RUSTFLAGS) endif ifdef CONFIG_SLS
init/Kconfig +44 -1
63 lines not on this page · raw message
lib/Kconfig.debug +155 -0
161 lines not on this page · raw message
rust/.gitignore new file +10 -0
@@ -0,0 +1,10 @@ +# SPDX-License-Identifier: GPL-2.0 + +target.json +bindings_generated.rs +bindings_helpers_generated.rs +exports_*_generated.h +doctests_kernel_generated.rs +doctests_kernel_generated_kunit.c +doc/ +test/
rust/Makefile new file +398 -0
398 lines not on this page · raw message
rust/bindgen_parameters new file +17 -0
@@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0 + +--opaque-type xregs_state +--opaque-type desc_struct +--opaque-type arch_lbr_state +--opaque-type local_apic + +# `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/.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/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 +10 -0
@@ -1,4 +1,5 @@ DEBUG_CFLAGS := +DEBUG_RUSTFLAGS := ifdef CONFIG_DEBUG_INFO_SPLIT DEBUG_CFLAGS += -gsplit-dwarf
@@ -10,6 +11,12 @@ ifndef CONFIG_AS_IS_LLVM KBUILD_AFLAGS += -Wa,-gdwarf-2 endif +ifdef CONFIG_DEBUG_INFO_REDUCED +DEBUG_RUSTFLAGS += -Cdebuginfo=1 +else +DEBUG_RUSTFLAGS += -Cdebuginfo=2 +endif + ifndef CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT dwarf-version-$(CONFIG_DEBUG_INFO_DWARF4) := 4 dwarf-version-$(CONFIG_DEBUG_INFO_DWARF5) := 5
@@ -31,3 +38,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/generate_rust_target.rs new file +227 -0
227 lines not on this page · raw message
scripts/is_rust_module.sh new file +13 -0
@@ -0,0 +1,13 @@ +#!/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. +${NM} "$*" | grep -qE '^[0-9a-fA-F]+ r _R[^[:space:]]+16___IS_RUST_MODULE[^[:space:]]*$'
scripts/kconfig/confdata.c +75 -0
99 lines not on this page · raw message
scripts/min-tool-version.sh +6 -0
@@ -31,6 +31,12 @@ llvm) echo 11.0.0 fi ;; +rustc) + echo 1.60.0 + ;; +bindgen) + echo 0.56.0 + ;; *) echo "$1: unknown tool" >&2 exit 1
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__)
scripts/rust-is-available.sh new file +158 -0
158 lines not on this page · raw message
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 1/25 kallsyms: avoid hardcoding the buffer size
In reply to Miguel OjedaFrom: Boqun Feng <[email protected]>
This makes it easier to update the size later on.
Furthermore, a static assert is added to ensure both are updated when that happens. The relationship used is one that keeps the new size (512+1) close to the original buffer size (500).
---
This is a prerequisite patch, independently submitted at:
https://lore.kernel.org/lkml/[email protected]/
scripts/kallsyms.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-)
scripts/kallsyms.c +13 -3
@@ -27,8 +27,18 @@#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 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;unsigned int len;
@@ -197,15 +207,15 @@ 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,500 , in) ==NULL ) +if (rc !=EOF &&fgets (name,sizeof (name), in) ==NULL )fprintf (stderr,"Read error or end of file.\n" );return NULL ; }
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 2/25 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, and therefore we need to 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), we use ULEB128 to keep smaller symbols in 1 byte, with the rest in 2 bytes.
---
This is a prerequisite patch, independently submitted at:
https://lore.kernel.org/lkml/[email protected]/
kernel/kallsyms.c | 26 ++++++++++++++++++++++---- scripts/kallsyms.c | 29 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-)
kernel/kallsyms.c +22 -4
@@ -69,12 +69,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
@@ -127,7 +135,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,
@@ -141,8 +149,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
@@ -480,12 +480,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.36.1
Miguel Ojeda
maintainerPATCH v7 3/25 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.
---
This is a prerequisite patch, independently submitted at:
https://lore.kernel.org/lkml/[email protected]/
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,10 +30,10 @@#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. */ -#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
@@ -95,7 +95,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.36.1
Miguel Ojeda
maintainerPATCH v7 4/25 kunit: take `kunit_assert` as `const`
In reply to Miguel OjedaThe kunit_do_failed_assertion function passes its struct kunit_assert argument to kunit_fail. This one, in turn, calls its format field passing the assert again as a const pointer.
Therefore, the whole chain may be made const.
---
This is a prerequisite patch, independently submitted at:
https://lore.kernel.org/lkml/[email protected]/
include/kunit/test.h | 2 +- lib/kunit/test.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-)
include/kunit/test.h +1 -1
@@ -774,7 +774,7 @@ void __printf(2, 3) kunit_log_append(char *log, const char *fmt, ...);void kunit_do_failed_assertion (struct kunit *test,const struct kunit_loc *loc,enum kunit_assert_type type, -struct kunit_assert *assert, +const struct kunit_assert *assert,const char *fmt, ...);#define KUNIT_ASSERTION (test, assert_type, pass, assert_class,INITIALIZER , fmt, ...) do { \
lib/kunit/test.c +2 -2
@@ -241,7 +241,7 @@ static void kunit_print_string_stream(struct kunit *test, }static void kunit_fail (struct kunit *test,const struct kunit_loc *loc, -enum kunit_assert_type type,struct kunit_assert *assert, +enum kunit_assert_type type,const struct kunit_assert *assert,const struct va_format *message) {struct string_stream *stream;
@@ -281,7 +281,7 @@ static void __noreturn kunit_abort(struct kunit *test)void kunit_do_failed_assertion (struct kunit *test,const struct kunit_loc *loc,enum kunit_assert_type type, -struct kunit_assert *assert, +const struct kunit_assert *assert,const char *fmt, ...) {va_list args;
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 5/25 rust: add C helpers
In reply to Miguel OjedaThis source file contains forwarders to C macros and inlined functions.
--- rust/helpers.c | 644 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 644 insertions(+) create mode 100644 rust/helpers.c
rust/helpers.c new file +644 -0
@@ -0,0 +1,644 @@ +// 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/amba/bus.h> +#include <linux/bug.h> +#include <linux/build_bug.h> +#include <linux/clk.h> +#include <linux/errname.h> +#include <linux/gfp.h> +#include <linux/highmem.h> +#include <linux/io.h> +#include <linux/irqchip/chained_irq.h> +#include <linux/irqdomain.h> +#include <linux/irq.h> +#include <linux/mutex.h> +#include <linux/netdevice.h> +#include <linux/of_device.h> +#include <linux/platform_device.h> +#include <linux/sched/signal.h> +#include <linux/security.h> +#include <linux/skbuff.h> +#include <linux/uaccess.h> +#include <linux/uio.h> + +__noreturn void rust_helper_BUG (void ) +{ +BUG (); +} +EXPORT_SYMBOL_GPL (rust_helper_BUG); + +void rust_helper_clk_disable_unprepare (struct clk *clk) +{ +return clk_disable_unprepare (clk); +} +EXPORT_SYMBOL_GPL (rust_helper_clk_disable_unprepare); + +int rust_helper_clk_prepare_enable (struct clk *clk) +{ +return clk_prepare_enable (clk); +} +EXPORT_SYMBOL_GPL (rust_helper_clk_prepare_enable); + +unsigned long rust_helper_copy_from_user (void *to,const void __user *from,unsigned long n) +{ +return copy_from_user (to, from, n); +} +EXPORT_SYMBOL_GPL (rust_helper_copy_from_user); + +unsigned long rust_helper_copy_to_user (void __user *to,const void *from,unsigned long n) +{ +return copy_to_user (to, from, n); +} +EXPORT_SYMBOL_GPL (rust_helper_copy_to_user); + +unsigned long rust_helper_clear_user (void __user *to,unsigned long n) +{ +return clear_user (to, n); +} +EXPORT_SYMBOL_GPL (rust_helper_clear_user); + +void __iomem *rust_helper_ioremap (resource_size_t offset,unsigned long size) +{ +return ioremap (offset, size); +} +EXPORT_SYMBOL_GPL (rust_helper_ioremap); + +u8 rust_helper_readb (const volatile void __iomem *addr) +{ +return readb (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readb); + +u16 rust_helper_readw (const volatile void __iomem *addr) +{ +return readw (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readw); + +u32 rust_helper_readl (const volatile void __iomem *addr) +{ +return readl (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readl); + +#ifdef CONFIG_64BIT +u64 rust_helper_readq (const volatile void __iomem *addr) +{ +return readq (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readq); +#endif + +void rust_helper_writeb (u8 value,volatile void __iomem *addr) +{ +writeb (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writeb); + +void rust_helper_writew (u16 value,volatile void __iomem *addr) +{ +writew (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writew); + +void rust_helper_writel (u32 value,volatile void __iomem *addr) +{ +writel (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writel); + +#ifdef CONFIG_64BIT +void rust_helper_writeq (u64 value,volatile void __iomem *addr) +{ +writeq (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writeq); +#endif + +u8 rust_helper_readb_relaxed (const volatile void __iomem *addr) +{ +return readb_relaxed (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readb_relaxed); + +u16 rust_helper_readw_relaxed (const volatile void __iomem *addr) +{ +return readw_relaxed (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readw_relaxed); + +u32 rust_helper_readl_relaxed (const volatile void __iomem *addr) +{ +return readl_relaxed (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readl_relaxed); + +#ifdef CONFIG_64BIT +u64 rust_helper_readq_relaxed (const volatile void __iomem *addr) +{ +return readq_relaxed (addr); +} +EXPORT_SYMBOL_GPL (rust_helper_readq_relaxed); +#endif + +void rust_helper_writeb_relaxed (u8 value,volatile void __iomem *addr) +{ +writeb_relaxed (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writeb_relaxed); + +void rust_helper_writew_relaxed (u16 value,volatile void __iomem *addr) +{ +writew_relaxed (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writew_relaxed); + +void rust_helper_writel_relaxed (u32 value,volatile void __iomem *addr) +{ +writel_relaxed (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writel_relaxed); + +#ifdef CONFIG_64BIT +void rust_helper_writeq_relaxed (u64 value,volatile void __iomem *addr) +{ +writeq_relaxed (value, addr); +} +EXPORT_SYMBOL_GPL (rust_helper_writeq_relaxed); +#endif + +void rust_helper_memcpy_fromio (void *to,const volatile void __iomem *from,long count) +{ +memcpy_fromio (to, from, count); +} +EXPORT_SYMBOL_GPL (rust_helper_memcpy_fromio); + +void rust_helper___spin_lock_init (spinlock_t *lock,const char *name, +struct lock_class_key *key) +{ +#ifdef CONFIG_DEBUG_SPINLOCK +__spin_lock_init (lock, name, key); +#else +spin_lock_init (lock); +#endif +} +EXPORT_SYMBOL_GPL (rust_helper___spin_lock_init); + +void rust_helper_spin_lock (spinlock_t *lock) +{ +spin_lock (lock); +} +EXPORT_SYMBOL_GPL (rust_helper_spin_lock); + +void rust_helper_spin_unlock (spinlock_t *lock) +{ +spin_unlock (lock); +} +EXPORT_SYMBOL_GPL (rust_helper_spin_unlock); + +unsigned long rust_helper_spin_lock_irqsave (spinlock_t *lock) +{ +unsigned long flags; + +spin_lock_irqsave (lock, flags); + +return flags; +} +EXPORT_SYMBOL_GPL (rust_helper_spin_lock_irqsave); + +void rust_helper_spin_unlock_irqrestore (spinlock_t *lock,unsigned long flags) +{ +spin_unlock_irqrestore (lock, flags); +} +EXPORT_SYMBOL_GPL (rust_helper_spin_unlock_irqrestore); + +void rust_helper__raw_spin_lock_init (raw_spinlock_t *lock,const char *name, +struct lock_class_key *key) +{ +#ifdef CONFIG_DEBUG_SPINLOCK +_raw_spin_lock_init (lock, name, key); +#else +raw_spin_lock_init (lock); +#endif +} +EXPORT_SYMBOL_GPL (rust_helper__raw_spin_lock_init); + +void rust_helper_raw_spin_lock (raw_spinlock_t *lock) +{ +raw_spin_lock (lock); +} +EXPORT_SYMBOL_GPL (rust_helper_raw_spin_lock); + +void rust_helper_raw_spin_unlock (raw_spinlock_t *lock) +{ +raw_spin_unlock (lock); +} +EXPORT_SYMBOL_GPL (rust_helper_raw_spin_unlock); + +unsigned long rust_helper_raw_spin_lock_irqsave (raw_spinlock_t *lock) +{ +unsigned long flags; + +raw_spin_lock_irqsave (lock, flags); + +return flags; +} +EXPORT_SYMBOL_GPL (rust_helper_raw_spin_lock_irqsave); + +void rust_helper_raw_spin_unlock_irqrestore (raw_spinlock_t *lock, +unsigned long flags) +{ +raw_spin_unlock_irqrestore (lock, flags); +} +EXPORT_SYMBOL_GPL (rust_helper_raw_spin_unlock_irqrestore); + +void rust_helper_init_wait (struct wait_queue_entry *wq_entry) +{ +init_wait (wq_entry); +} +EXPORT_SYMBOL_GPL (rust_helper_init_wait); + +void rust_helper_init_waitqueue_func_entry (struct wait_queue_entry *wq_entry, +wait_queue_func_t func) +{ +init_waitqueue_func_entry (wq_entry, func); +} +EXPORT_SYMBOL_GPL (rust_helper_init_waitqueue_func_entry); + +int rust_helper_signal_pending (struct task_struct *t) +{ +return signal_pending (t); +} +EXPORT_SYMBOL_GPL (rust_helper_signal_pending); + +struct page *rust_helper_alloc_pages (gfp_t gfp_mask,unsigned int order) +{ +return alloc_pages (gfp_mask, order); +} +EXPORT_SYMBOL_GPL (rust_helper_alloc_pages); + +void *rust_helper_kmap (struct page *page) +{ +return kmap (page); +} +EXPORT_SYMBOL_GPL (rust_helper_kmap); + +void rust_helper_kunmap (struct page *page) +{ +return kunmap (page); +} +EXPORT_SYMBOL_GPL (rust_helper_kunmap); + +int rust_helper_cond_resched (void ) +{ +return cond_resched (); +} +EXPORT_SYMBOL_GPL (rust_helper_cond_resched); + +size_t rust_helper_copy_from_iter (void *addr,size_t bytes,struct iov_iter *i) +{ +return copy_from_iter (addr, bytes, i); +} +EXPORT_SYMBOL_GPL (rust_helper_copy_from_iter); + +size_t rust_helper_copy_to_iter (const void *addr,size_t bytes,struct iov_iter *i) +{ +return copy_to_iter (addr, bytes, i); +} +EXPORT_SYMBOL_GPL (rust_helper_copy_to_iter); + +bool rust_helper_IS_ERR (__force const void *ptr) +{ +return IS_ERR (ptr); +} +EXPORT_SYMBOL_GPL (rust_helper_IS_ERR); + +long rust_helper_PTR_ERR (__force const void *ptr) +{ +return PTR_ERR (ptr); +} +EXPORT_SYMBOL_GPL (rust_helper_PTR_ERR); + +const char *rust_helper_errname (int err) +{ +return errname (err); +} +EXPORT_SYMBOL_GPL (rust_helper_errname); + +void rust_helper_mutex_lock (struct mutex *lock) +{ +mutex_lock (lock); +} +EXPORT_SYMBOL_GPL (rust_helper_mutex_lock); + +void rust_helper_amba_set_drvdata (struct amba_device *dev,void *data) +{ +amba_set_drvdata (dev, data); +} +EXPORT_SYMBOL_GPL (rust_helper_amba_set_drvdata); + +void *rust_helper_amba_get_drvdata (struct amba_device *dev) +{ +return amba_get_drvdata (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_amba_get_drvdata); + +void * +rust_helper_platform_get_drvdata (const struct platform_device *pdev) +{ +return platform_get_drvdata (pdev); +} +EXPORT_SYMBOL_GPL (rust_helper_platform_get_drvdata); + +void +rust_helper_platform_set_drvdata (struct platform_device *pdev, +void *data) +{ +return platform_set_drvdata (pdev, data); +} +EXPORT_SYMBOL_GPL (rust_helper_platform_set_drvdata); + +refcount_t rust_helper_REFCOUNT_INIT (int n) +{ +return (refcount_t )REFCOUNT_INIT (n); +} +EXPORT_SYMBOL_GPL (rust_helper_REFCOUNT_INIT); + +void rust_helper_refcount_inc (refcount_t *r) +{ +refcount_inc (r); +} +EXPORT_SYMBOL_GPL (rust_helper_refcount_inc); + +bool rust_helper_refcount_dec_and_test (refcount_t *r) +{ +return refcount_dec_and_test (r); +} +EXPORT_SYMBOL_GPL (rust_helper_refcount_dec_and_test); + +void rust_helper_rb_link_node (struct rb_node *node,struct rb_node *parent, +struct rb_node **rb_link) +{ +rb_link_node (node, parent, rb_link); +} +EXPORT_SYMBOL_GPL (rust_helper_rb_link_node); + +struct task_struct *rust_helper_get_current (void ) +{ +return current; +} +EXPORT_SYMBOL_GPL (rust_helper_get_current); + +void rust_helper_get_task_struct (struct task_struct *t) +{ +get_task_struct (t); +} +EXPORT_SYMBOL_GPL (rust_helper_get_task_struct); + +void rust_helper_put_task_struct (struct task_struct *t) +{ +put_task_struct (t); +} +EXPORT_SYMBOL_GPL (rust_helper_put_task_struct); + +int rust_helper_security_binder_set_context_mgr (const struct cred *mgr) +{ +return security_binder_set_context_mgr (mgr); +} +EXPORT_SYMBOL_GPL (rust_helper_security_binder_set_context_mgr); + +int rust_helper_security_binder_transaction (const struct cred *from, +const struct cred *to) +{ +return security_binder_transaction (from, to); +} +EXPORT_SYMBOL_GPL (rust_helper_security_binder_transaction); + +int rust_helper_security_binder_transfer_binder (const struct cred *from, +const struct cred *to) +{ +return security_binder_transfer_binder (from, to); +} +EXPORT_SYMBOL_GPL (rust_helper_security_binder_transfer_binder); + +int rust_helper_security_binder_transfer_file (const struct cred *from, +const struct cred *to, +struct file *file) +{ +return security_binder_transfer_file (from, to, file); +} +EXPORT_SYMBOL_GPL (rust_helper_security_binder_transfer_file); + +struct file *rust_helper_get_file (struct file *f) +{ +return get_file (f); +} +EXPORT_SYMBOL_GPL (rust_helper_get_file); + +void rust_helper_rcu_read_lock (void ) +{ +rcu_read_lock (); +} +EXPORT_SYMBOL_GPL (rust_helper_rcu_read_lock); + +void rust_helper_rcu_read_unlock (void ) +{ +rcu_read_unlock (); +} +EXPORT_SYMBOL_GPL (rust_helper_rcu_read_unlock); + +void rust_helper_synchronize_rcu (void ) +{ +synchronize_rcu (); +} +EXPORT_SYMBOL_GPL (rust_helper_synchronize_rcu); + +void *rust_helper_dev_get_drvdata (struct device *dev) +{ +return dev_get_drvdata (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_dev_get_drvdata); + +const char *rust_helper_dev_name (const struct device *dev) +{ +return dev_name (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_dev_name); + +void rust_helper___seqcount_init (seqcount_t *s,const char *name, +struct lock_class_key *key) +{ +__seqcount_init (s, name, key); +} +EXPORT_SYMBOL_GPL (rust_helper___seqcount_init); + +unsigned rust_helper_read_seqcount_begin (seqcount_t *s) +{ +return read_seqcount_begin (s); +} +EXPORT_SYMBOL_GPL (rust_helper_read_seqcount_begin); + +int rust_helper_read_seqcount_retry (seqcount_t *s,unsigned start) +{ +return read_seqcount_retry (s, start); +} +EXPORT_SYMBOL_GPL (rust_helper_read_seqcount_retry); + +void rust_helper_write_seqcount_begin (seqcount_t *s) +{ +do_write_seqcount_begin (s); +} +EXPORT_SYMBOL_GPL (rust_helper_write_seqcount_begin); + +void rust_helper_write_seqcount_end (seqcount_t *s) +{ +do_write_seqcount_end (s); +} +EXPORT_SYMBOL_GPL (rust_helper_write_seqcount_end); + +void rust_helper_irq_set_handler_locked (struct irq_data *data, +irq_flow_handler_t handler) +{ +irq_set_handler_locked (data, handler); +} +EXPORT_SYMBOL_GPL (rust_helper_irq_set_handler_locked); + +void *rust_helper_irq_data_get_irq_chip_data (struct irq_data *d) +{ +return irq_data_get_irq_chip_data (d); +} +EXPORT_SYMBOL_GPL (rust_helper_irq_data_get_irq_chip_data); + +struct irq_chip *rust_helper_irq_desc_get_chip (struct irq_desc *desc) +{ +return irq_desc_get_chip (desc); +} +EXPORT_SYMBOL_GPL (rust_helper_irq_desc_get_chip); + +void *rust_helper_irq_desc_get_handler_data (struct irq_desc *desc) +{ +return irq_desc_get_handler_data (desc); +} +EXPORT_SYMBOL_GPL (rust_helper_irq_desc_get_handler_data); + +void rust_helper_chained_irq_enter (struct irq_chip *chip, +struct irq_desc *desc) +{ +chained_irq_enter (chip, desc); +} +EXPORT_SYMBOL_GPL (rust_helper_chained_irq_enter); + +void rust_helper_chained_irq_exit (struct irq_chip *chip, +struct irq_desc *desc) +{ +chained_irq_exit (chip, desc); +} +EXPORT_SYMBOL_GPL (rust_helper_chained_irq_exit); + +const struct cred *rust_helper_get_cred (const struct cred *cred) +{ +return get_cred (cred); +} +EXPORT_SYMBOL_GPL (rust_helper_get_cred); + +void rust_helper_put_cred (const struct cred *cred) +{ +put_cred (cred); +} +EXPORT_SYMBOL_GPL (rust_helper_put_cred); + +const struct of_device_id *rust_helper_of_match_device ( +const struct of_device_id *matches,const struct device *dev) +{ +return of_match_device (matches, dev); +} +EXPORT_SYMBOL_GPL (rust_helper_of_match_device); + +void rust_helper_init_completion (struct completion *c) +{ +init_completion (c); +} +EXPORT_SYMBOL_GPL (rust_helper_init_completion); + +struct sk_buff *rust_helper_skb_get (struct sk_buff *skb) +{ +return skb_get (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_get); + +unsigned int rust_helper_skb_headlen (const struct sk_buff *skb) +{ +return skb_headlen (skb); +} +EXPORT_SYMBOL_GPL (rust_helper_skb_headlen); + +void rust_helper_dev_hold (struct net_device *dev) +{ +return dev_hold (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_dev_hold); + +void rust_helper_dev_put (struct net_device *dev) +{ +return dev_put (dev); +} +EXPORT_SYMBOL_GPL (rust_helper_dev_put); + +struct net *rust_helper_get_net (struct net *net) +{ +return get_net (net); +} +EXPORT_SYMBOL_GPL (rust_helper_get_net); + +void rust_helper_put_net (struct net *net) +{ +return put_net (net); +} +EXPORT_SYMBOL_GPL (rust_helper_put_net); + +unsigned int rust_helper_NF_QUEUE_NR (unsigned int n) +{ +return NF_QUEUE_NR (n); +} +EXPORT_SYMBOL_GPL (rust_helper_NF_QUEUE_NR); + +/* +* 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.36.1
Miguel Ojeda
maintainerPATCH v7 6/25 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 | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 rust/compiler_builtins.rs
rust/compiler_builtins.rs new file +57 -0
@@ -0,0 +1,57 @@ +// 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! ("`i128` should not be used" , { + __ashrti3, + __muloti4, + __multi3, +}); + +define_panicking_intrinsics! ("`u128` should not be used" , { + __ashlti3, + __lshrti3, + __udivmodti4, + __udivti3, + __umodti3, +}); + +#[cfg(target_arch = "arm" )] +define_panicking_intrinsics! ("`u64` division/modulo should not be used" , { + __aeabi_uldivmod, + __mulodi4, +});
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 8/25 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 rc and sync modules via new cfgs.
- Skipping the vec! macro.
- Addding 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.
--- rust/alloc/README.md | 33 ++++ rust/alloc/alloc.rs | 2 + rust/alloc/borrow.rs | 2 + rust/alloc/boxed.rs | 2 + rust/alloc/collections/mod.rs | 2 + rust/alloc/fmt.rs | 2 + rust/alloc/lib.rs | 5 +- rust/alloc/macros.rs | 4 +- rust/alloc/raw_vec.rs | 50 ++++- rust/alloc/slice.rs | 93 ++++++++- rust/alloc/str.rs | 19 ++ rust/alloc/string.rs | 6 +- rust/alloc/vec/drain.rs | 2 + rust/alloc/vec/drain_filter.rs | 2 + rust/alloc/vec/into_iter.rs | 2 + rust/alloc/vec/is_zero.rs | 2 + rust/alloc/vec/mod.rs | 313 +++++++++++++++++++++++++++++- rust/alloc/vec/partial_eq.rs | 2 + rust/alloc/vec/set_len_on_drop.rs | 2 + rust/alloc/vec/spec_extend.rs | 87 +++++++++ 20 files changed, 623 insertions(+), 9 deletions(-) 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 +2 -0
@@ -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" )]
rust/alloc/boxed.rs +2 -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
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/fmt.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension.
rust/alloc/lib.rs +4 -1
@@ -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
@@ -204,11 +206,12 @@ mod boxed {pub mod borrow;pub mod collections;pub mod fmt; +#[cfg(not(no_rc))] pub mod rc;pub mod slice;pub mod str;pub mod string; -#[cfg(target_has_atomic = "ptr" )] +#[cfg(all(not(no_sync), target_has_atomic = "ptr" ))] pub mod sync;#[cfg(all(not(no_global_oom_handling), target_has_atomic = "ptr" ))] pub mod task;
rust/alloc/macros.rs +3 -1
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +/// Creates a [`Vec`] containing the arguments. /// /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
@@ -34,7 +36,7 @@/// be mindful of side effects. /// /// [`Vec`]: crate::vec::Vec -#[cfg(not(test))] +#[cfg(all(not(no_global_oom_handling), not(test)))] #[macro_export] #[stable(feature = "rust1" , since = "1.0.0" )] #[rustc_diagnostic_item = "vec_macro" ]
rust/alloc/raw_vec.rs +49 -1
86 lines not on this page · raw message
rust/alloc/slice.rs +92 -1
142 lines not on this page · raw message
rust/alloc/str.rs +19 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! Unicode string slices. //! //! *[See also the `str` primitive type](str).*
@@ -36,6 +38,7 @@ use core::unicode::conversions;use crate ::borrow::ToOwned ;use crate ::boxed::Box ; +use crate ::collections::TryReserveError ;use crate ::slice::{Concat ,Join ,SliceIndex };use crate ::string::String ;use crate ::vec::Vec ;
@@ -590,6 +593,22 @@ impl str {// make_ascii_lowercase() preserves the UTF-8 invariant. unsafe {String ::from_utf8_unchecked (bytes) } } + +/// Tries to create a `String`. +/// +/// # Examples +/// +/// Basic usage: +/// +/// ``` +/// let s: &str = "a"; +/// let ss: String = s.try_to_owned().unwrap(); +/// ``` +#[inline] +#[stable(feature = "kernel" , since = "1.0.0" )] +pub fn try_to_owned (&self) ->Result <String ,TryReserveError > { +unsafe {Ok (String ::from_utf8_unchecked (self.as_bytes ().try_to_vec ()?)) } + } }/// Converts a boxed slice of bytes to a boxed string slice without checking
rust/alloc/string.rs +4 -2
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +//! A UTF-8–encoded, growable string. //! //! This module contains the [`String`] type, the [`ToString`] trait for
@@ -47,8 +49,8 @@ use core::char::{decode_utf16, REPLACEMENT_CHARACTER};use core::fmt;use core::hash;#[cfg(not(no_global_oom_handling))] -use core::iter::FromIterator ; -use core::iter::{from_fn,FusedIterator }; +use core::iter::{from_fn,FromIterator }; +use core::iter::FusedIterator ;#[cfg(not(no_global_oom_handling))] use core::ops::Add ;#[cfg(not(no_global_oom_handling))]
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 +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +use crate ::alloc::{Allocator ,Global };use crate ::raw_vec::RawVec ;use core::fmt;
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 +310 -3
390 lines not on this page · raw message
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 ;
rust/alloc/vec/set_len_on_drop.rs +2 -0
@@ -1,3 +1,5 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT +// Set the length of the vec when the `SetLenOnDrop` value goes out of scope. // // The idea is: The length field in SetLenOnDrop is a local variable
rust/alloc/vec/spec_extend.rs +87 -0
128 lines not on this page · raw message
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 9/25 rust: add `build_error` crate
In reply to Miguel OjedaFrom: Gary Guo <[email protected]>
The build_error crate provides the build_error function which is then used to provide the build_error! and the build_assert! macros.
build_assert! is intended to be used when static_assert! cannot be used, e.g. when the condition refers to generic parameters or parameters of an inline function.
--- rust/build_error.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 rust/build_error.rs
rust/build_error.rs new file +29 -0
@@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Build-time error. +//! +//! This crate provides a function `build_error`, which will panic in +//! compile-time if executed in const context, and will cause a build error +//! if not executed at compile time and the optimizer does not optimise away the +//! call. +//! +//! It is used by `build_assert!` in the kernel crate, allowing checking of +//! conditions that could be checked statically, but could not be enforced in +//! Rust yet (e.g. perform some checks in const functions, but those +//! functions could still be called in the runtime). + +#![no_std] + +/// Panics if executed in const context, or triggers a build error if not. +#[inline(never)] +#[cold] +#[no_mangle] +#[track_caller] +pub const fn build_error (msg: &'staticstr ) -> ! { +panic! ("{}" , msg); +} + +#[cfg( CONFIG_RUST_BUILD_ASSERT_WARN )] +#[link_section = ".gnu.warning.build_error" ] +#[used] +static BUILD_ERROR_WARNING : [u8 ;45 ] = *b"call to build_error present after compilation" ;
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 10/25 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 | 79 ++++++ rust/macros/lib.rs | 94 ++++++ rust/macros/module.rs | 631 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 804 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 +79 -0
@@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-2.0 + +use proc_macro::{token_stream,Group ,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_literal (it: &mut token_stream::IntoIter ) ->String { +try_literal (it).expect ("Expected Literal" ) +} + +pub (crate )fn expect_group (it: &mut token_stream::IntoIter ) ->Group { +if let TokenTree ::Group (group) = it.next ().expect ("Reached end of token stream for Group" ) { + group + }else { +panic! ("Expected Group" ); + } +} + +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" ); + } +} + +pub (crate )fn get_literal (it: &mut token_stream::IntoIter , expected_name: &str ) ->String { +assert_eq! (expect_ident (it), expected_name); +assert_eq! (expect_punct (it),':' ); +let literal =expect_literal (it); +assert_eq! (expect_punct (it),',' ); + literal +} + +pub (crate )fn get_byte_string (it: &mut token_stream::IntoIter , expected_name: &str ) ->String { +assert_eq! (expect_ident (it), expected_name); +assert_eq! (expect_punct (it),':' ); +let byte_string =expect_byte_string (it); +assert_eq! (expect_punct (it),',' ); + byte_string +}
rust/macros/lib.rs new file +94 -0
94 lines not on this page · raw message
rust/macros/module.rs new file +631 -0
631 lines not on this page · raw message
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 7/25 rust: import upstream `alloc` crate
In reply to Miguel OjedaThis is a subset of the Rust standard library alloc crate, version 1.60.0, licensed under "Apache-2.0 OR MIT", from:
https://github.com/rust-lang/rust/tree/1.60.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.60.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
--- rust/alloc/alloc.rs | 436 ++++ rust/alloc/borrow.rs | 496 +++++ rust/alloc/boxed.rs | 2005 +++++++++++++++++++ rust/alloc/collections/mod.rs | 154 ++ rust/alloc/fmt.rs | 599 ++++++ rust/alloc/lib.rs | 223 +++ rust/alloc/macros.rs | 125 ++ rust/alloc/raw_vec.rs | 519 +++++ rust/alloc/slice.rs | 1191 +++++++++++ rust/alloc/str.rs | 613 ++++++ rust/alloc/string.rs | 2867 +++++++++++++++++++++++++++ rust/alloc/vec/drain.rs | 184 ++ rust/alloc/vec/drain_filter.rs | 143 ++ rust/alloc/vec/into_iter.rs | 354 ++++ rust/alloc/vec/is_zero.rs | 104 + rust/alloc/vec/mod.rs | 3055 +++++++++++++++++++++++++++++ rust/alloc/vec/partial_eq.rs | 47 + rust/alloc/vec/set_len_on_drop.rs | 28 + rust/alloc/vec/spec_extend.rs | 87 + 19 files changed, 13230 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/fmt.rs create mode 100644 rust/alloc/lib.rs create mode 100644 rust/alloc/macros.rs create mode 100644 rust/alloc/raw_vec.rs create mode 100644 rust/alloc/slice.rs create mode 100644 rust/alloc/str.rs create mode 100644 rust/alloc/string.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/alloc/vec/set_len_on_drop.rs create mode 100644 rust/alloc/vec/spec_extend.rs
rust/alloc/alloc.rs new file +436 -0
@@ -0,0 +1,436 @@ +//! 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::*; + +#[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 Drop>( + 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(any(target_os = "hermit" , 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 {} bytes failed" , size) + } + +// 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 +2005 -0
2,005 lines not on this page · raw message
rust/alloc/collections/mod.rs new file +154 -0
63 lines not on this page · raw message
rust/alloc/fmt.rs new file +599 -0
599 lines not on this page · raw message
rust/alloc/lib.rs new file +223 -0
223 lines not on this page · raw message
rust/alloc/macros.rs new file +125 -0
125 lines not on this page · raw message
rust/alloc/raw_vec.rs new file +519 -0
519 lines not on this page · raw message
rust/alloc/slice.rs new file +1191 -0
1,191 lines not on this page · raw message
rust/alloc/str.rs new file +613 -0
613 lines not on this page · raw message
rust/alloc/string.rs new file +2867 -0
2,867 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 +354 -0
354 lines not on this page · raw message
rust/alloc/vec/is_zero.rs new file +104 -0
104 lines not on this page · raw message
rust/alloc/vec/mod.rs new file +3055 -0
3,055 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
rust/alloc/vec/set_len_on_drop.rs new file +28 -0
Lines of this file are not shown. View the raw message.
rust/alloc/vec/spec_extend.rs new file +87 -0
87 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.36.1
Part of the diff is not shown here. View the raw message.
Miguel Ojeda
maintainerPATCH v7 11/25 rust: add `kernel` crate's `sync` module
In reply to Miguel OjedaFrom: Wedson Almeida Filho <[email protected]>
This module contains the kernel APIs related to synchronisation that have been ported or wrapped for usage by Rust code in the kernel and is shared by all of them.
--- include/linux/spinlock.h | 25 +- rust/kernel/sync.rs | 161 +++++++++++ rust/kernel/sync/arc.rs | 503 ++++++++++++++++++++++++++++++++++ rust/kernel/sync/condvar.rs | 138 ++++++++++ rust/kernel/sync/guard.rs | 169 ++++++++++++ rust/kernel/sync/locked_by.rs | 111 ++++++++ rust/kernel/sync/mutex.rs | 153 +++++++++++ rust/kernel/sync/nowait.rs | 188 +++++++++++++ rust/kernel/sync/revocable.rs | 250 +++++++++++++++++ rust/kernel/sync/rwsem.rs | 197 +++++++++++++ rust/kernel/sync/seqlock.rs | 202 ++++++++++++++ rust/kernel/sync/smutex.rs | 295 ++++++++++++++++++++ rust/kernel/sync/spinlock.rs | 360 ++++++++++++++++++++++++ 13 files changed, 2745 insertions(+), 7 deletions(-) create mode 100644 rust/kernel/sync.rs create mode 100644 rust/kernel/sync/arc.rs create mode 100644 rust/kernel/sync/condvar.rs create mode 100644 rust/kernel/sync/guard.rs create mode 100644 rust/kernel/sync/locked_by.rs create mode 100644 rust/kernel/sync/mutex.rs create mode 100644 rust/kernel/sync/nowait.rs create mode 100644 rust/kernel/sync/revocable.rs create mode 100644 rust/kernel/sync/rwsem.rs create mode 100644 rust/kernel/sync/seqlock.rs create mode 100644 rust/kernel/sync/smutex.rs create mode 100644 rust/kernel/sync/spinlock.rs
include/linux/spinlock.h +18 -7
@@ -99,11 +99,17 @@extern void __raw_spin_lock_init (raw_spinlock_t *lock,const char *name,struct lock_class_key *key,short inner); +static inline void _raw_spin_lock_init (raw_spinlock_t *lock,const char *name, +struct lock_class_key *key) +{ +__raw_spin_lock_init (lock, name, key,LD_WAIT_SPIN ); +} +# define raw_spin_lock_init (lock) \ do { \ static struct lock_class_key __key; \ \ - __raw_spin_lock_init((lock), #lock, &__key, LD_WAIT_SPIN); \ + _raw_spin_lock_init((lock), #lock, &__key); \ } while (0)#else
@@ -326,12 +332,17 @@ static __always_inline raw_spinlock_t *spinlock_check(spinlock_t *lock)#ifdef CONFIG_DEBUG_SPINLOCK -# define spin_lock_init (lock) \ -do { \ - static struct lock_class_key __key; \ - \ - __raw_spin_lock_init(spinlock_check(lock), \ - #lock, &__key, LD_WAIT_CONFIG); \ +static inline void __spin_lock_init (spinlock_t *lock,const char *name, +struct lock_class_key *key) +{ +__raw_spin_lock_init (spinlock_check (lock), name, key,LD_WAIT_CONFIG ); +} + +# define spin_lock_init (lock) \ +do { \ + static struct lock_class_key __key; \ + \ + __spin_lock_init(lock, #lock, &__key); \ } while (0)#else
rust/kernel/sync.rs new file +161 -0
161 lines not on this page · raw message
rust/kernel/sync/arc.rs new file +503 -0
503 lines not on this page · raw message
rust/kernel/sync/condvar.rs new file +138 -0
138 lines not on this page · raw message
rust/kernel/sync/guard.rs new file +169 -0
169 lines not on this page · raw message
rust/kernel/sync/locked_by.rs new file +111 -0
111 lines not on this page · raw message
rust/kernel/sync/mutex.rs new file +153 -0
153 lines not on this page · raw message
rust/kernel/sync/nowait.rs new file +188 -0
188 lines not on this page · raw message
rust/kernel/sync/revocable.rs new file +250 -0
250 lines not on this page · raw message
rust/kernel/sync/rwsem.rs new file +197 -0
197 lines not on this page · raw message
rust/kernel/sync/seqlock.rs new file +202 -0
202 lines not on this page · raw message
rust/kernel/sync/smutex.rs new file +295 -0
295 lines not on this page · raw message
rust/kernel/sync/spinlock.rs new file +360 -0
360 lines not on this page · raw message
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 13/25 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 | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 rust/exports.c
rust/exports.c new file +20 -0
@@ -0,0 +1,20 @@ +// 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_kernel_generated.h"
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 14/25 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
@@ -2270,6 +2270,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
@@ -2396,6 +2399,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,
@@ -2468,6 +2475,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.36.1
Miguel Ojeda
maintainerPATCH v7 15/25 scripts: checkpatch: diagnose uses of `%pA` in the C side
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'
With this change, we introduce an error message with further explanation:
ERROR: '%pA' is only intended to be used from Rust code
--- scripts/checkpatch.pl | 4 ++++ 1 file changed, 4 insertions(+)
scripts/checkpatch.pl +4 -0
@@ -6784,6 +6784,10 @@ sub process { my $stat_real = get_stat_real($linenr, $lc); my $ext_type = "Invalid"; my $use = ""; + if ($bad_specifier =~ /pA/) { + ERROR("VSPRINTF_RUST", + "'\%pA' is only intended to be used from Rust code\n" . "$here\n$stat_real\n"); + } if ($bad_specifier =~ /p[Ff]/) { $use = " - use %pS instead"; $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 16/25 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
@@ -3615,7 +3615,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 = '#';
@@ -3663,7 +3663,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.36.1
Miguel Ojeda
maintainerPATCH v7 17/25 scripts: add `rustdoc_test_{builder,gen}.py` scripts
In reply to Miguel OjedaRust documentation tests are typically examples of usage of any item (e.g. function, struct, module...). They are very convenient because they are just written alongside the documentation, e.g.:
/// Sums two numbers.
///
/// # Examples
///
/// ```
/// assert_eq!(mymod::f(10, 20), 30);
/// ```
pub fn f(a: i32, b: i32) -> i32 {
a + b
}These scripts are used to transform Rust documentation tests into KUnit tests, so that they can be run in-kernel. In turn, this allows us to run tests that use kernel APIs.
In particular, the test builder receives rustdoc-generated tests, parses them and stores the result. Then, the test generator takes the saved results and generates a KUnit suite where each original documentation test is a test case.
For the moment, this is only done for the kernel crate, but the plan is to generalize it for other crates and modules.
--- scripts/rustdoc_test_builder.py | 59 ++++++++++++ scripts/rustdoc_test_gen.py | 164 ++++++++++++++++++++++++++++++++ 2 files changed, 223 insertions(+) create mode 100755 scripts/rustdoc_test_builder.py create mode 100755 scripts/rustdoc_test_gen.py
scripts/rustdoc_test_builder.py new file +59 -0
@@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0 +"""rustdoc_test_builder - Test builder for `rustdoc`-generated tests. +""" + +import json +import pathlib +import re +import sys + +RUST_DIR = pathlib.Path("rust") +TESTS_DIR = RUST_DIR / "test" / "doctests" / "kernel" + +# `[^\s]*` removes the prefix (e.g. `_doctest_main_`) plus any +# leading path (for `O=` builds). +MAIN_RE = re.compile( + r"^" + r"fn main\(\) { " + r"#\[allow\(non_snake_case\)\] " + r"fn ([^\s]*rust_kernel_([a-zA-Z0-9_]+))\(\) {" + r"$" +) + +def main(): + found_main = False + test_header = "" + test_body = "" + for line in sys.stdin.readlines(): + main_match = MAIN_RE.match(line) + if main_match: + if found_main: + raise Exception("More than one `main` line found.") + found_main = True + function_name = main_match.group(1) + test_name = f"rust_kernel_doctest_{main_match.group(2)}" + continue + + if found_main: + test_body += line + else: + test_header += line + + if not found_main: + raise Exception("No `main` line found.") + + call_line = f"}} {function_name}() }}" + if not test_body.endswith(call_line): + raise Exception("Unexpected end of test body.") + test_body = test_body[:-len(call_line)] + + with open(TESTS_DIR / f"{test_name}.json", "w") as fd: + json.dump({ + "name": test_name, + "header": test_header, + "body": test_body, + }, fd, sort_keys=True, indent=4) + +if __name__ == "__main__": + main()
scripts/rustdoc_test_gen.py new file +164 -0
164 lines not on this page · raw message
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 12/25 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 | 65 +++ rust/kernel/amba.rs | 257 ++++++++++ rust/kernel/bindings.rs | 47 ++ rust/kernel/bindings_helper.h | 46 ++ rust/kernel/build_assert.rs | 82 ++++ rust/kernel/c_types.rs | 119 +++++ rust/kernel/chrdev.rs | 207 ++++++++ rust/kernel/clk.rs | 79 ++++ rust/kernel/cred.rs | 46 ++ rust/kernel/device.rs | 546 +++++++++++++++++++++ rust/kernel/driver.rs | 442 +++++++++++++++++ rust/kernel/error.rs | 565 ++++++++++++++++++++++ rust/kernel/file.rs | 860 ++++++++++++++++++++++++++++++++++ rust/kernel/gpio.rs | 478 +++++++++++++++++++ rust/kernel/hwrng.rs | 242 ++++++++++ rust/kernel/io_buffer.rs | 153 ++++++ rust/kernel/io_mem.rs | 275 +++++++++++ rust/kernel/iov_iter.rs | 81 ++++ rust/kernel/irq.rs | 411 ++++++++++++++++ rust/kernel/kasync.rs | 6 + rust/kernel/kasync/net.rs | 322 +++++++++++++ rust/kernel/kunit.rs | 91 ++++ rust/kernel/lib.rs | 261 +++++++++++ rust/kernel/linked_list.rs | 247 ++++++++++ rust/kernel/miscdev.rs | 291 ++++++++++++ rust/kernel/mm.rs | 149 ++++++ rust/kernel/module_param.rs | 498 ++++++++++++++++++++ rust/kernel/net.rs | 392 ++++++++++++++++ rust/kernel/net/filter.rs | 447 ++++++++++++++++++ rust/kernel/of.rs | 63 +++ rust/kernel/pages.rs | 144 ++++++ rust/kernel/platform.rs | 223 +++++++++ rust/kernel/power.rs | 118 +++++ rust/kernel/prelude.rs | 36 ++ rust/kernel/print.rs | 405 ++++++++++++++++ rust/kernel/random.rs | 42 ++ rust/kernel/raw_list.rs | 361 ++++++++++++++ rust/kernel/rbtree.rs | 563 ++++++++++++++++++++++ rust/kernel/revocable.rs | 161 +++++++ rust/kernel/security.rs | 38 ++ rust/kernel/static_assert.rs | 38 ++ rust/kernel/std_vendor.rs | 160 +++++++ rust/kernel/str.rs | 597 +++++++++++++++++++++++ rust/kernel/sysctl.rs | 199 ++++++++ rust/kernel/task.rs | 175 +++++++ rust/kernel/types.rs | 679 +++++++++++++++++++++++++++ rust/kernel/user_ptr.rs | 175 +++++++ 47 files changed, 11882 insertions(+) create mode 100644 rust/kernel/allocator.rs create mode 100644 rust/kernel/amba.rs create mode 100644 rust/kernel/bindings.rs create mode 100644 rust/kernel/bindings_helper.h create mode 100644 rust/kernel/build_assert.rs create mode 100644 rust/kernel/c_types.rs create mode 100644 rust/kernel/chrdev.rs create mode 100644 rust/kernel/clk.rs create mode 100644 rust/kernel/cred.rs create mode 100644 rust/kernel/device.rs create mode 100644 rust/kernel/driver.rs create mode 100644 rust/kernel/error.rs create mode 100644 rust/kernel/file.rs create mode 100644 rust/kernel/gpio.rs create mode 100644 rust/kernel/hwrng.rs create mode 100644 rust/kernel/io_buffer.rs create mode 100644 rust/kernel/io_mem.rs create mode 100644 rust/kernel/iov_iter.rs create mode 100644 rust/kernel/irq.rs create mode 100644 rust/kernel/kasync.rs create mode 100644 rust/kernel/kasync/net.rs create mode 100644 rust/kernel/kunit.rs create mode 100644 rust/kernel/lib.rs create mode 100644 rust/kernel/linked_list.rs create mode 100644 rust/kernel/miscdev.rs create mode 100644 rust/kernel/mm.rs create mode 100644 rust/kernel/module_param.rs create mode 100644 rust/kernel/net.rs create mode 100644 rust/kernel/net/filter.rs create mode 100644 rust/kernel/of.rs create mode 100644 rust/kernel/pages.rs create mode 100644 rust/kernel/platform.rs create mode 100644 rust/kernel/power.rs create mode 100644 rust/kernel/prelude.rs create mode 100644 rust/kernel/print.rs create mode 100644 rust/kernel/random.rs create mode 100644 rust/kernel/raw_list.rs create mode 100644 rust/kernel/rbtree.rs create mode 100644 rust/kernel/revocable.rs create mode 100644 rust/kernel/security.rs create mode 100644 rust/kernel/static_assert.rs create mode 100644 rust/kernel/std_vendor.rs create mode 100644 rust/kernel/str.rs create mode 100644 rust/kernel/sysctl.rs create mode 100644 rust/kernel/task.rs create mode 100644 rust/kernel/types.rs create mode 100644 rust/kernel/user_ptr.rs
rust/kernel/allocator.rs new file +65 -0
@@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Allocator support. + +use core::alloc::{GlobalAlloc ,Layout }; +use core::ptr; + +use crate ::bindings; +use crate ::c_types; + +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 c_types::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 c_types::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 c_types::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/amba.rs new file +257 -0
257 lines not on this page · raw message
rust/kernel/bindings.rs new file +47 -0
47 lines not on this page · raw message
rust/kernel/bindings_helper.h new file +46 -0
46 lines not on this page · raw message
rust/kernel/build_assert.rs new file +82 -0
82 lines not on this page · raw message
rust/kernel/c_types.rs new file +119 -0
119 lines not on this page · raw message
rust/kernel/chrdev.rs new file +207 -0
207 lines not on this page · raw message
rust/kernel/clk.rs new file +79 -0
79 lines not on this page · raw message
rust/kernel/cred.rs new file +46 -0
46 lines not on this page · raw message
rust/kernel/device.rs new file +546 -0
546 lines not on this page · raw message
rust/kernel/driver.rs new file +442 -0
442 lines not on this page · raw message
rust/kernel/error.rs new file +565 -0
565 lines not on this page · raw message
rust/kernel/file.rs new file +860 -0
499 lines not on this page · raw message
rust/kernel/gpio.rs new file +478 -0
478 lines not on this page · raw message
rust/kernel/hwrng.rs new file +242 -0
242 lines not on this page · raw message
rust/kernel/io_buffer.rs new file +153 -0
153 lines not on this page · raw message
rust/kernel/io_mem.rs new file +275 -0
275 lines not on this page · raw message
rust/kernel/iov_iter.rs new file +81 -0
81 lines not on this page · raw message
rust/kernel/irq.rs new file +411 -0
411 lines not on this page · raw message
rust/kernel/kasync/net.rs new file +322 -0
322 lines not on this page · raw message
rust/kernel/kunit.rs new file +91 -0
91 lines not on this page · raw message
rust/kernel/lib.rs new file +261 -0
261 lines not on this page · raw message
rust/kernel/linked_list.rs new file +247 -0
247 lines not on this page · raw message
rust/kernel/miscdev.rs new file +291 -0
291 lines not on this page · raw message
rust/kernel/mm.rs new file +149 -0
149 lines not on this page · raw message
rust/kernel/module_param.rs new file +498 -0
498 lines not on this page · raw message
rust/kernel/net.rs new file +392 -0
392 lines not on this page · raw message
rust/kernel/net/filter.rs new file +447 -0
447 lines not on this page · raw message
rust/kernel/of.rs new file +63 -0
63 lines not on this page · raw message
rust/kernel/pages.rs new file +144 -0
144 lines not on this page · raw message
rust/kernel/platform.rs new file +223 -0
223 lines not on this page · raw message
rust/kernel/power.rs new file +118 -0
118 lines not on this page · raw message
rust/kernel/print.rs new file +405 -0
405 lines not on this page · raw message
rust/kernel/random.rs new file +42 -0
42 lines not on this page · raw message
rust/kernel/raw_list.rs new file +361 -0
361 lines not on this page · raw message
rust/kernel/rbtree.rs new file +563 -0
563 lines not on this page · raw message
rust/kernel/revocable.rs new file +161 -0
161 lines not on this page · raw message
rust/kernel/std_vendor.rs new file +160 -0
160 lines not on this page · raw message
rust/kernel/str.rs new file +597 -0
597 lines not on this page · raw message
rust/kernel/sysctl.rs new file +199 -0
199 lines not on this page · raw message
rust/kernel/task.rs new file +175 -0
175 lines not on this page · raw message
rust/kernel/types.rs new file +679 -0
679 lines not on this page · raw message
rust/kernel/user_ptr.rs new file +175 -0
175 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.36.1
Part of the diff is not shown here. View the raw message.
Miguel Ojeda
maintainerPATCH v7 19/25 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.
---
I would like to use this patch for discussing the demangling topic.
The last discussion took place in v6:
https://lore.kernel.org/lkml/[email protected]/
The following discusses the different approaches we could take.
# Leave demangling to userspace
This is the easiest and less invasive approach, the one implemented by this patch.
The decode_stacktrace.sh script is already needed to map the offsets to the source code. Therefore, we could also take the chance to demangle the symbols here.
With this approach, we do not need to introduce any change in the vsprintf machinery and we minimize the risk of breaking user tools.
Note that, if we take this approach, it is likely we want to ask for a minimum version of either of the tools (since there may be users of the script that do not have recent enough toolchains).
# Demangling in kernelspace on-the-fly
That is, at backtrace print time, we demangle the Rust symbols.
The size of the code that would be needed is fairly small; around 5 KiB using the "official" library (written in Rust), e.g.:
text data bss dec hex filename
7799976 1689820 2129920 11619716 b14d84 vmlinux
7801111 1693916 2129920 11624947 b161f3 vmlinux + demanglingWe can remove a few bits from the official library, e.g. punycode support that we do not need (all our identifiers will be ASCII), but it does not make a substantial difference.
The official library performs the demangling without requiring allocations. However, of course, it will increased our stack usage and complexity, specially considering a stack dump may be requested in not ideal conditions.
Furthermore, this approach (and the ones below) likely require adding a new %p specifier (or a new modifier to existing ones) if we do not want to affect non-backtrace uses of the B/S ones. Also, it is unclear whether we should write the demangled versions in an extra, different line or replace the real symbol -- we could be breaking user tools relying on parsing backtraces (e.g. our own decode_stacktrace.sh). For instance, they could be relying on having real symbols there, or may break due to e.g. spaces.
# Demangling at compile-time
This implies having kallsyms demangle all the Rust symbols.
The size of this data is around the same order of magnitude of the non-demangled ones. However, this is notably more than the demangling code (see previous point), e.g. 120 KiB (uncompressed) in a small kernel.
This approach also brings the same concerns regarding modifying the backtrace printing (see previous point).
# Demangling at compile-time and substituting symbols by hashes
One variation of the previous alternative is avoiding the mangled names inside the kernel, by hashing them. This would avoid having to support "big symbols" and would also reduce the size of the kallsyms tables, while still allowing to link modules.
However, if we do not have the real symbols around, then we do not have the possibility of providing both the mangled and demangled versions in the backtrace, which brings us back to the issues related to breaking userspace tools. There are also other places other than backtraces using "real" symbols that users may be relying on, such as /proc/*/stack.
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"
@@ -169,6 +177,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.36.1
Miguel Ojeda
maintainerPATCH v7 18/25 scripts: add `generate_rust_analyzer.py` scripts
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.
--- scripts/generate_rust_analyzer.py | 134 ++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100755 scripts/generate_rust_analyzer.py
scripts/generate_rust_analyzer.py new file +134 -0
@@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0 +"""generate_rust_analyzer - Generates the `rust-project.json` file for `rust-analyzer`. +""" + +import argparse +import json +import logging +import pathlib +import sys + +def generate_crates(srctree, objtree, sysroot_src): + # Generate the configuration list. + cfg = [] + with open(objtree / "include" / "generated" / "rustc_cfg") as fd: + for line in fd: + line = line.replace("--cfg=", "") + line = line.replace("\n", "") + cfg.append(line) + + # Now fill the crates list -- dependencies need to come first. + # + # Avoid O(n^2) iterations by keeping a map of indexes. + crates = [] + crates_indexes = {} + + def append_crate(display_name, root_module, deps, cfg=[], is_workspace_member=True, is_proc_macro=False): + crates_indexes[display_name] = len(crates) + crates.append({ + "display_name": display_name, + "root_module": str(root_module), + "is_workspace_member": is_workspace_member, + "is_proc_macro": is_proc_macro, + "deps": [{"crate": crates_indexes[dep], "name": dep} for dep in deps], + "cfg": cfg, + "edition": "2021", + "env": { + "RUST_MODFILE": "This is only for rust-analyzer" + } + }) + + # First, the ones in `rust/` since they are a bit special. + append_crate( + "core", + sysroot_src / "core" / "src" / "lib.rs", + [], + is_workspace_member=False, + ) + + append_crate( + "compiler_builtins", + srctree / "rust" / "compiler_builtins.rs", + [], + ) + + append_crate( + "alloc", + srctree / "rust" / "alloc" / "lib.rs", + ["core", "compiler_builtins"], + ) + + append_crate( + "macros", + srctree / "rust" / "macros" / "lib.rs", + [], + is_proc_macro=True, + ) + crates[-1]["proc_macro_dylib_path"] = "rust/libmacros.so" + + append_crate( + "build_error", + srctree / "rust" / "build_error.rs", + ["core", "compiler_builtins"], + ) + + append_crate( + "kernel", + srctree / "rust" / "kernel" / "lib.rs", + ["core", "alloc", "macros", "build_error"], + cfg=cfg, + ) + crates[-1]["env"]["OBJTREE"] = str(objtree.resolve(True)) + crates[-1]["source"] = { + "include_dirs": [ + str(srctree / "rust" / "kernel"), + str(objtree / "rust") + ], + "exclude_dirs": [], + } + + # Then, the rest outside of `rust/`. + # + # We explicitly mention the top-level folders we want to cover. + for folder in ("samples", "drivers"): + for path in (srctree / folder).rglob("*.rs"): + logging.info("Checking %s", path) + name = path.name.replace(".rs", "") + + # Skip those that are not crate roots. + if f"{name}.o" not in open(path.parent / "Makefile").read(): + continue + + logging.info("Adding %s", name) + append_crate( + name, + path, + ["core", "alloc", "kernel"], + cfg=cfg, + ) + + return crates + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--verbose', '-v', action='store_true') + parser.add_argument("srctree", type=pathlib.Path) + parser.add_argument("objtree", type=pathlib.Path) + parser.add_argument("sysroot_src", type=pathlib.Path) + args = parser.parse_args() + + logging.basicConfig( + format="[%(asctime)s] [%(levelname)s] %(message)s", + level=logging.INFO if args.verbose else logging.WARNING + ) + + rust_project = { + "crates": generate_crates(args.srctree, args.objtree, args.sysroot_src), + "sysroot_src": str(args.sysroot_src), + } + + json.dump(rust_project, sys.stdout, sort_keys=True, indent=4) + +if __name__ == "__main__": + main()
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 20/25 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 an asset (SVG logo) used for the rustdoc target and 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 | 25 +++ 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, 682 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
@@ -11,6 +11,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 +25 -0
@@ -0,0 +1,25 @@ +.. 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 +============ ================ ============================================== +``arm`` Maintained ``armv6`` and compatible only, + ``RUST_OPT_LEVEL >= 2``. +``arm64`` Maintained None. +``powerpc`` Maintained ``ppc64le`` only, ``RUST_OPT_LEVEL < 2`` + requires ``CONFIG_THREAD_SHIFT=15``. +``riscv`` Maintained ``riscv64`` only. +``x86`` Maintained ``x86_64`` only. +============ ================ ==============================================
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.36.1
Miguel Ojeda
maintainerRFC PATCH v7 24/25 drivers: gpio: PrimeCell PL061 in Rust
In reply to Miguel OjedaFrom: Wedson Almeida Filho <[email protected]>
A port to Rust of the PrimeCell PL061 GPIO driver.
This module is a work in progress and will be sent for review later on, as well as separately from the Rust support.
However, it is included to show how an actual working module written in Rust may look like.
--- drivers/gpio/Kconfig | 8 + drivers/gpio/Makefile | 1 + drivers/gpio/gpio_pl061_rust.rs | 370 ++++++++++++++++++++++++++++++++ 3 files changed, 379 insertions(+) create mode 100644 drivers/gpio/gpio_pl061_rust.rs
drivers/gpio/Kconfig +8 -0
@@ -481,6 +481,14 @@ config GPIO_PL061 help Say yes here to support the PrimeCell PL061 GPIO device. +config GPIO_PL061_RUST + tristate "PrimeCell PL061 GPIO support written in Rust" + depends on ARM_AMBA && RUST + select IRQ_DOMAIN + select GPIOLIB_IRQCHIP + help + Say yes here to support the PrimeCell PL061 GPIO device + config GPIO_PMIC_EIC_SPRD tristate "Spreadtrum PMIC EIC support" depends on MFD_SC27XX_PMIC || COMPILE_TEST
drivers/gpio/Makefile +1 -0
@@ -118,6 +118,7 @@ obj-$(CONFIG_GPIO_PCIE_IDIO_24) += gpio-pcie-idio-24.o obj-$(CONFIG_GPIO_PCI_IDIO_16) += gpio-pci-idio-16.o obj-$(CONFIG_GPIO_PISOSR) += gpio-pisosr.o obj-$(CONFIG_GPIO_PL061) += gpio-pl061.o +obj-$(CONFIG_GPIO_PL061_RUST) += gpio_pl061_rust.o obj-$(CONFIG_GPIO_PMIC_EIC_SPRD) += gpio-pmic-eic-sprd.o obj-$(CONFIG_GPIO_PXA) += gpio-pxa.o obj-$(CONFIG_GPIO_RASPBERRYPI_EXP) += gpio-raspberrypi-exp.o
drivers/gpio/gpio_pl061_rust.rs new file +370 -0
370 lines not on this page · raw message
Signature · 1 line
2.36.1
Miguel Ojeda
maintainerPATCH v7 23/25 MAINTAINERS: Rust
In reply to Miguel OjedaMiguel, Alex and Wedson will be maintaining the Rust support.
--- MAINTAINERS | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
MAINTAINERS +15 -0
@@ -17149,6 +17149,21 @@ L: [email protected] S: Maintained F: drivers/infiniband/ulp/rtrs/ +RUST +M: Miguel Ojeda <[email protected]> +M: Alex Gaynor <[email protected]> +M: Wedson Almeida Filho <[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.36.1
Miguel Ojeda
maintainerRFC PATCH v7 25/25 drivers: android: Binder IPC in Rust
In reply to Miguel OjedaFrom: Wedson Almeida Filho <[email protected]>
A port to Rust of the Android Binder IPC mechanism.
This module is a work in progress and will be sent for review later on, as well as separately from the Rust support.
However, it is included to show how an actual working module written in Rust may look like.
--- drivers/android/Kconfig | 6 + drivers/android/Makefile | 2 + drivers/android/allocation.rs | 266 ++++++++ drivers/android/context.rs | 80 +++ drivers/android/defs.rs | 99 +++ drivers/android/node.rs | 476 ++++++++++++++ drivers/android/process.rs | 960 ++++++++++++++++++++++++++++ drivers/android/range_alloc.rs | 189 ++++++ drivers/android/rust_binder.rs | 111 ++++ drivers/android/thread.rs | 870 +++++++++++++++++++++++++ drivers/android/transaction.rs | 326 ++++++++++ include/uapi/linux/android/binder.h | 28 +- 12 files changed, 3400 insertions(+), 13 deletions(-) create mode 100644 drivers/android/allocation.rs create mode 100644 drivers/android/context.rs create mode 100644 drivers/android/defs.rs create mode 100644 drivers/android/node.rs create mode 100644 drivers/android/process.rs create mode 100644 drivers/android/range_alloc.rs create mode 100644 drivers/android/rust_binder.rs create mode 100644 drivers/android/thread.rs create mode 100644 drivers/android/transaction.rs
drivers/android/Kconfig +6 -0
@@ -20,6 +20,12 @@ config ANDROID_BINDER_IPC Android process, using Binder to identify, invoke and pass arguments between said processes. +config ANDROID_BINDER_IPC_RUST + bool "Android Binder IPC Driver in Rust" + depends on MMU && RUST + help + Implementation of the Binder IPC in Rust. + config ANDROID_BINDERFS bool "Android Binderfs filesystem" depends on ANDROID_BINDER_IPC
drivers/android/Makefile +2 -0
@@ -4,3 +4,5 @@ ccflags-y += -I$(src) # needed for trace events obj-$(CONFIG_ANDROID_BINDERFS) += binderfs.o obj-$(CONFIG_ANDROID_BINDER_IPC) += binder.o binder_alloc.o obj-$(CONFIG_ANDROID_BINDER_IPC_SELFTEST) += binder_alloc_selftest.o + +obj-$(CONFIG_ANDROID_BINDER_IPC_RUST) += rust_binder.o
drivers/android/allocation.rs new file +266 -0
266 lines not on this page · raw message
drivers/android/context.rs new file +80 -0
80 lines not on this page · raw message
drivers/android/defs.rs new file +99 -0
99 lines not on this page · raw message
drivers/android/node.rs new file +476 -0
476 lines not on this page · raw message
drivers/android/process.rs new file +960 -0
960 lines not on this page · raw message
drivers/android/range_alloc.rs new file +189 -0
189 lines not on this page · raw message
drivers/android/rust_binder.rs new file +111 -0
111 lines not on this page · raw message
drivers/android/thread.rs new file +870 -0
802 lines not on this page · raw message
drivers/android/transaction.rs new file +326 -0
326 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.36.1
Part of the diff is not shown here. View the raw message.
Miguel Ojeda
maintainerPATCH v7 22/25 samples: add Rust examples
In reply to Miguel OjedaA set of Rust modules that showcase how Rust modules look like and how to use the abstracted kernel features, as well as an example of a Rust host program with several modules.
These samples also double as tests in the CI.
The semaphore sample comes with a C version for comparison.
--- samples/Kconfig | 2 + samples/Makefile | 1 + samples/rust/Kconfig | 140 ++++++++++++++++ samples/rust/Makefile | 16 ++ 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_chrdev.rs | 50 ++++++ samples/rust/rust_minimal.rs | 35 ++++ samples/rust/rust_miscdev.rs | 143 +++++++++++++++++ samples/rust/rust_module_parameters.rs | 69 ++++++++ samples/rust/rust_netfilter.rs | 54 +++++++ samples/rust/rust_platform.rs | 22 +++ samples/rust/rust_print.rs | 54 +++++++ samples/rust/rust_random.rs | 60 +++++++ samples/rust/rust_semaphore.rs | 171 ++++++++++++++++++++ samples/rust/rust_semaphore_c.c | 212 +++++++++++++++++++++++++ samples/rust/rust_stack_probing.rs | 36 +++++ samples/rust/rust_sync.rs | 93 +++++++++++ 21 files changed, 1190 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_chrdev.rs create mode 100644 samples/rust/rust_minimal.rs create mode 100644 samples/rust/rust_miscdev.rs create mode 100644 samples/rust/rust_module_parameters.rs create mode 100644 samples/rust/rust_netfilter.rs create mode 100644 samples/rust/rust_platform.rs create mode 100644 samples/rust/rust_print.rs create mode 100644 samples/rust/rust_random.rs create mode 100644 samples/rust/rust_semaphore.rs create mode 100644 samples/rust/rust_semaphore_c.c create mode 100644 samples/rust/rust_stack_probing.rs create mode 100644 samples/rust/rust_sync.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 +140 -0
140 lines not on this page · raw message
samples/rust/Makefile new file +16 -0
@@ -0,0 +1,16 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o +obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o +obj-$(CONFIG_SAMPLE_RUST_MODULE_PARAMETERS) += rust_module_parameters.o +obj-$(CONFIG_SAMPLE_RUST_SYNC) += rust_sync.o +obj-$(CONFIG_SAMPLE_RUST_CHRDEV) += rust_chrdev.o +obj-$(CONFIG_SAMPLE_RUST_MISCDEV) += rust_miscdev.o +obj-$(CONFIG_SAMPLE_RUST_STACK_PROBING) += rust_stack_probing.o +obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE) += rust_semaphore.o +obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE_C) += rust_semaphore_c.o +obj-$(CONFIG_SAMPLE_RUST_RANDOM) += rust_random.o +obj-$(CONFIG_SAMPLE_RUST_PLATFORM) += rust_platform.o +obj-$(CONFIG_SAMPLE_RUST_NETFILTER) += rust_netfilter.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_chrdev.rs new file +50 -0
50 lines not on this page · raw message
samples/rust/rust_minimal.rs new file +35 -0
@@ -0,0 +1,35 @@ +// 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 { + message:String , +} + +impl kernel::Module for RustMinimal { +fn init (_name: &'staticCStr , _module: &'staticThisModule ) ->Result <Self > { +pr_info! ("Rust minimal sample (init)\n" ); +pr_info! ("Am I built-in? {}\n" , !cfg! (MODULE )); + +Ok (RustMinimal { + message:"on the heap!" .try_to_owned ()?, + }) + } +} + +impl Drop for RustMinimal { +fn drop (&mut self) { +pr_info! ("My message is {}\n" , self.message); +pr_info! ("Rust minimal sample (exit)\n" ); + } +}
samples/rust/rust_miscdev.rs new file +143 -0
143 lines not on this page · raw message
samples/rust/rust_module_parameters.rs new file +69 -0
69 lines not on this page · raw message
samples/rust/rust_netfilter.rs new file +54 -0
54 lines not on this page · raw message
samples/rust/rust_platform.rs new file +22 -0
@@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust platform device driver sample. + +use kernel::{module_platform_driver, of, platform, prelude::*}; + +module_platform_driver! { +type :Driver , +name :b"rust_platform" , + license:b"GPL" , +} + +struct Driver ; +impl platform::Driver for Driver { + kernel::define_of_id_table! {(), [ + (of::DeviceId ::Compatible (b"rust,sample" ),None ), + ]} + +fn probe (_dev: &mut platform::Device , _id_info:Option <&Self ::IdInfo >) ->Result { +Ok (()) + } +}
samples/rust/rust_print.rs new file +54 -0
54 lines not on this page · raw message
samples/rust/rust_random.rs new file +60 -0
60 lines not on this page · raw message
samples/rust/rust_semaphore.rs new file +171 -0
171 lines not on this page · raw message
samples/rust/rust_semaphore_c.c new file +212 -0
212 lines not on this page · raw message
samples/rust/rust_stack_probing.rs new file +36 -0
@@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust stack probing sample. + +use kernel::prelude::*; + +module! { +type :RustStackProbing , +name :b"rust_stack_probing" , + author:b"Rust for Linux Contributors" , + description:b"Rust stack probing sample" , + license:b"GPL" , +} + +struct RustStackProbing ; + +impl kernel::Module for RustStackProbing { +fn init (_name: &'staticCStr , _module: &'staticThisModule ) ->Result <Self > { +pr_info! ("Rust stack probing sample (init)\n" ); + +// Including this large variable on the stack will trigger +// stack probing on the supported archs. +// This will verify that stack probing does not lead to +// any errors if we need to link `__rust_probestack`. +let x: [u64 ;514 ] = core::hint::black_box ([5 ;514 ]); +pr_info! ("Large array has length: {}\n" , x.len ()); + +Ok (RustStackProbing ) + } +} + +impl Drop for RustStackProbing { +fn drop (&mut self) { +pr_info! ("Rust stack probing sample (exit)\n" ); + } +}
samples/rust/rust_sync.rs new file +93 -0
93 lines not on this page · raw message
Signature · 1 line
2.36.1
Joe Perches
maintainerRe: [PATCH v7 15/25] scripts: checkpatch: diagnose uses of `%pA` in the C side
In reply to Miguel OjedaQuoted 9 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'
With this change, we introduce an error message with further explanation:
Quoted 8 lines
ERROR: '%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]>Signed-off-by Miguel Ojeda <[email protected]>
How many developers are required for a trivial patch?
scripts/checkpatch.pl
Quoted 1 line
scripts/checkpatch.pl +0
-0
[]
scripts/checkpatch.pl sub process { · line 6791
Quoted 9 lines
scripts/checkpatch.pl +4
-0@@ -6784,6 +6784,10 @@ sub process { my $stat_real = get_stat_real($linenr, $lc); my $ext_type = "Invalid"; my $use = ""; + if ($bad_specifier =~ /pA/) { + ERROR("VSPRINTF_RUST", + "'\%pA' is only intended to be used from Rust code\n" . "$here\n$stat_real\n"); + } if ($bad_specifier =~ /p[Ff]/) {
and this should now use elsif
Quoted 2 lines
scripts/checkpatch.pl +0
-0$use = " - use %pS instead"; $use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
Re: [PATCH v7 04/25] kunit: take `kunit_assert` as `const`
In reply to Miguel OjedaQuoted 8 lines · Miguel Ojeda
The
kunit_do_failed_assertionfunction passes itsstruct kunit_assertargument tokunit_fail. This one, in turn, calls itsformatfield passing the assert again as aconstpointer.Therefore, the whole chain may be made
const.
Quoted 7 lines
Reviewed-by Daniel Latypov <[email protected]>Reviewed-by Brendan Higgins <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>---
This is a prerequisite patch, independently submitted at:https://lore.kernel.org/lkml/[email protected]/
FYI, we'd asked Shuah to pick this patch up in her "kunit" branch. It's applied here:
https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git/commit/?h=kunit&id=7466886b400b1904ce30fa311904849e314a2cf4
It had previously seemed unclear if this series could make it for the 5.19 merge window (but it now looks like there's interest in trying it out early on).
Daniel
Shuah Khan
maintainerRe: [PATCH v7 04/25] kunit: take `kunit_assert` as `const`
Quoted 21 lines · Daniel Latypov
Quoted 8 lines · Miguel Ojeda
The
kunit_do_failed_assertionfunction passes itsstruct kunit_assertargument tokunit_fail. This one, in turn, calls itsformatfield passing the assert again as aconstpointer.Therefore, the whole chain may be made
const.Quoted 7 lines
Reviewed-by Daniel Latypov <[email protected]>Reviewed-by Brendan Higgins <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>---
This is a prerequisite patch, independently submitted at:https://lore.kernel.org/lkml/[email protected]/FYI, we'd asked Shuah to pick this patch up in her "kunit" branch. It's applied here:
https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git/commit/?h=kunit&id=7466886b400b1904ce30fa311904849e314a2cf4
Quoted 6 lines
It had previously seemed unclear if this series could make it for the 5.19 merge window (but it now looks like there's interest in trying it out early on).
Daniel
I am just about send pull request with this patch included.
thanks,
-- Shuah
Re: [PATCH v7 21/25] Kbuild: add Rust support
In reply to Miguel OjedaQuoted 58 lines
lib/Kconfig.debug +58
-0+choice + prompt "Optimization level" + default RUST_OPT_LEVEL_SIMILAR_AS_CHOSEN_FOR_C + depends on RUST + help + Controls rustc's `-Copt-level` codegen option. + + This flag controls the optimization level. + + If unsure, say "Similar as chosen for C". + +config RUST_OPT_LEVEL_SIMILAR_AS_CHOSEN_FOR_C + bool "Similar as chosen for C" + help + This choice will pick a similar optimization level as chosen in + the "Compiler optimization level" for C: + + -O2 is currently mapped to -Copt-level=2 + -O3 is currently mapped to -Copt-level=3 + -Os is currently mapped to -Copt-level=s + + The mapping may change over time to follow the intended semantics + of the choice for C as sensibly as possible. + + This is the default. + +config RUST_OPT_LEVEL_0 + bool "No optimizations (-Copt-level=0)" + help + Not recommended for most purposes. It may come in handy for debugging + suspected optimizer bugs, unexpected undefined behavior, etc. + + Note that this level will *not* enable debug assertions nor overflow + checks on its own (like it happens when interacting with rustc + directly). Use the corresponding configuration options to control + that instead, orthogonally. + + Note this level may cause excessive stack usage, which can lead to stack + overflow and subsequent crashes. + +config RUST_OPT_LEVEL_1 + bool "Basic optimizations (-Copt-level=1)" + help + Useful for debugging without getting too lost, but without + the overhead and boilerplate of no optimizations at all. + + Note this level may cause excessive stack usage, which can lead to stack + overflow and subsequent crashes. + +config RUST_OPT_LEVEL_2 + bool "Some optimizations (-Copt-level=2)" + help + The sensible choice in most cases. + +config RUST_OPT_LEVEL_3 + bool "All optimizations (-Copt-level=3)" + help + Yet more performance (hopefully).
lib/Kconfig.debug config HYPERV_TESTING · line 2862
Quoted 10 lines
lib/Kconfig.debug +10
-0+ +config RUST_OPT_LEVEL_S + bool "Optimize for size (-Copt-level=s)" + help + Smaller kernel, ideally without too much performance loss. + +config RUST_OPT_LEVEL_Z + bool "Optimize for size, no loop vectorization (-Copt-level=z)" + help + Like the previous level, but also turn off loop vectorization.
I'm super not into having the rust optimization level differ from the C optimization level. This is just someone having too much fun wrapping every compiler flag in a kbuild option. Either folks wan't smaller size or more optimizations. Allowing for RUST_OPT_LEVEL_S and CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE or RUST_OPT_LEVEL_3 and CONFIG_CC_OPTIMIZE_FOR_SIZE is just wacky nonsense that's going to make randconfig bug reports more confusing to tease out.
Signature · 7 lines
Thanks, ~Nick Desaulniers _______________________________________________ linux-um mailing list [email protected] http://lists.infradead.org/mailman/listinfo/linux-um
Re: [PATCH v7 06/25] rust: add `compiler_builtins` crate
In reply to Miguel OjedaQuoted 27 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.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]>--- rust/compiler_builtins.rs | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 rust/compiler_builtins.rsrust/compiler_builtins.rs new file +2
-0@@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-2.0 +
rust/compiler_builtins.rs line 12
Quoted 10 lines
rust/compiler_builtins.rs new file +10
-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
^ Any progress on this? Got any links to any feature requests or bug reports.
Also, I'm not sure my concern about explicit build failures for C code was ever addressed? We have a constant problem with long long division on ARCH=arm32 and ARCH=i386 in C code.
https://lore.kernel.org/lkml/CAKwvOdk+A2PBdjSFVUhj4xyCGCKujtej1uPgywQgrKPiK2ksPw@mail.gmail.com/
Quoted 48 lines
rust/compiler_builtins.rs new file +45
-1+//! 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! ("`i128` should not be used" , { + __ashrti3, + __muloti4, + __multi3, +}); + +define_panicking_intrinsics! ("`u128` should not be used" , { + __ashlti3, + __lshrti3, + __udivmodti4, + __udivti3, + __umodti3, +}); + +#[cfg(target_arch = "arm" )] +define_panicking_intrinsics! ("`u64` division/modulo should not be used" , { + __aeabi_uldivmod, + __mulodi4, +}); --2.36.1
Signature · 2 lines
Thanks, ~Nick Desaulniers
Re: [PATCH v7 01/25] kallsyms: avoid hardcoding the buffer size
In reply to Miguel OjedaQuoted 4 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This makes it easier to update the size later on.
This does not really conform to [1].
E.g.
"Declare KSY_NAME_LEN, which describes the maximum length for a kernel symbol read by kallsyms from the input. In read_symbol(), define the buffer to be of length "KSY_NAME_LEN + 1", which includes the terminator character."
would be better.
Quoted 3 lines
Furthermore, a static assert is added to ensure both are updated when that happens. The relationship used is one that keeps the new size (512+1) close to the original buffer size (500).
You must split this then into two patches:
1. A patch that re-defines the length with KSYM_NAME_LEN, i.e. #define KSYM_NAME_LEN 499
2. A patch which increases the size and reasoning for that.
Right now bundles two separate changes, which does not conform to [2].
BR, Jarkko
Re: [PATCH v7 01/25] kallsyms: avoid hardcoding the buffer size
Quoted 23 lines · Jarkko Sakkinen
Quoted 4 lines · Miguel Ojeda
From: Boqun Feng <[email protected]>
This makes it easier to update the size later on.
This does not really conform to [1].
E.g.
"Declare
KSY_NAME_LEN, which describes the maximum length for a kernel symbol read by kallsyms from the input. Inread_symbol(), define the buffer to be of length "KSY_NAME_LEN+ 1", which includes the terminator character."would be better.
Quoted 3 lines
Furthermore, a static assert is added to ensure both are updated when that happens. The relationship used is one that keeps the new size (512+1) close to the original buffer size (500).
You must split this then into two patches:
Quoted 7 lines
1. A patch that re-defines the length with
KSYM_NAME_LEN, i.e. #defineKSYM_NAME_LEN499
2. A patch which increases the size and reasoning for that.Right now bundles two separate changes, which does not conform to [2].
BR, Jarkko
The URL's:
[1] https://www.kernel.org/doc/html/latest/process/submitting-patches.html#describe-changes
[2] https://www.kernel.org/doc/html/latest/process/submitting-patches.html#separate-your-changes
BR, Jarkko
Re: [PATCH v7 02/25] kallsyms: support "big" kernel symbols
In reply to Miguel OjedaQuoted 5 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, and therefore we need to introduce longer lengths to the symbol table.
s/we need to//
Quoted 3 lines
In order to avoid increasing all lengths to 2 bytes (since most of them are small, including many Rust ones), we use ULEB128 to
s/we//
Quoted 125 lines
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]>---
This is a prerequisite patch, independently submitted at:https://lore.kernel.org/lkml/[email protected]/kernel/kallsyms.c | 26 ++++++++++++++++++++++---- scripts/kallsyms.c | 29 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 7 deletions(-)kernel/kallsyms.c +22
-4@@ -69,12 +69,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 @@ -127,7 +135,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, @@ -141,8 +149,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@@ -480,12 +480,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.36.1
BR, Jarkko
Re: [PATCH v7 03/25] kallsyms: increase maximum kernel symbol length to 512
In reply to Miguel OjedaQuoted 19 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 } } }
Quoted 7 lines
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.
There's no description what the patch does.
Quoted 119 lines
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]>---
This is a prerequisite patch, independently submitted at:https://lore.kernel.org/lkml/[email protected]/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,10 +30,10 @@#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. */ -#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@@ -95,7 +95,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.36.1
BR, Jarkko
Gary Guo
maintainerRe: [PATCH v7 06/25] rust: add `compiler_builtins` crate
In reply to Nick DesaulniersQuoted 11 lines · On Mon, 23 May 2022 11:37:16 -0700 Nick Desaulniers <[email protected]>…
Also, I'm not sure my concern about explicit build failures for C code was ever addressed? We have a constant problem with
long longdivision on ARCH=arm32 and ARCH=i386 in C code.
https://lore.kernel.org/lkml/CAKwvOdk+A2PBdjSFVUhj4xyCGCKujtej1uPgywQgrKPiK2ksPw@mail.gmail.com/rust/compiler_builtins.rs line 57
Quoted 6 lines
(quoted diff) +2
-0+#[cfg(target_arch = "arm")] +define_panicking_intrinsics!("`u64` division/modulo should not beused", {
rust/compiler_builtins.rs new file +3
-0+ __aeabi_uldivmod, + __mulodi4, +});
Starting in LLVM 14 (used in Rust 1.60+), __mulodi4 will no longer be generated. So that can be removed.
As for __aeabi_uldivmod, is there any reason that it can't just be defined in arch/arm/lib? There are quite a few __aeabi functions already defined there.
The source of __aeabi_uldivmod in compiler-rt seems quite simple, just delegating to __uldivmoddi4. I think just changing that to div64_u64_rem should do the job?
https://android.googlesource.com/toolchain/compiler-rt/+/release_32/lib/arm/aeabi_uldivmod.S
- Gary
Re: [PATCH v7 06/25] rust: add `compiler_builtins` crate
In reply to Nick DesaulniersQuoted 2 lines · Nick Desaulniers
^ Any progress on this? Got any links to any feature requests or bug reports.
We got the floating point ones removed via a new feature flag
(https://github.com/rust-lang/rust/pull/86048) that Gary added (they were already removed by the time of the message you link), so upstream Rust is willing to add this sort of thing for us.
For the i128/u128 ones, no change; but upstream Rust is aware of this need (e.g. we presented them in the Rust CTCFT from November:
https://youtu.be/azcrUzeY3Pw?t=751).
See also https://github.com/Rust-for-Linux/linux/issues/2 and linked issues there for more information.
Quoted 4 lines
Also, I'm not sure my concern about explicit build failures for C code was ever addressed? We have a constant problem with
long longdivision on ARCH=arm32 and ARCH=i386 in C code.
https://lore.kernel.org/lkml/CAKwvOdk+A2PBdjSFVUhj4xyCGCKujtej1uPgywQgrKPiK2ksPw@mail.gmail.com/
In my reply to that message I mentioned that the goal is to avoid the panicking intrinsics to begin with. We already removed some, so I would try to continue down that path. If that proves not possible, then yeah, we would need something different.
Cheers,
Miguel
Re: [PATCH v7 04/25] kunit: take `kunit_assert` as `const`
In reply to Shuah KhanQuoted 7 lines · Shuah Khan
Quoted 5 lines · Daniel Latypov
FYI, we'd asked Shuah to pick this patch up in her "kunit" branch. It's applied here:
https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git/commit/?h=kunit&id=7466886b400b1904ce30fa311904849e314a2cf4
Quoted 5 lines
Quoted 3 lines
It had previously seemed unclear if this series could make it for the 5.19 merge window (but it now looks like there's interest in trying it out early on).
I am just about send pull request with this patch included.
Thank you, Daniel and Shuah!
Cheers,
Miguel
Re: [PATCH v7 21/25] Kbuild: add Rust support
In reply to Nick DesaulniersQuoted 4 lines · Nick Desaulniers
I'm super not into having the rust optimization level differ from the C optimization level. This is just someone having too much fun wrapping every compiler flag in a kbuild option. Either folks wan't
I mean, Makefiles are not my favorite pastime... :)
Quoted 4 lines
smaller size or more optimizations. Allowing for
RUST_OPT_LEVEL_SandCONFIG_CC_OPTIMIZE_FOR_PERFORMANCEorRUST_OPT_LEVEL_3andCONFIG_CC_OPTIMIZE_FOR_SIZEis just wacky nonsense that's going to make randconfig bug reports more confusing to tease out.
I think what is important is to decide whether extra levels, for C and Rust, should be kept compile-able/maintained or not (I also replied in the -O1 for C thread [1]).
Note that the Rust side can be compiled as -O0 or -O1 at the moment, which is something we do not have for the C side; thus having only the C == Rust option means we will not have a configuration with those anymore.
For me it is less complex to not have them, and I have not heard more opinions on this, either for or against (apart from that thread suggesting -O1 for the C side), so if nobody else chimes in, I will remove them.
[1] https://lore.kernel.org/lkml/CANiq72kySVvOQ7eqwe0Jzz3V0JTtrcqODHR9Ty4-sfDMdzP6XQ@mail.gmail.com/
Cheers,
Miguel
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
Re: [PATCH v7 01/25] kallsyms: avoid hardcoding the buffer size
In reply to Jarkko SakkinenQuoted 7 lines · Jarkko Sakkinen
"Declare
KSY_NAME_LEN, which describes the maximum length for a kernel symbol read by kallsyms from the input. Inread_symbol(), define the buffer to be of length "KSY_NAME_LEN+ 1", which includes the terminator character."would be better.
Note that the patch is not declaring KSYM_NAME_LEN, but a new constant for a fairly arbitrarily sized for an input buffer.
I am all for detailed commit messages, and I agree this can be expanded. However, I think the first sentence of what you wrote should be part of the docs of the constant, and the second one sounds like it could be a comment on the code. Something like "Introduce KSYM_NAME_LEN_BUFFER in place of the previously hardcoded size of the input buffer (...)" would be better for a reviewer.
Quoted 1 line
You must split this then into two patches:
Note that the size is not really being increased in a meaningful way -- the important bit is the introduction of the relationship between constants. The changes are all meant as a replacement for the previously hardcoded constant, so I don't think the split is a "must", but we can do it.
We can even split this into 3 patches: clean up the unneeded sizeof, replace (and, importantly, document) the hardcoded constant, and finally introduce the relationship.
Thanks for taking a look!
Cheers,
Miguel
Re: [PATCH v7 15/25] scripts: checkpatch: diagnose uses of `%pA` in the C side
In reply to Joe PerchesQuoted 2 lines · Joe Perches
How many developers are required for a trivial patch?
We are sending the core series as a team, so by default I acknowledge all the maintainers. But yeah, I could drop some of the Co-developed-by's.
Quoted 1 line
and this should now use elsif
Yeah, will change.
By the way, I also thought about skipping the warning if the error is there, e.g. wrapping everything else in an else, if you prefer.
Thanks for the very quick review!
Cheers,
Miguel
Re: [PATCH v7 03/25] kallsyms: increase maximum kernel symbol length to 512
In reply to Jarkko SakkinenQuoted 2 lines · Jarkko Sakkinen
There's no description what the patch does.
I am not sure what you mean. Both the subject and the last paragraph describe what the patch does, while the rest gives the rationale behind it.
Cheers,
Miguel
Re: [PATCH v7 06/25] rust: add `compiler_builtins` crate
In reply to Gary GuoQuoted 9 lines · Gary Guo
Quoted 5 lines · On Mon, 23 May 2022 11:37:16 -0700 Nick Desaulniers <[email protected]>…
Also, I'm not sure my concern about explicit build failures for C code was ever addressed? We have a constant problem with
long longdivision on ARCH=arm32 and ARCH=i386 in C code.
https://lore.kernel.org/lkml/CAKwvOdk+A2PBdjSFVUhj4xyCGCKujtej1uPgywQgrKPiK2ksPw@mail.gmail.com/
Quoted 9 lines
Quoted 6 lines
rust/compiler_builtins.rs line 57
Quoted 6 lines
(quoted diff) +2
-0+#[cfg(target_arch = "arm")] +define_panicking_intrinsics!("`u64` division/modulo should not beused", {
rust/compiler_builtins.rs new file +3
-0+ __aeabi_uldivmod, + __mulodi4, +});Starting in LLVM 14 (used in Rust 1.60+),
__mulodi4will no longer be generated. So that can be removed.
I'm familiar, but good catch. ;)
https://reviews.llvm.org/D108936
https://reviews.llvm.org/D108842
https://reviews.llvm.org/D108844
https://reviews.llvm.org/D112750
https://reviews.llvm.org/D108928
https://reviews.llvm.org/D108939
https://bugs.llvm.org/show_bug.cgi?id=28629
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103034
Quoted 4 lines
As for
__aeabi_uldivmod, is there any reason that it can't just be defined inarch/arm/lib? There are quite a few__aeabifunctions already defined there.
Indeed.arch/arm/kernel/armksyms.c andarch/arm/lib/lib1funcs.S
This is the previous thread I recall w/ Linus:
https://lore.kernel.org/llvm/CAHk-=wiydA=Oay+NB2m2ewCHpPEcoU51qPFrzsekFoPu7QPtuw@mail.gmail.com/
If CONFIG_RUST provides those symbols, it will hide the linkage failures that we try to use to spot & avoid 64b division that's open coded using the / binary operator, rather than the kernel's do_div() and friends.
Quoted 4 lines
The source of
__aeabi_uldivmodin compiler-rt seems quite simple, just delegating to__uldivmoddi4. I think just changing that todiv64_u64_remshould do the job?
Maybe; send a patch and see what happens. There's probably other 32b architectures that will need other symbols that also handle 64b division though, so it's not as simple as providing __aeabi_uldivmod for ARM.
There's probably someone from linux-arm-kernel that can provide additional context.
https://lore.kernel.org/linux-arm-kernel/[email protected]/
is pretty old, but refers to policies that seem to pre-exist other references to __aeabi_uldivmod on that list.
arch/nios2/kernel/nios2_ksyms.c exports __udivmoddi4, but it also explicitly links against libgcc. I'm guessing that's frowned upon, but not out of the question relative to having the kernel ported to the architecture at all.
Quoted 2 lines
https://android.googlesource.com/toolchain/compiler-rt/+/release_32/lib/arm/aeabi_uldivmod.S
Here's the latest source.
https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/arm/aeabi_uldivmod.S
and __uldivmoddi4:
https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/udivmoddi4.c
By chance, does any of the rust code in this series use open coded division w/ 64 bit operands (rather than using do_div) by accident?
I'm also curious about the panic message for 128b operands. IIUC, those are functions that may have long long operands. On 32b ARM, which is ILP32, I'd have expected long long to be 64b, not 128b. Message might be misleading.
Signature · 2 lines
Thanks, ~Nick Desaulniers
Re: [PATCH v7 21/25] Kbuild: add Rust support
In reply to Miguel OjedaMakefile endif · line 128
Quoted 13 lines · Miguel Ojeda
Makefile +6
-0@@ -120,6 +120,15 @@ endif export KBUILD_CHECKSRC +# Enable "clippy" (a linter) as part of the Rust compilation. +# +# Use 'make CLIPPY=1' to enable it. +ifeq ("$(origin CLIPPY)", "command line") + KBUILD_CLIPPY := $(CLIPPY) +endif
Is there a reason to not just turn clippy on always? Might be nicer to start off with good practices by default. :^)
Quoted 11 lines
Makefile +2
-1@@ -1494,7 +1588,8 @@ MRPROPER_FILES += include/config include/generated \ certs/signing_key.pem \ certs/x509.genkey \ vmlinux-gdb.py \ - *.spec + *.spec \ + rust/target.json rust/libmacros.so # clean - Delete most, but leave enough to build external modules #
Makefile $(mrproper-dirs): · line 1619
Quoted 6 lines
Makefile +3
-0@@ -1519,6 +1614,9 @@ $(mrproper-dirs): mrproper: clean $(mrproper-dirs) $(call cmd,rmfiles) + @find . $(RCS_FIND_IGNORE) \ + \( -name '*.rmeta' \) \ + -type f -print | xargs rm -f
Are there *.rmeta directories that we _don't_ want to remove via make mrproper? I'm curious why *.rmeta isn't just part of MRPROPER_FILES?
Quoted 13 lines
Makefile +6
-0# distclean #@@ -1606,6 +1704,23 @@ help: @echo ' kselftest-merge - Merge all the config dependencies of' @echo ' kselftest to existing .config.' @echo '' + @echo 'Rust targets:' + @echo ' rustavailable - Checks whether the Rust toolchain is' + @echo ' available and, if not, explains why.' + @echo ' rustfmt - Reformat all the Rust code in the kernel' + @echo ' rustfmtcheck - Checks if all the Rust code in the kernel' + @echo ' is formatted, printing a diff otherwise.'
Makefile help: · line 1722
Quoted 10 lines
Makefile +10
-0+ @echo ' rustdoc - Generate Rust documentation' + @echo ' (requires kernel .config)' + @echo ' rusttest - Runs the Rust tests' + @echo ' (requires kernel .config; downloads external repos)' + @echo ' rust-analyzer - Generate rust-project.json rust-analyzer support file' + @echo ' (requires kernel .config)' + @echo ' dir/file.[os] - Build specified target only' + @echo ' dir/file.i - Build macro expanded source, similar to C preprocessing' + @echo ' (run with RUSTFMT=n to skip reformatting if needed)' + @echo ' dir/file.ll - Build the LLVM assembly file'
I don't think we need to repeat dir/* here again for rust. The existing targets listed above (outside this hunk) make sense in both contexts.
Does rustc really use .i as a conventional suffix for macro expanded sources? (The C compiler might use the -x flag to override the guess it would make based on the file extension; I'm curious if rustc can ingest .i files or will it warn?)
init/Kconfig config PROFILING · line 2089
Quoted 13 lines
init/Kconfig +9
-0+config RUSTC_VERSION_TEXT + string + depends on RUST + default $(shell,command -v $(RUSTC) >/dev/null 2>&1 && $(RUSTC) --version || echo n) + +config BINDGEN_VERSION_TEXT + string + depends on RUST + default $(shell,command -v $(BINDGEN) >/dev/null 2>&1 && $(BINDGEN) --version || echo n)
Are these two kconfigs used anywhere?
scripts/Kconfig.include ld-option = $(success,$(LD) -v $(1)) · line 39
Quoted 10 lines
scripts/Kconfig.include +1
-1@@ -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)
Not that it's important to do so, but a couple hunks s/compiler/C compiler/. Those _could_ probably get submitted ahead of this, but not important to do so.
Quoted 11 lines
scripts/Makefile.debug +1
-0@@ -1,4 +1,5 @@ DEBUG_CFLAGS := +DEBUG_RUSTFLAGS := ifdef CONFIG_DEBUG_INFO_SPLIT DEBUG_CFLAGS += -gsplit-dwarf
scripts/Makefile.debug ifndef CONFIG_AS_IS_LLVM · line 19
Quoted 9 lines
scripts/Makefile.debug +6
-0@@ -10,6 +11,12 @@ ifndef CONFIG_AS_IS_LLVM KBUILD_AFLAGS += -Wa,-gdwarf-2 endif +ifdef CONFIG_DEBUG_INFO_REDUCED +DEBUG_RUSTFLAGS += -Cdebuginfo=1 +else +DEBUG_RUSTFLAGS += -Cdebuginfo=2 +endif +
How does enabling or disabling debug info work for rustc? I may have missed it, but I was surprised to see no additional flags getting passed to rustc based on CONFIG_DEBUG info.
scripts/generate_rust_target.rs
Quoted 5 lines
scripts/generate_rust_target.rs new file +0
-0
Ah, that explains the host rust build infra. Bravo! Hard coding the target files was my major concern last I looked at the series. I'm very happy to see it be generated properly from .config!
I haven't actually reviewed this yet, but it makes me significantly more confident in the series to see this approach added. Good job whoever wrote this.
Quoted 9 lines
scripts/is_rust_module.sh new file +3
-0@@ -0,0 +1,13 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +#
scripts/is_rust_module.sh line 13
Quoted 10 lines
scripts/is_rust_module.sh new file +10
-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. +${NM} "$*" | grep -qE '^[0-9a-fA-F]+ r _R[^[:space:]]+16___IS_RUST_MODULE[^[:space:]]*$'
Does $(READELF) -p .comment foo.o print anything about which compiler was used? That seems less brittle IMO.
---
Modulo the RUST_OPT_LEVEL_SIMILAR_AS_CHOSEN_FOR_C which I'm not a fan of, this is looking good to me. Masahiro, what are your thoughts on the build system support?
Signature · 2 lines
Thanks, ~Nick Desaulniers
Re: [PATCH v7 01/25] kallsyms: avoid hardcoding the buffer size
In reply to Miguel OjedaQuoted 12 lines · Miguel Ojeda
Quoted 7 lines · Jarkko Sakkinen
"Declare
KSY_NAME_LEN, which describes the maximum length for a kernel symbol read by kallsyms from the input. Inread_symbol(), define the buffer to be of length "KSY_NAME_LEN+ 1", which includes the terminator character."would be better.
Note that the patch is not declaring
KSYM_NAME_LEN, but a new constant for a fairly arbitrarily sized for an input buffer.
Quoted 6 lines
I am all for detailed commit messages, and I agree this can be expanded. However, I think the first sentence of what you wrote should be part of the docs of the constant, and the second one sounds like it could be a comment on the code. Something like "Introduce
KSYM_NAME_LEN_BUFFERin place of the previously hardcoded size of the input buffer (...)" would be better for a reviewer.
Inline comment would be sufficient a remainder, and actually a better idea.
Quoted 8 lines
Quoted 1 line
You must split this then into two patches:
Note that the size is not really being increased in a meaningful way -- the important bit is the introduction of the relationship between constants. The changes are all meant as a replacement for the previously hardcoded constant, so I don't think the split is a "must", but we can do it.
Quoted 8 lines
We can even split this into 3 patches: clean up the unneeded
sizeof, replace (and, importantly, document) the hardcoded constant, and finally introduce the relationship.Thanks for taking a look!
Cheers,
Miguel
BR, Jarkko
Re: [PATCH v7 03/25] kallsyms: increase maximum kernel symbol length to 512
In reply to Miguel OjedaQuoted 10 lines · Miguel Ojeda
Quoted 2 lines · Jarkko Sakkinen
There's no description what the patch does.
I am not sure what you mean. Both the subject and the last paragraph describe what the patch does, while the rest gives the rationale behind it.
Cheers,
Miguel
The honest answer: I don't actually remember what I was thinking (other stuff stole my focus) but my comment neither makes much sense to me. Please just ignore it, and apologies for causing confusion.
There's something I'm looking into in my spare time right now. I'm experimenting with interfacing keyring types to Rust. The first step, I guess, is to provide a Rust abstraction for assoc_array.
I've skimmed through the patch set and have now *rough* idea of patterns and techniques. My opens are more on the process side of things since there's no yet mainline subtree.
If I send a patch or patch sets, would this be a good workflow:
1. RFC tag.
2. In the cover letter denote the patch set version, which was used the baseline.
Linux keyring is without argument a kind of subsystem that would hugely benefit of the Rust work, as it is both user space facing nd handling a vast amount of user's confidential data.
BR, Jarkko
Re: [PATCH v7 03/25] kallsyms: increase maximum kernel symbol length to 512
Quoted 5 lines · Jarkko Sakkinen
The honest answer: I don't actually remember what I was thinking (other stuff stole my focus) but my comment neither makes much sense to me. Please just ignore it, and apologies for causing confusion.
No apologies needed!
Quoted 8 lines
There's something I'm looking into in my spare time right now. I'm experimenting with interfacing keyring types to Rust. The first step, I guess, is to provide a Rust abstraction for
assoc_array.I've skimmed through the patch set and have now *rough* idea of patterns and techniques. My opens are more on the process side of things since there's no yet mainline subtree.
Thanks a lot for taking a look and taking the initiative.
Quoted 5 lines
If I send a patch or patch sets, would this be a good workflow:
1. RFC tag.
2. In the cover letter denote the patch set version, which was used the baseline.
Sounds good to me. Alternatively, you can use a --base= pointing to one of the commits in our rust branch.
Cheers,
Miguel
Re: [PATCH v7 21/25] Kbuild: add Rust support
In reply to Nick DesaulniersQuoted 3 lines · Nick Desaulniers
Is there a reason to not just turn clippy on always? Might be nicer to start off with good practices by default. :^)
The idea crossed my mind too [1], but sadly Clippy disables some optimizations and in general is not intended to be used for normal compilation [2].
[1] https://github.com/rust-lang/rust-clippy/issues/8035
[2] https://github.com/rust-lang/rust-clippy/pull/8037
Quoted 2 lines
Are there *.rmeta directories that we _don't_ want to remove via
make mrproper? I'm curious why *.rmeta isn't just part ofMRPROPER_FILES?
Putting them in MRPROPER_FILES would mean only those in a given directory are removed (e.g. the root one), but the idea here is to find them anywhere in the tree, since in the future we may have library crates in different parts of the tree.
However, I am not sure I understand your first question in relation with the second one -- if we put them in MRPROPER_FILES, that would remove less, not more.
Quoted 3 lines
I don't think we need to repeat dir/* here again for rust. The existing targets listed above (outside this hunk) make sense in both contexts.
The idea here is to document the differences (e.g. RUSTFMT) and that we may have other targets in the future that do not apply to C (e.g. MIR dump, if that happens to be useful).
But maybe I can fit that in the normal place and make it still look good... I will give it a try.
Quoted 2 lines
Does rustc really use .i as a conventional suffix for macro expanded sources? (The C compiler might use the -x flag to override the guess
It is not a conventional suffix at all as far as I am aware.
Maybe we should use a different one to aid editors and users anyway, e.g. .rsi, similar to .mi for Objective-C .m files.
Quoted 2 lines
it would make based on the file extension; I'm curious if rustc can ingest .i files or will it warn?)
The macro expanded output is not intended to be used as a compilable input, but as a debugging aid only. I can note this there.
Having said that, rustc accepts the "preprocessed" output in the sense that it will just treat them as normal source files (no flag needed, and e.g. both .i and .rsi work); however, it may give new diagnostics or may require extra flags to enable some compiler features.
From a quick test, I managed to compile a "preprocessed" Rust kernel module with only command-line changes. But if we really wanted to support this, we would need to ask upstream Rust to actually support it.
Quoted 1 line
Are these two kconfigs used anywhere?
Not for the moment, but it could still be useful when getting .config reports (and we could add it to LINUX_COMPILER etc. in the future).
Quoted 3 lines
How does enabling or disabling debug info work for rustc? I may have missed it, but I was surprised to see no additional flags getting passed to rustc based on
CONFIG_DEBUGinfo.
-Cdebuginfo= is the one; by default there is no debug info and that option enables it (i.e. it is not just the level but the enablement too).
(Note that in userspace, when compiling a common program, you will get some debug info coming from the standard library and other dependencies).
Quoted 7 lines
Ah, that explains the host rust build infra. Bravo! Hard coding the target files was my major concern last I looked at the series. I'm very happy to see it be generated properly from .config!
I haven't actually reviewed this yet, but it makes me significantly more confident in the series to see this approach added. Good job whoever wrote this.
Thanks! I thought Rust would be a nice option for writing hostprogs, though of course for the moment only programs that can assume Rust is there may use it.
Note that non-x86 specific options need to be handled properly still (e.g. move things between the arch Makefiles and the hostprog as needed).
I would still want to see compilers come to some kind of common format for this as we discussed other times, but... :)
Quoted 2 lines
Does
$(READELF) -p .comment foo.oprint anything about which compiler was used? That seems less brittle IMO.
Currently, rustc does not add a .comment section; but we could ask, I sent [3].
If debug info is enabled, another way is using the DW_AT_language attribute, like pahole will be doing for a new option we need [4]. However, we would still need a way for the other case.
In any case, I am not sure something like .comment is less or more brittle -- compilers could in theory change it (e.g. not emitting it), while adding a symbol is something we control. So different kinds of brittleness.
[3] https://github.com/rust-lang/rust/pull/97550
[4] https://git.kernel.org/pub/scm/devel/pahole/pahole.git/commit/?id=8ee363790b7437283c53090a85a9fec2f0b0fbc4
Cheers,
Miguel
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
Re: [PATCH v7 21/25] Kbuild: add Rust support
In reply to Miguel OjedaQuoted 44 lines · Miguel Ojeda
Having all the new files in place, we now enable Rust support in the build system, including
Kconfigentries related to Rust, the Rust configuration printer, the target specification generation script, the version detection script and a few other bits.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 Miguel Cano <[email protected]>Signed-off-by Miguel Cano <[email protected]>Co-developed-by David Gow <[email protected]>Signed-off-by David Gow <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>---
Makefile PHONY += $(DOC_TARGETS) · line 1803
Quoted 8 lines
Makefile +8
-0+# Rust targets +# --------------------------------------------------------------------------- + +# "Is Rust available?" target +PHONY += rustavailable +rustavailable: + $(Q)$(CONFIG_SHELL) $(srctree)/scripts/rust-is-available.sh -v && echo >&2 "Rust is available!" +
Is it intentional to print the successful message to stderr?
Signature · 2 lines
Best Regards Masahiro Yamada
Re: [PATCH v7 21/25] Kbuild: add Rust support
Hi Masahiro,
Quoted 2 lines · Masahiro Yamada
Is it intentional to print the successful message to stderr?
I think it makes sense to change it to stdout, given the message is the main point of running rustavailable for normal users, and those that just want the status code may ignore it.
Thanks for taking a look again!
Cheers,
Miguel
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
Hey,
Maybe I am just missing something blatantly obvious here, but trying to build rust support in -next fails for me. I am using ClangBuiltLinux clang version 15.0.0 5b0788fef86ed7008a11f6ee19b9d86d42b6fcfa and LLD 15.0.0. Is it just expected that building -next with rust support is not a good idea?
My defconfig is the default RISC-V one plus:CONFIG_RUST=yCONFIG_SAMPLES=yCONFIG_SAMPLES_RUST=yCONFIG_SAMPLE_RUST_MINIMAL=y
Thanks,
Conor.
Fail log:
UPD rust/target.json
BINDGEN rust/bindings_generated.rs
BINDGEN rust/bindings_helpers_generated.rs
RUSTC L rust/core.o
EXPORTS rust/exports_core_generated.h
RUSTC P rust/libmacros.so
RUSTC L rust/compiler_builtins.o
RUSTC L rust/alloc.o
RUSTC L rust/build_error.o
EXPORTS rust/exports_alloc_generated.h
RUSTC L rust/kernel.o
error[E0428]: the name maple_enode is defined multiple times
--> linux/rust/bindings_generated.rs:18009:1
|
18006 | pub struct maple_enode {
| ---------------------- previous definition of the type `maple_enode` here
...
18009 | pub type maple_enode = *mut maple_enode;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `maple_enode` redefined here
| = note: maple_enode must be defined only once in the type namespace of this module
error[E0428]: the name maple_pnode is defined multiple times
--> linux/rust/bindings_generated.rs:18015:1
|
18012 | pub struct maple_pnode {
| ---------------------- previous definition of the type `maple_pnode` here
...
18015 | pub type maple_pnode = *mut maple_pnode;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `maple_pnode` redefined here
| = note: maple_pnode must be defined only once in the type namespace of this module
error[E0391]: cycle detected when expanding type alias bindings::bindings_raw::maple_pnode
--> linux/rust/bindings_generated.rs:18015:29
|
18015 | pub type maple_pnode = *mut maple_pnode;
| ^^^^^^^^^^^
| = note: ...which immediately requires expanding type alias bindings::bindings_raw::maple_pnode again = note: type aliases cannot be recursive
= help: consider using a struct, enum, or union instead to break the cycle
= help: see <https://doc.rust-lang.org/reference/types.html#recursive-types> for more information
note: cycle used when computing type of bindings::bindings_raw::maple_range_64::parent
--> linux/rust/bindings_generated.rs:18058:22
|
18058 | pub parent: *mut maple_pnode,
| ^^^^^^^^^^^error[E0391]: cycle detected when expanding type alias bindings::bindings_raw::maple_enode
--> linux/rust/bindings_generated.rs:18009:29
|
18009 | pub type maple_enode = *mut maple_enode;
| ^^^^^^^^^^^
| = note: ...which immediately requires expanding type alias bindings::bindings_raw::maple_enode again = note: type aliases cannot be recursive
= help: consider using a struct, enum, or union instead to break the cycle
= help: see <https://doc.rust-lang.org/reference/types.html#recursive-types> for more information
note: cycle used when computing type of bindings::bindings_raw::maple_topiary::next
--> linux/rust/bindings_generated.rs:18340:20
|
18340 | pub next: *mut maple_enode,
| ^^^^^^^^^^^error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> linux/rust/bindings_generated.rs:18005:10
|
18005 | #[derive(Copy, Clone)]
| ^^^^
| |
| impl doesn't use only types from inside the current crate
| `*mut [type error]` is not defined in the current crate
| = note: define and implement a trait or new type instead
= note: this error originates in the derive macro Copy (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> linux/rust/bindings_generated.rs:18011:10
|
18011 | #[derive(Copy, Clone)]
| ^^^^
| |
| impl doesn't use only types from inside the current crate
| `*mut [type error]` is not defined in the current crate
| = note: define and implement a trait or new type instead
= note: this error originates in the derive macro Copy (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> linux/rust/bindings_generated.rs:18005:16
|
18005 | #[derive(Copy, Clone)]
| ^^^^^
| |
| impl doesn't use only types from inside the current crate
| `*mut [type error]` is not defined in the current crate
| = note: define and implement a trait or new type instead
= note: this error originates in the derive macro Clone (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> linux/rust/bindings_generated.rs:18011:16
|
18011 | #[derive(Copy, Clone)]
| ^^^^^
| |
| impl doesn't use only types from inside the current crate
| `*mut [type error]` is not defined in the current crate
| = note: define and implement a trait or new type instead
= note: this error originates in the derive macro Clone (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 8 previous errors
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
Hi Conor,
Quoted 6 lines · Conor Dooley
Maybe I am just missing something blatantly obvious here, but trying to build rust support in -next fails for me. I am using ClangBuiltLinux clang version 15.0.0
5b0788fef86ed7008a11f6ee19b9d86d42b6fcfaand LLD 15.0.0. Is it just expected that building -next with rust support is not a good idea?
Please see https://github.com/Rust-for-Linux/linux/issues/795 for details about the maple tree issue.
I will update the rust-next branch next week with the new version of the patches; but if you are interested in developing, please use the development rust branch instead in GitHub for the moment.
Cheers,
Miguel
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
Quoted 4 lines · Miguel Ojeda
Hi Conor,
Quoted 1 line · Conor Dooley
Quoted 8 lines
Quoted 5 lines
Maybe I am just missing something blatantly obvious here, but trying to build rust support in -next fails for me. I am using ClangBuiltLinux clang version 15.0.0
5b0788fef86ed7008a11f6ee19b9d86d42b6fcfaand LLD 15.0.0. Is it just expected that building -next with rust support is not a good idea?Please see https://github.com/Rust-for-Linux/linux/issues/795 for details about the maple tree issue.
Ah right, sorry for the noise so. I checked the ml but didn't see a report there.
Quoted 4 lines
I will update the
rust-nextbranch next week with the new version of the patches; but if you are interested in developing, please use the developmentrustbranch instead in GitHub for the moment.
Thanks Miguel, good to know! I'll just wait around for a new version. Just been trying to get my CI etc in order for when rust support lands, but it sounds like I should be okay as it's a known problem & not some only-broken-on-riscv thing.
Thanks,
Conor.
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um
Quoted 3 lines · On Sat, Jul 16, 2022 at 3:51 PM <[email protected]> wrote:
Ah right, sorry for the noise so. I checked the ml but didn't see a report there.
No apologies needed -- thanks to you for the report, instead! :)
Quoted 4 lines
Thanks Miguel, good to know! I'll just wait around for a new version. Just been trying to get my CI etc in order for when rust support lands, but it sounds like I should be okay as it's a known problem & not some only-broken-on-riscv thing.
Yeah, it is a simple bindgen issue. Thanks a lot for making the effort to prepare your CI in advance!
Cheers,
Miguel
_______________________________________________
linux-um mailing list
[email protected]
http://lists.infradead.org/mailman/listinfo/linux-um