Skip to content

Commit 52af267

Browse files
committed
Auto merge of rust-lang#133944 - ricci009:master, r=<try>
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 6ac8878 + a88bcbe commit 52af267

File tree

3 files changed

+498
-0
lines changed

3 files changed

+498
-0
lines changed

tests/auxiliary/minicore.rs

+115
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+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
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, regex, rfs, rustc, serde_json};
10+
use serde_json::Value;
11+
12+
// It is not possible to run the Rust test-suite on these targets.
13+
const SKIPPED_TARGETS: &[&str] = &[
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+
"csky-unknown-linux-gnuabiv2",
21+
"csky-unknown-linux-gnuabiv2hf",
22+
];
23+
24+
const MAPPED_TARGETS: &[(&str, &str)] = &[
25+
("armv5te-unknown-linux-uclibcgnueabi", "armv5te-unknown-linux"),
26+
("mips-unknown-linux-uclibc", "mips-unknown-linux"),
27+
("mipsel-unknown-linux-uclibc", "mips-unknown-linux"),
28+
("powerpc-unknown-linux-gnuspe", "powerpc-unknown-linux-gnu"),
29+
("powerpc-unknown-linux-muslspe", "powerpc-unknown-linux-musl"),
30+
("x86_64-unknown-l4re-uclibc", "x86_64-unknown-l4re"),
31+
];
32+
33+
fn main() {
34+
let minicore_path = run_make_support::source_root().join("tests/auxiliary/minicore.rs");
35+
36+
preprocess_core_ffi();
37+
38+
let targets_json =
39+
rustc().arg("--print").arg("all-target-specs-json").arg("-Z").arg("unstable-options").run();
40+
let targets_json_str =
41+
String::from_utf8(targets_json.stdout().to_vec()).expect("error not a string");
42+
43+
let j: Value = serde_json::from_str(&targets_json_str).unwrap();
44+
for (target, v) in j.as_object().unwrap() {
45+
let llvm_target = &v["llvm-target"].as_str().unwrap();
46+
47+
if SKIPPED_TARGETS.iter().any(|&to_skip_target| target == to_skip_target) {
48+
continue;
49+
}
50+
51+
// Create a new variable to hold either the mapped target or original llvm_target
52+
let target_to_use = MAPPED_TARGETS
53+
.iter()
54+
.find(|&&(from, _)| from == *llvm_target)
55+
.map(|&(_, to)| to)
56+
.unwrap_or(llvm_target);
57+
58+
// Run Clang's preprocessor for the relevant target, printing default macro definitions.
59+
let clang_output =
60+
clang().args(&["-E", "-dM", "-x", "c", "/dev/null", "-target", &target_to_use]).run();
61+
62+
let defines = String::from_utf8(clang_output.stdout()).expect("Invalid UTF-8");
63+
64+
let minicore_content = rfs::read_to_string(&minicore_path);
65+
let mut rmake_content = format!(
66+
r#"
67+
#![no_std]
68+
#![no_core]
69+
#![feature(link_cfg)]
70+
#![allow(unused)]
71+
#![crate_type = "rlib"]
72+
73+
/* begin minicore content */
74+
{minicore_content}
75+
/* end minicore content */
76+
77+
#[path = "processed_mod.rs"]
78+
mod ffi;
79+
#[path = "tests.rs"]
80+
mod tests;
81+
"#
82+
);
83+
84+
rmake_content.push_str(&format!(
85+
"
86+
const CLANG_C_CHAR_SIZE: usize = {};
87+
const CLANG_C_CHAR_SIGNED: bool = {};
88+
const CLANG_C_SHORT_SIZE: usize = {};
89+
const CLANG_C_INT_SIZE: usize = {};
90+
const CLANG_C_LONG_SIZE: usize = {};
91+
const CLANG_C_LONGLONG_SIZE: usize = {};
92+
const CLANG_C_FLOAT_SIZE: usize = {};
93+
const CLANG_C_DOUBLE_SIZE: usize = {};
94+
const CLANG_C_SIZE_T_SIZE: usize = {};
95+
const CLANG_C_PTRDIFF_T_SIZE: usize = {};
96+
",
97+
parse_size(&defines, "CHAR"),
98+
char_is_signed(&defines),
99+
parse_size(&defines, "SHORT"),
100+
parse_size(&defines, "INT"),
101+
parse_size(&defines, "LONG"),
102+
parse_size(&defines, "LONG_LONG"),
103+
parse_size(&defines, "FLOAT"),
104+
parse_size(&defines, "DOUBLE"),
105+
parse_size(&defines, "SIZE_T"),
106+
parse_size(&defines, "PTRDIFF_T"),
107+
));
108+
109+
// Generate a target-specific rmake file.
110+
// If type misalignments occur,
111+
// generated rmake file name used to identify the failing target.
112+
let file_name = format!("{}_rmake.rs", target.replace("-", "_").replace(".", "_"));
113+
114+
// Attempt to build the test file for the relevant target.
115+
// Tests use constant evaluation, so running is not necessary.
116+
rfs::write(&file_name, rmake_content);
117+
let rustc_output = rustc()
118+
.arg("-Zunstable-options")
119+
.arg("--emit=metadata")
120+
.arg("--target")
121+
.arg(target)
122+
.arg("-o-")
123+
.arg(&file_name)
124+
.run();
125+
rfs::remove_file(&file_name);
126+
if !rustc_output.status().success() {
127+
panic!("Failed for target {}", target);
128+
}
129+
}
130+
131+
// Cleanup
132+
rfs::remove_file("processed_mod.rs");
133+
}
134+
135+
// Helper to parse size from clang defines
136+
fn parse_size(defines: &str, type_name: &str) -> usize {
137+
let search_pattern = format!("__SIZEOF_{}__ ", type_name.to_uppercase());
138+
for line in defines.lines() {
139+
if line.contains(&search_pattern) {
140+
if let Some(size_str) = line.split_whitespace().last() {
141+
return size_str.parse().unwrap_or(0);
142+
}
143+
}
144+
}
145+
146+
// Only allow CHAR to default to 1
147+
if type_name.to_uppercase() == "CHAR" {
148+
return 1;
149+
}
150+
151+
panic!("Could not find size definition for type: {}", type_name);
152+
}
153+
154+
fn char_is_signed(defines: &str) -> bool {
155+
!defines.lines().any(|line| line.contains("__CHAR_UNSIGNED__"))
156+
}
157+
158+
/// Parse core/ffi/mod.rs to retrieve only necessary macros and type defines
159+
fn preprocess_core_ffi() {
160+
let mod_path = run_make_support::source_root().join("library/core/src/ffi/mod.rs");
161+
let mut content = rfs::read_to_string(&mod_path);
162+
163+
//remove stability features #![unstable]
164+
let mut re = regex::Regex::new(r"#!?\[(un)?stable[^]]*?\]").unwrap();
165+
content = re.replace_all(&content, "").to_string();
166+
167+
//remove doc features #[doc...]
168+
re = regex::Regex::new(r"#\[doc[^]]*?\]").unwrap();
169+
content = re.replace_all(&content, "").to_string();
170+
171+
//remove lang feature #[lang...]
172+
re = regex::Regex::new(r"#\[lang[^]]*?\]").unwrap();
173+
content = re.replace_all(&content, "").to_string();
174+
175+
//remove non inline modules
176+
re = regex::Regex::new(r".*mod.*;").unwrap();
177+
content = re.replace_all(&content, "").to_string();
178+
179+
//remove use
180+
re = regex::Regex::new(r".*use.*;").unwrap();
181+
content = re.replace_all(&content, "").to_string();
182+
183+
//remove fn fmt {...}
184+
re = regex::Regex::new(r"(?s)fn fmt.*?\{.*?\}").unwrap();
185+
content = re.replace_all(&content, "").to_string();
186+
187+
//rmv impl fmt {...}
188+
re = regex::Regex::new(r"(?s)impl fmt::Debug for.*?\{.*?\}").unwrap();
189+
content = re.replace_all(&content, "").to_string();
190+
191+
let file_name = "processed_mod.rs";
192+
193+
rfs::write(&file_name, content);
194+
}

0 commit comments

Comments
 (0)