Skip to content

Commit b5392e7

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 e6f12c8 + 8fbd055 commit b5392e7

File tree

3 files changed

+482
-0
lines changed

3 files changed

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

0 commit comments

Comments
 (0)