Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 5ad1b16

Browse files
committed
Auto merge of rust-lang#133944 - ricci009:master, r=<try>
[WIP] Prototype run-make test to check `core::ffi::c_*` types against clang Hello, I have been working on issue rust-lang#133058 for a bit of time now and would love some feedback as I seem to be stuck and not sure if I am approaching this correctly. I currently have the following setup: 1. Get the rust target list 2. Use rust target to query the llvm target 3. Get clang definitions through querying the clang command with llvm target. I only save the necessary defines. Here is an example of the saved info (code can easily be modified to store Width as well): Target: riscv64-unknown-linux-musl __CHAR_BIT__ = 8 __CHAR_UNSIGNED__ = 1 __SIZEOF_DOUBLE__ = 8 __SIZEOF_INT__ = 4 __SIZEOF_LONG__ = 8 __SIZEOF_PTRDIFF_T__ = 8 __SIZEOF_SIZE_T__ = 8 __SIZEOF_FLOAT__ = 4 __SIZEOF_LONG_LONG__ = 8 __SIZEOF_SHORT__ = 2 Target: riscv64-unknown-fuchsia __CHAR_UNSIGNED__ = 1 __SIZEOF_SHORT__ = 2 __CHAR_BIT__ = 8 __SIZEOF_INT__ = 4 __SIZEOF_SIZE_T__ = 8 __SIZEOF_FLOAT__ = 4 __SIZEOF_LONG__ = 8 __SIZEOF_DOUBLE__ = 8 __SIZEOF_PTRDIFF_T__ = 8 __SIZEOF_LONG_LONG__ = 8 - I then save this into a hash map with the following format: <LLVM TARGET, <DEFINE NAME, DEFINE VALUE>> - Ex: <x86_64-unknown-linux-gnu, <__SIZEOF_INT__, 4>> This is where it gets a bit shaky as I have been brainstorming ways to get the available c types in core::ffi to verify the size of the defined types but do not think I have the expertise to do this. For the current implementation I specifically focus on the c_char type (unsigned vs signed). The test is currently failing as there are type mismatches which are expected (issue rust-lang#129945 highlights this). I just do not know how to continue executing tests even with the type mismatches as it creates an error when running the run-make test. Or maybe I am doing something wrong in generating the test? Not too sure but would love your input. Thanks r? `@tgross35` `@jieyouxu` try-job: x86_64-gnu-debug
2 parents 2f348cb + 1b49dbf commit 5ad1b16

File tree

3 files changed

+497
-0
lines changed

3 files changed

+497
-0
lines changed

tests/auxiliary/minicore.rs

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,64 @@
1717
#![feature(no_core, lang_items, rustc_attrs, decl_macro, naked_functions, f16, f128)]
1818
#![allow(unused, improper_ctypes_definitions, internal_features)]
1919
#![feature(asm_experimental_arch)]
20+
#![feature(intrinsics)]
2021
#![no_std]
2122
#![no_core]
2223

