refactor(build): share Linux headers and Kbuild settings

This commit is contained in:
Tyler Smith committed 2026-11-01 13:54:14 +00:00
1 parent 001af6acbf
commit eb12517cf5
10 files changed
+287 -163

No files matched your search

Generated
+1
View File
@@ -2138,6 +2138,7 @@ name = "stela-c-build"
version = "0.1.0"
dependencies = [
"cc",
"tempfile",
]
[[package]]
+4
View File
@@ -9,6 +9,10 @@ workspace = true
[features]
native = ["dep:cc"]
linux = ["native"]
[dependencies]
cc = { version = "1", optional = true }
[dev-dependencies]
tempfile = "3"
+2
View File
@@ -3,6 +3,8 @@
//! the active Rust toolchain's LLVM archiver.
use std::{env, path::PathBuf, process::Command};
#[cfg(feature = "linux")]
pub mod linux;
#[cfg(feature = "native")]
pub mod native;
+223
View File
@@ -0,0 +1,223 @@
//! Linux header layout, generated asm wrappers and Kbuild compilation settings.
use std::{
fs,
path::{Path, PathBuf},
};
/// Source and output trees owned by the invoking build.
pub struct Roots {
pub linux: PathBuf,
pub compat: PathBuf,
pub output: PathBuf,
}
/// A Linux module's names from Kbuild.
pub struct Module<'a> {
pub name: &'a str,
pub file: &'a str,
}
pub struct Environment {
linux: PathBuf,
compat: PathBuf,
wrappers: PathBuf,
}
impl Environment {
pub fn new(roots: Roots) -> Self {
additions(&roots.compat, &roots.compat, &roots.linux.join("include"));
let wrappers = roots.output.join("linux-asm");
let include = roots.linux.join("include");
let x86_uapi = roots.linux.join("arch/x86/include/uapi");
for (list, arch, directory) in [
("asm-generic/Kbuild", roots.compat.join("asm"), "asm"),
("uapi/asm-generic/Kbuild", x86_uapi.join("asm"), "uapi/asm"),
] {
let output = wrappers.join(directory);
fs::create_dir_all(&output).expect("create the asm wrapper directory");
let contents = fs::read_to_string(include.join(list))
.unwrap_or_else(|error| panic!("{list}: {error}"));
for header in contents
.lines()
.filter_map(|line| line.strip_prefix("mandatory-y += "))
.filter(|header| !arch.join(header).exists())
{
fs::write(
output.join(header),
format!("#include <asm-generic/{header}>\n"),
)
.expect("write an asm wrapper");
}
}
Self {
linux: roots.linux,
compat: roots.compat,
wrappers,
}
}
/// Apply the shared Linux ABI and header search order. The caller supplies
/// its class-specific include directories and optional generated headers.
pub fn apply(
&self,
build: &mut cc::Build,
generated: Option<&Path>,
directories: &[PathBuf],
module: Option<&Module<'_>>,
) {
build
.flag("-nostdinc")
.define("__KERNEL__", None)
.define("__DISABLE_EXPORTS", None);
for flag in [
"-fms-extensions",
"-fshort-wchar",
"-fno-strict-aliasing",
"-fno-common",
"-fno-strict-overflow",
"-fno-delete-null-pointer-checks",
"-funsigned-char",
] {
build.flag(flag);
}
let include = self.linux.join("include");
let x86_uapi = self.linux.join("arch/x86/include/uapi");
let mm = self.linux.join("mm");
for header in [
include.join("linux/kconfig.h"),
include.join("linux/compiler_types.h"),
self.compat.join("stela/compiler.h"),
] {
build.flag("-include").flag(header);
}
if let Some(module) = module {
build
.define("KBUILD_MODNAME", format!("\"{}\"", module.name).as_str())
.define("KBUILD_MODFILE", format!("\"{}\"", module.file).as_str());
}
for directory in directories.iter().map(PathBuf::as_path).chain([
self.compat.as_path(),
include.as_path(),
x86_uapi.as_path(),
mm.as_path(),
]) {
println!("cargo:rerun-if-changed={}", directory.display());
}
for directory in generated
.map(Path::to_path_buf)
.into_iter()
.chain(directories.iter().cloned())
.chain([
self.compat.clone(),
self.wrappers.clone(),
include.clone(),
x86_uapi,
self.wrappers.join("uapi"),
include.join("uapi"),
mm,
])
{
build.flag("-isystem").flag(directory);
}
}
}
/// Stela may add headers and provide its architecture, while common Linux
/// headers continue to come from the selected upstream tree.
fn additions(directory: &Path, compat: &Path, include: &Path) {
for entry in fs::read_dir(directory).expect("read the kernel-API directory") {
let path = entry.expect("readable directory entry").path();
let header = path.strip_prefix(compat).expect("a kernel-API path");
if path.is_dir() {
if header != Path::new("asm") {
additions(&path, compat, include);
}
continue;
}
for tree in [include.to_path_buf(), include.join("uapi")] {
assert!(
!tree.join(header).exists(),
"{}/{} would replace Linux's in {}",
compat.display(),
header.display(),
tree.display()
);
}
}
}
#[cfg(test)]
mod tests {
//! Header ownership and architecture-wrapper controls in independent trees.
use super::*;
use tempfile::TempDir;
fn roots() -> (TempDir, Roots) {
let temporary = tempfile::tempdir().unwrap();
let linux = temporary.path().join("linux");
let compat = temporary.path().join("compat");
for directory in [
linux.join("include/asm-generic"),
linux.join("include/uapi/asm-generic"),
compat.join("asm"),
] {
fs::create_dir_all(directory).unwrap();
}
for path in [
"include/asm-generic/Kbuild",
"include/uapi/asm-generic/Kbuild",
] {
fs::write(linux.join(path), "mandatory-y += types.h\n").unwrap();
}
let output = temporary.path().join("output");
(
temporary,
Roots {
linux,
compat,
output,
},
)
}
#[test]
fn mandatory_headers_get_original_generic_wrappers() {
let (_temporary, roots) = roots();
let output = roots.output.clone();
let _environment = Environment::new(roots);
for path in ["linux-asm/asm/types.h", "linux-asm/uapi/asm/types.h"] {
assert_eq!(
fs::read_to_string(output.join(path)).unwrap(),
"#include <asm-generic/types.h>\n"
);
}
}
#[test]
fn common_headers_cannot_override_linux_or_uapi() {
for tree in ["include", "include/uapi"] {
let (_temporary, roots) = roots();
fs::create_dir_all(roots.compat.join("linux")).unwrap();
fs::create_dir_all(roots.linux.join(tree).join("linux")).unwrap();
fs::write(roots.compat.join("linux/example.h"), "compat").unwrap();
fs::write(roots.linux.join(tree).join("linux/example.h"), "upstream").unwrap();
assert!(std::panic::catch_unwind(|| Environment::new(roots)).is_err());
}
}
#[test]
fn architecture_headers_keep_their_selected_implementation() {
let (_temporary, roots) = roots();
fs::write(roots.compat.join("asm/types.h"), "Stela architecture").unwrap();
let arch = roots.linux.join("arch/x86/include/uapi/asm");
fs::create_dir_all(&arch).unwrap();
fs::write(arch.join("types.h"), "Linux architecture UAPI").unwrap();
let output = roots.output.clone();
let _environment = Environment::new(roots);
assert!(!output.join("linux-asm/asm/types.h").exists());
assert!(!output.join("linux-asm/uapi/asm/types.h").exists());
assert_eq!(
fs::read_to_string(arch.join("types.h")).unwrap(),
"Linux architecture UAPI"
);
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ workspace = true
[features]
# Common native Linux kernel services; selecting this attaches no GPU.
linux-kernel = ["dep:cc", "dep:stela-c-build", "stela-c-build/native", "stela-driver-base/linux-kernel"]
linux-kernel = ["dep:cc", "dep:stela-c-build", "stela-c-build/linux", "stela-driver-base/linux-kernel"]
# Build the implemented native NVIDIA OS hooks, not a complete GPU driver.
nvidia-port = ["dep:cc", "dep:stela-c-build", "stela-c-build/native"]
# Native Xe command/page-table support; not an initialized Intel GPU driver.
+6 -5
View File
@@ -1,7 +1,8 @@
//! Stela's amdgpu port and its hosted tests.
use super::native::{self, Linux, Module, Tests};
use super::native::{self, Linux, Tests};
use stela_c_build::linux::Module;
const AMDGPU: Module = Module {
const AMDGPU: Module<'static> = Module {
name: "amdgpu",
file: "drivers/gpu/drm/amd/amdgpu/amdgpu",
};
@@ -12,10 +13,10 @@ const AMDGPU: Module = Module {
pub fn port(linux: &Linux, tests: &mut Tests) {
const FIXTURES: &str = "src/amd/tests/fixtures.c";
let configure = |mut build: cc::Build| {
linux.apply(
linux.environment.apply(
&mut build,
None,
&[
&native::drm_includes(&[
"amd/include/asic_reg",
"amd/include",
"amd/amdgpu",
@@ -29,7 +30,7 @@ pub fn port(linux: &Linux, tests: &mut Tests) {
"amd/amdkfd",
"amd/ras/rascore",
"amd/ras/ras_mgr",
],
]),
Some(&AMDGPU),
);
build
+15 -4
View File
@@ -1,12 +1,13 @@
//! Stela's Xe and i915 port, its dispatch packers and their hosted tests.
//! Linux's and Mesa's original generators supply the workaround table and the
//! packet headers, run by a selected Python interpreter.
use super::native::{self, Linux, Module, Tests};
use super::native::{self, Linux, Tests};
use std::{
env, fs,
path::{Path, PathBuf},
process::Command,
};
use stela_c_build::linux::Module;
const SOURCE: &str = "src/intel";
const XE_DRIVER: &str = "../../third_party/linux/drivers/gpu/drm/xe";
@@ -14,7 +15,7 @@ const GENXML: &str = "../../third_party/mesa/src/intel/genxml";
const LEGACY: &str = "GPGPU_WALKER,MEDIA_STATE_FLUSH";
const COMPUTE: &str = "COMPUTE_WALKER,COMPUTE_WALKER_BODY,INTERFACE_DESCRIPTOR_DATA,POSTSYNC_DATA,PREF_SLM_ALLOCATION_SIZE";
const XE: Module = Module {
const XE: Module<'static> = Module {
name: "xe",
file: "drivers/gpu/drm/xe/xe",
};
@@ -83,10 +84,20 @@ struct Builds {
impl Builds {
fn new(linux: &Linux, base: &cc::Build, generated: &Path, dispatch: &Path) -> Self {
let mut xe = base.clone();
linux.apply(&mut xe, Some(generated), &["xe"], Some(&XE));
linux.environment.apply(
&mut xe,
Some(generated),
&native::drm_includes(&["xe"]),
Some(&XE),
);
xe.include(SOURCE);
let mut i915 = base.clone();
linux.apply(&mut i915, None, &["i915"], Some(&I915));
linux.environment.apply(
&mut i915,
None,
&native::drm_includes(&["i915"]),
Some(&I915),
);
i915.define("I915", None).include(SOURCE);
let mut encoders = base.clone();
encoders
+20 -146
View File
@@ -39,20 +39,12 @@ fn require_source(source: &str) {
);
}
/// A Linux module, as Kbuild names it to the sources it builds.
#[cfg(feature = "linux-kernel")]
pub struct Module {
pub name: &'static str,
/// The module's path in Linux's tree, without its extension.
pub file: &'static str,
}
/// Stela's Linux environment for unchanged Linux sources, and the kernel-API
/// in `compat/linux/kernel` that they call, built once for every port.
#[cfg(feature = "linux-kernel")]
pub struct Linux {
/// Kbuild's generated asm wrappers, in `asm/` and `uapi/asm/`.
wrappers: PathBuf,
/// Shared Kbuild flags and generated architecture header layout.
pub environment: stela_c_build::linux::Environment,
/// The kernel-API archive for Cargo's target.
pub archive: PathBuf,
/// The environment's units whose registrations nouveau's image names.
@@ -165,42 +157,18 @@ const DMA_BUF_SOURCES: &[&str] = &[
];
#[cfg(feature = "linux-kernel")]
const COMPAT: &str = "src/compat/linux";
#[cfg(feature = "linux-kernel")]
const INCLUDE: &str = "../../third_party/linux/include";
#[cfg(feature = "linux-kernel")]
const X86_UAPI: &str = "../../third_party/linux/arch/x86/include/uapi";
#[cfg(feature = "linux-kernel")]
impl Linux {
pub fn new() -> Self {
require_sources();
additions(Path::new(COMPAT));
let wrappers = out_dir().join("linux-asm");
// As Kbuild does, each mandatory asm header that the arch does not
// provide wraps asm-generic's. Stela's arch headers are compat's.
for (list, arch, directory) in [
("asm-generic/Kbuild", format!("{COMPAT}/asm"), "asm"),
(
"uapi/asm-generic/Kbuild",
format!("{X86_UAPI}/asm"),
"uapi/asm",
),
] {
let output = wrappers.join(directory);
fs::create_dir_all(&output).expect("create the asm wrapper directory");
let list = fs::read_to_string(format!("{INCLUDE}/{list}"))
.unwrap_or_else(|error| panic!("{list}: {error}"));
for header in list
.lines()
.filter_map(|line| line.strip_prefix("mandatory-y += "))
.filter(|header| !Path::new(&arch).join(header).exists())
{
let wrapper = format!("#include <asm-generic/{header}>\n");
fs::write(output.join(header), wrapper).expect("write an asm wrapper");
}
}
let environment = stela_c_build::linux::Environment::new(stela_c_build::linux::Roots {
linux: LINUX.into(),
compat: COMPAT.into(),
output: out_dir(),
});
let mut linux = Self {
wrappers,
environment,
archive: PathBuf::new(),
hosted: Vec::new(),
#[cfg(feature = "nouveau-port")]
@@ -275,7 +243,7 @@ impl Linux {
println!("cargo:rerun-if-changed={}", source.display());
}
let mut build = configure();
linux.apply(&mut build, None, &[], None);
linux.environment.apply(&mut build, None, &[], None);
let crc_objects = linux_crc::objects(&build, &crc_tables);
build.objects(crc_objects);
#[cfg(feature = "nouveau-port")]
@@ -307,7 +275,7 @@ impl Linux {
helper.file(format!("{COMPAT}/stela/test.c"));
let helper_objects = helper.compile_intermediates();
let mut fixture = configure();
linux.apply(&mut fixture, None, &[], None);
linux.environment.apply(&mut fixture, None, &[], None);
fixture
.define("STELA_LINUX_TREES_TEST", None)
.define("STELA_LINUX_TREES_CALLABLE", None)
@@ -338,7 +306,7 @@ impl Linux {
];
let services = archive(&host, "linux-host", &services);
let mut kernel_build = host;
linux.apply(&mut kernel_build, None, &[], None);
linux.environment.apply(&mut kernel_build, None, &[], None);
let crc_objects = linux_crc::objects(&kernel_build, &crc_tables);
kernel_build.objects(crc_objects);
linux.hosted = vec![
@@ -368,7 +336,7 @@ impl Linux {
let Some(mut build) = hosted() else {
return;
};
self.apply(&mut build, None, &[], None);
self.environment.apply(&mut build, None, &[], None);
let archives = self.hosted.iter().map(PathBuf::as_path).collect::<Vec<_>>();
// Dedicated lifecycle fixture: unchanged original kobject/uevent APIs.
tests.add(
@@ -469,85 +437,15 @@ impl Linux {
);
}
}
}
/// Kbuild's definitions, flags and forced includes, and system include
/// directories so upstream code keeps Linux's warning profile rather than
/// Stela's. `generated` holds headers a driver's build generates and
/// `drivers` its directories below Linux's `drivers/gpu/drm`. Stela's
/// arch headers in `compat/linux/asm` and the generated wrappers stand for
/// Linux's arch tree ahead of its `include` tree, and the x86 uapi
/// headers and their wrappers ahead of `include/uapi`.
pub fn apply(
&self,
build: &mut cc::Build,
generated: Option<&Path>,
drivers: &[&str],
module: Option<&Module>,
) {
// As Kbuild builds, no headers outside Linux's trees: neither the
// host's C library nor the compiler's own. Stela's C code gets the C
// headers it uses from `compat`, over Linux's types.
build
.flag("-nostdinc")
.define("__KERNEL__", None)
// Linux explicitly supports static reuse without its ELF module
// export records (also used by its own UEFI stub).
.define("__DISABLE_EXPORTS", None);
for flag in [
"-fms-extensions",
// Linux KBUILD_CFLAGS: EFI names use 16-bit wide literals on every host.
"-fshort-wchar",
"-fno-strict-aliasing",
"-fno-common",
"-fno-strict-overflow",
"-fno-delete-null-pointer-checks",
"-funsigned-char",
] {
build.flag(flag);
}
for header in [
format!("{INCLUDE}/linux/kconfig.h"),
format!("{INCLUDE}/linux/compiler_types.h"),
format!("{COMPAT}/stela/compiler.h"),
] {
build.flag("-include").flag(header);
}
if let Some(module) = module {
build
.define("KBUILD_MODNAME", format!("\"{}\"", module.name).as_str())
.define("KBUILD_MODFILE", format!("\"{}\"", module.file).as_str());
}
let drivers = drivers
.iter()
.map(|driver| PathBuf::from(format!("{DRM}/{driver}")))
.collect::<Vec<_>>();
// Cargo sees no included header, so every source tree the
// environment builds from is an input.
for directory in drivers.iter().map(|path| path.as_path()).chain([
Path::new(COMPAT),
Path::new(INCLUDE),
Path::new(X86_UAPI),
Path::new(LINUX).join("mm").as_path(),
]) {
println!("cargo:rerun-if-changed={}", directory.display());
}
for directory in generated
.map(Path::to_path_buf)
.into_iter()
.chain(drivers)
.chain([
COMPAT.into(),
self.wrappers.clone(),
INCLUDE.into(),
X86_UAPI.into(),
self.wrappers.join("uapi"),
format!("{INCLUDE}/uapi").into(),
format!("{LINUX}/mm").into(),
])
{
build.flag("-isystem").flag(directory);
}
}
/// Include directories below the GPU framework's source root.
#[cfg(feature = "linux-kernel")]
pub fn drm_includes(directories: &[&str]) -> Vec<PathBuf> {
directories
.iter()
.map(|directory| Path::new(DRM).join(directory))
.collect()
}
/// Compile unchanged helpers with the common ABI and baseline diagnostics,
@@ -620,30 +518,6 @@ pub fn upstream_warnings(build: &mut cc::Build) {
}
}
/// Every header in `compat` adds to Linux's: none stands in for one of
/// `include/` by sharing its path, so upstream code always compiles against
/// Linux's own headers. Its `asm/` is Stela's arch, which stands in for x86's.
#[cfg(feature = "linux-kernel")]
fn additions(directory: &Path) {
for entry in fs::read_dir(directory).expect("read the kernel-API directory") {
let path = entry.expect("readable directory entry").path();
let header = path.strip_prefix(COMPAT).expect("a kernel-API path");
if path.is_dir() {
if header != Path::new("asm") {
additions(&path);
}
continue;
}
for tree in [INCLUDE, &format!("{INCLUDE}/uapi")] {
assert!(
!Path::new(tree).join(header).exists(),
"{COMPAT}/{} would replace Linux's in {tree}",
header.display()
);
}
}
}
/// Clang reports nothing from system headers, not even a call to a service no
/// header declares, so check each adapter for those before it links.
#[cfg(feature = "linux-kernel")]
+9 -3
View File
@@ -3,7 +3,7 @@
//! environment does not yet supply.
use super::initcalls::{self, Captured, Unit};
use super::kbuild::{Config, Kbuild};
use super::native::{self, Linux, Module};
use super::native::{self, Linux};
use object::{Object, ObjectSymbol, read::archive::ArchiveFile};
use std::{
collections::{BTreeMap, BTreeSet},
@@ -11,11 +11,12 @@ use std::{
path::Path,
thread,
};
use stela_c_build::linux::Module;
const NOUVEAU: &str = "../../third_party/linux/drivers/gpu/drm/nouveau";
const AUTOCONF: &str = "src/compat/linux/generated/autoconf.h";
const KERNEL: &str = "src/compat/linux/kernel";
const MODULE: Module = Module {
const MODULE: Module<'static> = Module {
name: "nouveau",
file: "drivers/gpu/drm/nouveau/nouveau",
};
@@ -101,7 +102,12 @@ pub fn port(linux: &mut Linux) {
// Compiled below, with its registrations captured.
sources.retain(|source| *source != INITCALLS.path());
let mut build = stela_c_build::native::configure();
linux.apply(&mut build, None, &includes, Some(&MODULE));
linux.environment.apply(
&mut build,
None,
&native::drm_includes(&includes),
Some(&MODULE),
);
native::upstream_warnings(&mut build);
// As Kbuild builds every profile: Linux relies on the optimizer to drop
// the calls its configuration disables.
@@ -3,13 +3,15 @@
use std::{env, path::PathBuf};
#[cfg(feature = "linux-kernel")]
use super::native::{LINUX, Linux, Module, Tests, check_declarations, run};
use super::native::{self, LINUX, Linux, Tests, check_declarations, run};
#[cfg(feature = "linux-kernel")]
use std::{
process::{self, Command},
time::{SystemTime, UNIX_EPOCH},
};
#[cfg(feature = "linux-kernel")]
use stela_c_build::linux::Module;
#[cfg(feature = "linux-kernel")]
use stela_c_build::native::hosted;
const SELECTOR: &str = "STELA_NOUVEAU_FIRMWARE_TESTS";
@@ -111,16 +113,16 @@ pub fn tests(linux: &Linux, tests: &mut Tests) {
for file in ["nouveau_firmware_helpers.inc", "source-receipt.json"] {
println!("cargo:rerun-if-changed={}", generated.join(file).display());
}
linux.apply(
linux.environment.apply(
&mut build,
Some(&generated),
&[
&native::drm_includes(&[
"nouveau/include",
"nouveau/include/nvkm",
"nouveau/nvkm",
"nouveau/nvkm/subdev/gsp",
"nouveau",
],
]),
Some(&Module {
name: "nouveau",
file: "drivers/gpu/drm/nouveau/nouveau",