24+
/// Vendored from the 'cfg_if' crate
25+
26+
macro_rules! cfg_if {
27+
// match if/else chains with a final `else`
28+
(
29+
$(
30+
if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* }
31+
) else+
32+
else { $( $e_tokens:tt )* }
33+
) => {
34+
cfg_if! {
35+
@__items () ;
36+
$(
37+
(( $i_meta ) ( $( $i_tokens )* )) ,
38+
)+
39+
(() ( $( $e_tokens )* )) ,
40+
}
41+
};
42+
43+
// Internal and recursive macro to emit all the items
44+
//
45+
// Collects all the previous cfgs in a list at the beginning, so they can be
46+
// negated. After the semicolon is all the remaining items.
47+
(@__items ( $( $_:meta , )* ) ; ) => {};
48+
(
49+
@__items ( $( $no:meta , )* ) ;
50+
(( $( $yes:meta )? ) ( $( $tokens:tt )* )) ,
51+
$( $rest:tt , )*
52+
) => {
53+
// Emit all items within one block, applying an appropriate #[cfg]. The
54+
// #[cfg] will require all `$yes` matchers specified and must also negate
55+
// all previous matchers.
56+
#[cfg(all(
57+
$( $yes , )?
58+
not(any( $( $no ),* ))
59+
))]
60+
cfg_if! { @__identity $( $tokens )* }
61+
62+
// Recurse to emit all other items in `$rest`, and when we do so add all
63+
// our `$yes` matchers to the list of `$no` matchers as future emissions
64+
// will have to negate everything we just matched as well.
65+
cfg_if! {
66+
@__items ( $( $no , )* $( $yes , )? ) ;
67+
$( $rest , )*
68+
}
69+
};
70+
71+
// Internal macro to make __apply work out right for different match types,
72+
// because of how macros match/expand stuff.
73+
(@__identity $( $tokens:tt )* ) => {
74+
$( $tokens )*
75+
};
76+
}
77+
2378
// `core` has some exotic `marker_impls!` macro for handling the with-generics cases, but for our
2479
// purposes, just use a simple macro_rules macro.
2580
macro_rules! impl_marker_trait {
@@ -101,10 +156,70 @@ macro_rules! concat {
101156
/* compiler built-in */
102157
};
103158
}
159+
104160
#[rustc_builtin_macro]
105161
#[macro_export]
106162
macro_rules! stringify {
107163
($($t:tt)*) => {
108164
/* compiler built-in */
109165
};
110166
}
167+
168+
#[macro_export]
169+
macro_rules! panic {
170+
($msg:literal) => {
171+
$crate::panic(&$msg)
172+
};
173+
}
174+
175+
#[rustc_intrinsic]
176+
#[rustc_intrinsic_const_stable_indirect]
177+
#[rustc_intrinsic_must_be_overridden]
178+
pub const fn size_of<T>() -> usize {
179+
loop {}
180+
}
181+
182+
#[rustc_intrinsic]
183+
#[rustc_intrinsic_must_be_overridden]
184+
pub const fn abort() -> ! {
185+
loop {}
186+
}
187+
188+
#[lang = "panic"]
189+
#[rustc_const_panic_str]
190+
const fn panic(_expr: &&'static str) -> ! {
191+
abort();
192+
}
193+
194+
#[lang = "eq"]
195+
pub trait PartialEq<Rhs: ?Sized = Self> {
196+
fn eq(&self, other: &Rhs) -> bool;
197+
fn ne(&self, other: &Rhs) -> bool {
198+
!self.eq(other)
199+
}
200+
}
201+
202+
impl PartialEq for usize {
203+
fn eq(&self, other: &usize) -> bool {
204+
(*self) == (*other)
205+
}
206+
}
207+
208+
impl PartialEq for bool {
209+
fn eq(&self, other: &bool) -> bool {
210+
(*self) == (*other)
211+
}
212+
}
213+
214+
#[lang = "not"]
215+
pub trait Not {
216+
type Output;
217+
fn not(self) -> Self::Output;
218+
}
219+
220+
impl Not for bool {
221+
type Output = bool;
222+
fn not(self) -> Self {
223+
!self
224+
}
225+
}
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
//@ needs-force-clang-based-tests
2+
// This test checks that the clang defines for each target allign with the core ffi types defined in
3+
// mod.rs. Therefore each rust target is queried and the clang defines for each target are read and
4+
// compared to the core sizes to verify all types and sizes allign at buildtime.
5+
//
6+
// If this test fails because Rust adds a target that Clang does not support, this target should be
7+
// added to SKIPPED_TARGETS.
8+
9+
use run_make_support::{clang, llvm_components_contain, regex, rfs, rustc};
10+
11+
// It is not possible to run the Rust test-suite on these targets.
12+
const SKIPPED_TARGETS: &[&str] = &[
13+
"wasm32v1-none",
14+
"xtensa-esp32-espidf",
15+
"xtensa-esp32-none-elf",
16+
"xtensa-esp32s2-espidf",
17+
"xtensa-esp32s2-none-elf",
18+
"xtensa-esp32s3-espidf",
19+
"xtensa-esp32s3-none-elf",
20+
];
21+
22+
/// Map from a Rust target to the Clang target if they are not the same.
23+
const MAPPED_TARGETS: &[(&str, &str)] = &[
24+
("aarch64-apple-ios-sim", "aarch64-apple-ios"),
25+
("aarch64-apple-tvos-sim", "aarch64-apple-tvos"),
26+
("aarch64-apple-visionos-sim", "aarch64-apple-visionos"),
27+
("aarch64-apple-watchos-sim", "aarch64-apple-watchos"),
28+
("x86_64-apple-watchos-sim", "x86_64-apple-watchos"),
29+
];
30+
31+
fn main() {
32+
let targets = get_target_list();
33+
34+
let minicore_path = run_make_support::source_root().join("tests/auxiliary/minicore.rs");
35+
36+
regex_mod();
37+
38+
for target in targets.lines() {
39+
if SKIPPED_TARGETS.iter().any(|&to_skip_target| target == to_skip_target) {
40+
continue;
41+
}
42+
43+
// Map the Rust target string to a Clang target string if needed
44+
// Also replace riscv with necessary replacements to match clang
45+
// If neither just use target string
46+
let ctarget = MAPPED_TARGETS
47+
.iter()
48+
.find(|(rtarget, _)| *rtarget == target)
49+
.map(|(_, ctarget)| ctarget.to_string())
50+
.unwrap_or_else(|| {
51+
if target.starts_with("riscv") {
52+
target
53+
.replace("imac", "")
54+
.replace("gc", "")
55+
.replace("imafc", "")
56+
.replace("imc", "")
57+
.replace("ima", "")
58+
.replace("im", "")
59+
.replace("emc", "")
60+
.replace("em", "")
61+
.replace("e-", "-")
62+
.replace("i-", "-")
63+
} else {
64+
target.to_string()
65+
}
66+
});
67+
68+
// Run Clang's preprocessor for the relevant target, printing default macro definitions.
69+
let clang_output =
70+
clang().args(&["-E", "-dM", "-x", "c", "/dev/null", "-target", &ctarget]).run();
71+
72+
let defines = String::from_utf8(clang_output.stdout()).expect("Invalid UTF-8");
73+
74+
let minicore_content = rfs::read_to_string(&minicore_path);
75+
let mut rmake_content = format!(
76+
r#"
77+
#![no_std]
78+
#![no_core]
79+
#![feature(link_cfg)]
80+
#![allow(unused)]
81+
#![crate_type = "rlib"]
82+
83+
/* begin minicore content */
84+
{minicore_content}
85+
/* end minicore content */
86+
87+
#[path = "processed_mod.rs"]
88+
mod ffi;
89+
#[path = "tests.rs"]
90+
mod tests;
91+
"#
92+
);
93+
94+
rmake_content.push_str(&format!(
95+
"
96+
const CLANG_C_CHAR_SIZE: usize = {};
97+
const CLANG_C_CHAR_SIGNED: bool = {};
98+
const CLANG_C_SHORT_SIZE: usize = {};
99+
const CLANG_C_INT_SIZE: usize = {};
100+
const CLANG_C_LONG_SIZE: usize = {};
101+
const CLANG_C_LONGLONG_SIZE: usize = {};
102+
const CLANG_C_FLOAT_SIZE: usize = {};
103+
const CLANG_C_DOUBLE_SIZE: usize = {};
104+
const CLANG_C_SIZE_T_SIZE: usize = {};
105+
const CLANG_C_PTRDIFF_T_SIZE: usize = {};
106+
",
107+
parse_size(&defines, "CHAR"),
108+
char_is_signed(&defines),
109+
parse_size(&defines, "SHORT"),
110+
parse_size(&defines, "INT"),
111+
parse_size(&defines, "LONG"),
112+
parse_size(&defines, "LONG_LONG"),
113+
parse_size(&defines, "FLOAT"),
114+
parse_size(&defines, "DOUBLE"),
115+
parse_size(&defines, "SIZE_T"),
116+
parse_size(&defines, "PTRDIFF_T"),
117+
));
118+
119+
// Generate a target-specific rmake file.
120+
// If type misalignments occur,
121+
// generated rmake file name used to identify the failing target.
122+
let file_name = format!("{}_rmake.rs", target.replace("-", "_").replace(".", "_"));
123+
124+
// Attempt to build the test file for the relevant target.
125+
// Tests use constant evaluation, so running is not necessary.
126+
rfs::write(&file_name, rmake_content);
127+
let rustc_output = rustc()
128+
.arg("-Zunstable-options")
129+
.arg("--emit=metadata")
130+
.arg("--target")
131+
.arg(target)
132+
.arg("-o-")
133+
.arg(&file_name)
134+
.run();
135+
rfs::remove_file(&file_name);
136+
if !rustc_output.status().success() {
137+
panic!("Failed for target {}", target);
138+
}
139+
}
140+
141+
// Cleanup
142+
rfs::remove_file("processed_mod.rs");
143+
}
144+
145+
/// Get a list of available targets for 'rustc'.
146+
fn get_target_list() -> String {
147+
let completed_process = rustc().arg("--print").arg("target-list").run();
148+
String::from_utf8(completed_process.stdout()).expect("error not a string")
149+
}
150+
151+
// Helper to parse size from clang defines
152+
fn parse_size(defines: &str, type_name: &str) -> usize {
153+
let search_pattern = format!("__SIZEOF_{}__ ", type_name.to_uppercase());
154+
for line in defines.lines() {
155+
if line.contains(&search_pattern) {
156+
if let Some(size_str) = line.split_whitespace().last() {
157+
return size_str.parse().unwrap_or(0);
158+
}
159+
}
160+
}
161+
162+
// Only allow CHAR to default to 1
163+
if type_name.to_uppercase() == "CHAR" {
164+
return 1;
165+
}
166+
167+
panic!("Could not find size definition for type: {}", type_name);
168+
}
169+
170+
fn char_is_signed(defines: &str) -> bool {
171+
!defines.lines().any(|line| line.contains("__CHAR_UNSIGNED__"))
172+
}
173+
174+
/// Parse core/ffi/mod.rs to retrieve only necessary macros and type defines
175+
fn regex_mod() {
176+
let mod_path = run_make_support::source_root().join("library/core/src/ffi/mod.rs");
177+
let mut content = rfs::read_to_string(&mod_path);
178+
179+
//remove stability features #![unstable]
180+
let mut re = regex::Regex::new(r"#!?\[(un)?stable[^]]*?\]").unwrap();
181+
content = re.replace_all(&content, "").to_string();
182+
183+
//remove doc features #[doc...]
184+
re = regex::Regex::new(r"#\[doc[^]]*?\]").unwrap();
185+
content = re.replace_all(&content, "").to_string();
186+
187+
//remove lang feature #[lang...]
188+
re = regex::Regex::new(r"#\[lang[^]]*?\]").unwrap();
189+
content = re.replace_all(&content, "").to_string();
190+
191+
//remove non inline modules
192+
re = regex::Regex::new(r".*mod.*;").unwrap();
193+
content = re.replace_all(&content, "").to_string();
194+
195+
//remove use
196+
re = regex::Regex::new(r".*use.*;").unwrap();
197+
content = re.replace_all(&content, "").to_string();
198+
199+
//remove fn fmt {...}
200+
re = regex::Regex::new(r"(?s)fn fmt.*?\{.*?\}").unwrap();
201+
content = re.replace_all(&content, "").to_string();
202+
203+
//rmv impl fmt {...}
204+
re = regex::Regex::new(r"(?s)impl fmt::Debug for.*?\{.*?\}").unwrap();
205+
content = re.replace_all(&content, "").to_string();
206+
207+
let file_name = "processed_mod.rs";
208+
209+
rfs::write(&file_name, content);
210+
}

0 commit comments

Comments
 (0)