blob: e724a5fd9ffe2250cb1524f70c1e8b3f6143a21b [file] [log] [blame]
Alex Crichton8e5f0cd2015-09-09 22:46:19 -07001extern crate gcc;
2extern crate syntex_syntax as syntax;
3
Alex Crichton310d6232015-09-10 10:56:31 -07004use std::collections::HashSet;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -07005use std::env;
6use std::fs::File;
7use std::io::BufWriter;
8use std::io::prelude::*;
9use std::path::{Path, PathBuf};
10
Alex Crichton31504842015-09-10 23:43:41 -070011use syntax::abi::Abi;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -070012use syntax::ast;
Alex Crichtona9adfbf2015-09-09 23:21:27 -070013use syntax::attr::{self, ReprAttr};
Alex Crichton31504842015-09-10 23:43:41 -070014use syntax::diagnostic::SpanHandler;
15use syntax::ext::base::SyntaxExtension;
16use syntax::ext::expand;
17use syntax::parse::token::{intern, InternedString};
Alex Crichton8e5f0cd2015-09-09 22:46:19 -070018use syntax::parse::{self, ParseSess};
19use syntax::visit::{self, Visitor};
20
Alex Crichton310d6232015-09-10 10:56:31 -070021macro_rules! t {
22 ($e:expr) => (match $e {
23 Ok(e) => e,
24 Err(e) => panic!("{} failed with {}", stringify!($e), e),
25 })
26}
27
Alex Crichtona9adfbf2015-09-09 23:21:27 -070028struct TestGenerator<'a> {
Alex Crichton310d6232015-09-10 10:56:31 -070029 target: String,
Alex Crichton8e5f0cd2015-09-09 22:46:19 -070030 rust: Box<Write>,
31 c: Box<Write>,
Alex Crichtona9adfbf2015-09-09 23:21:27 -070032 sh: &'a SpanHandler,
Alex Crichton310d6232015-09-10 10:56:31 -070033 structs: HashSet<String>,
Alex Crichton31504842015-09-10 23:43:41 -070034 abi: Abi,
Alex Crichton5a284332015-09-13 23:33:33 -070035 tests: Vec<String>,
Alex Crichton310d6232015-09-10 10:56:31 -070036}
37
38struct StructFinder {
39 structs: HashSet<String>,
40}
41
42impl<'a> TestGenerator<'a> {
Alex Crichton0df7c102015-09-10 16:35:37 -070043 fn defines(&self) -> Vec<&'static str> {
44 let mut ret = Vec::new();
Alex Crichton31504842015-09-10 23:43:41 -070045
46 // Pull in extra goodies on linux
Alex Crichton1cf98ae2015-09-13 11:19:02 -070047 if self.target.contains("unknown-linux-gnu") {
Alex Crichton0df7c102015-09-10 16:35:37 -070048 ret.push("_GNU_SOURCE");
49 }
Alex Crichton31504842015-09-10 23:43:41 -070050
51 // MSVC doesn't have stdalign.h so get alignof ourselves
Alex Crichtonac2bd852015-09-10 17:21:20 -070052 if self.target.contains("msvc") {
53 ret.push("alignof __alignof");
54 }
Alex Crichton31504842015-09-10 23:43:41 -070055
Alex Crichtond3d77922015-09-11 17:03:39 -070056 // android also doesn't have stdalign.h so get alignof ourselves
Alex Crichton8fc95d22015-09-14 11:06:20 -070057 if self.target.contains("android") || self.target.contains("mips") {
Alex Crichtond3d77922015-09-11 17:03:39 -070058 ret.push("alignof __alignof__");
59 }
60
Alex Crichton31504842015-09-10 23:43:41 -070061 // Pull in extra goodies on mingw
62 if self.target.contains("windows") {
63 ret.push("_WIN32_WINNT 0x8000");
64 }
Alex Crichton0df7c102015-09-10 16:35:37 -070065 return ret
66 }
67
Alex Crichton310d6232015-09-10 10:56:31 -070068 fn headers(&self) -> Vec<&'static str> {
Alex Crichtonac2bd852015-09-10 17:21:20 -070069 let mut base = Vec::new();
70
Alex Crichtonf81e3d32015-09-11 15:27:09 -070071 base.extend([
Alex Crichton0df7c102015-09-10 16:35:37 -070072 "errno.h",
73 "fcntl.h",
Alex Crichton0df7c102015-09-10 16:35:37 -070074 "limits.h",
Alex Crichton310d6232015-09-10 10:56:31 -070075 "stddef.h",
76 "stdint.h",
Alex Crichton0df7c102015-09-10 16:35:37 -070077 "stdio.h",
78 "stdlib.h",
Alex Crichton310d6232015-09-10 10:56:31 -070079 "sys/stat.h",
Alex Crichton310d6232015-09-10 10:56:31 -070080 "sys/types.h",
Alex Crichton310d6232015-09-10 10:56:31 -070081 "time.h",
Alex Crichton310d6232015-09-10 10:56:31 -070082 "wchar.h",
Alex Crichtonf81e3d32015-09-11 15:27:09 -070083 ].iter().cloned());
Alex Crichton310d6232015-09-10 10:56:31 -070084
85 if self.target.contains("apple-darwin") {
Alex Crichtone8606192015-09-10 20:19:44 -070086 base.push("mach-o/dyld.h");
Alex Crichton310d6232015-09-10 10:56:31 -070087 base.push("mach/mach_time.h");
88 }
Alex Crichtonac2bd852015-09-10 17:21:20 -070089
Alex Crichtond3d77922015-09-11 17:03:39 -070090 if self.target.contains("unknown-linux") ||
91 self.target.contains("android") {
Alex Crichton310d6232015-09-10 10:56:31 -070092 base.push("linux/if_packet.h");
93 base.push("net/ethernet.h");
94 }
95
Alex Crichtonac2bd852015-09-10 17:21:20 -070096 if self.target.contains("windows") {
Alex Crichton7da9b102015-09-10 20:57:14 -070097 base.push("winsock2.h"); // must be before windows.h
98
99 base.push("direct.h");
100 base.push("io.h");
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700101 base.push("sys/utime.h");
Alex Crichton7da9b102015-09-10 20:57:14 -0700102 base.push("windows.h");
103 base.push("process.h");
104 base.push("ws2ipdef.h");
Alex Crichton31504842015-09-10 23:43:41 -0700105
106 if self.target.contains("gnu") {
107 base.push("stdalign.h");
108 base.push("ws2tcpip.h");
109 }
Alex Crichtonac2bd852015-09-10 17:21:20 -0700110 } else {
Alex Crichton22378822015-09-10 19:59:23 -0700111 base.push("ctype.h");
112 base.push("dirent.h");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700113 base.push("net/if.h");
114 base.push("netdb.h");
115 base.push("netinet/in.h");
116 base.push("netinet/ip.h");
117 base.push("netinet/tcp.h");
118 base.push("pthread.h");
119 base.push("signal.h");
Alex Crichtone8606192015-09-10 20:19:44 -0700120 base.push("string.h");
Alex Crichton22378822015-09-10 19:59:23 -0700121 base.push("sys/file.h");
122 base.push("sys/ioctl.h");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700123 base.push("sys/mman.h");
124 base.push("sys/resource.h");
125 base.push("sys/socket.h");
126 base.push("sys/time.h");
127 base.push("sys/un.h");
Alex Crichton22378822015-09-10 19:59:23 -0700128 base.push("sys/wait.h");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700129 base.push("unistd.h");
Alex Crichton22378822015-09-10 19:59:23 -0700130 base.push("utime.h");
Alex Crichtond3d77922015-09-11 17:03:39 -0700131
132 if self.target.contains("android") {
133 base.push("arpa/inet.h");
134 } else {
135 base.push("glob.h");
136 base.push("ifaddrs.h");
Alex Crichton8fc95d22015-09-14 11:06:20 -0700137 if !self.target.contains("mips") {
138 base.push("stdalign.h");
139 }
Alex Crichtond3d77922015-09-11 17:03:39 -0700140 base.push("sys/sysctl.h");
141 }
Alex Crichtonac2bd852015-09-10 17:21:20 -0700142 }
143
Alex Crichton310d6232015-09-10 10:56:31 -0700144 return base
145 }
146
147 fn rust2c(&self, ty: &str) -> String {
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700148 let windows = self.target.contains("windows");
Alex Crichton310d6232015-09-10 10:56:31 -0700149 match ty {
150 t if t.starts_with("c_") => {
151 match &ty[2..].replace("long", " long")[..] {
152 s if s.starts_with("u") => format!("unsigned {}", &s[1..]),
153 "short" => format!("short"),
154 s if s.starts_with("s") => format!("signed {}", &s[1..]),
155 s => s.to_string(),
156 }
157 }
Alex Crichton31504842015-09-10 23:43:41 -0700158
159 // Just pass all these through, no need for a "struct" prefix
Alex Crichton22378822015-09-10 19:59:23 -0700160 "glob_t" |
161 "FILE" |
162 "DIR" |
163 "fpos_t" => ty.to_string(),
Alex Crichton310d6232015-09-10 10:56:31 -0700164 t if t.starts_with("pthread") => t.to_string(),
165
Alex Crichton31504842015-09-10 23:43:41 -0700166 // Windows uppercase structs don't have `struct` in front, there's a
167 // few special cases for windows, and then otherwise put `struct` in
168 // front of everything.
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700169 t if self.structs.contains(t) => {
170 if windows && ty.chars().next().unwrap().is_uppercase() {
171 t.to_string()
172 } else if windows && t == "stat" {
173 "struct __stat64".to_string()
Alex Crichton7da9b102015-09-10 20:57:14 -0700174 } else if windows && t == "utimbuf" {
175 "struct __utimbuf64".to_string()
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700176 } else {
177 format!("struct {}", t)
178 }
179 }
Alex Crichton310d6232015-09-10 10:56:31 -0700180
Alex Crichton31504842015-09-10 23:43:41 -0700181 // Fixup a few types on windows that don't actually exist.
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700182 "time64_t" if windows => "__time64_t".to_string(),
183 "ssize_t" if windows => "SSIZE_T".to_string(),
Alex Crichton31504842015-09-10 23:43:41 -0700184
Alex Crichton310d6232015-09-10 10:56:31 -0700185 t => t.to_string(),
186 }
187 }
188
189 fn rust2cfield(&self, struct_: &str, field: &str) -> String {
190 match field {
Alex Crichton31504842015-09-10 23:43:41 -0700191 // Our stat *_nsec fields normally don't actually exist but are part
192 // of a timeval struct
Alex Crichton310d6232015-09-10 10:56:31 -0700193 s if s.ends_with("_nsec") && struct_ == "stat" => {
194 if self.target.contains("apple-darwin") {
195 s.replace("_nsec", "spec.tv_nsec")
Alex Crichtond3d77922015-09-11 17:03:39 -0700196 } else if self.target.contains("android") {
197 s.to_string()
Alex Crichton310d6232015-09-10 10:56:31 -0700198 } else {
199 s.replace("e_nsec", ".tv_nsec")
200 }
201 }
202 s => s.to_string(),
203 }
204 }
205
206 fn cfg_list(&self) -> Vec<(&'static str, Option<&'static str>)> {
207 let mut ret = Vec::new();
208 let (arch, target_pointer_width) = if self.target.starts_with("x86_64") {
209 ("x86_64", "64")
210 } else if self.target.starts_with("i686") {
211 ("x86", "32")
Alex Crichtond3d77922015-09-11 17:03:39 -0700212 } else if self.target.starts_with("arm") {
213 ("arm", "32")
Alex Crichton8fc95d22015-09-14 11:06:20 -0700214 } else if self.target.starts_with("mips") {
215 ("mips", "32")
Alex Crichton310d6232015-09-10 10:56:31 -0700216 } else {
217 panic!("unknown arch/pointer width: {}", self.target)
218 };
Alex Crichton1cf98ae2015-09-13 11:19:02 -0700219 let (os, family, env) = if self.target.contains("unknown-linux-gnu") {
Alex Crichton310d6232015-09-10 10:56:31 -0700220 ("linux", "unix", "gnu")
Alex Crichton1cf98ae2015-09-13 11:19:02 -0700221 } else if self.target.contains("unknown-linux-musl") {
222 ("linux", "unix", "musl")
Alex Crichton310d6232015-09-10 10:56:31 -0700223 } else if self.target.contains("apple-darwin") {
224 ("macos", "unix", "")
Alex Crichtonac2bd852015-09-10 17:21:20 -0700225 } else if self.target.contains("windows-msvc") {
226 ("windows", "windows", "msvc")
227 } else if self.target.contains("windows-gnu") {
228 ("windows", "windows", "gnu")
Alex Crichtond3d77922015-09-11 17:03:39 -0700229 } else if self.target.contains("android") {
230 ("android", "unix", "")
Alex Crichton310d6232015-09-10 10:56:31 -0700231 } else {
232 panic!("unknown os/family width: {}", self.target)
233 };
234
235 ret.push((family, None));
236 ret.push(("target_os", Some(os)));
237 ret.push(("target_family", Some(family)));
238 ret.push(("target_arch", Some(arch)));
239 // skip endianness
240 ret.push(("target_pointer_width", Some(target_pointer_width)));
241 ret.push(("target_env", Some(env)));
242
243 return ret
244 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700245}
246
247fn main() {
Alex Crichton310d6232015-09-10 10:56:31 -0700248 // Prep the test generator
249 let target = t!(env::var("TARGET"));
250 let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
251 let rust_out = BufWriter::new(t!(File::create(out.join("all.rs"))));
252 let c_out = BufWriter::new(t!(File::create(out.join("all.c"))));
Alex Crichton16083062015-09-09 22:59:24 -0700253 let sess = ParseSess::new();
Alex Crichton310d6232015-09-10 10:56:31 -0700254 let mut tg = TestGenerator {
255 target: target,
256 rust: Box::new(rust_out),
257 c: Box::new(c_out),
258 sh: &sess.span_diagnostic,
259 structs: HashSet::new(),
Alex Crichton31504842015-09-10 23:43:41 -0700260 abi: Abi::C,
Alex Crichton5a284332015-09-13 23:33:33 -0700261 tests: Vec::new(),
Alex Crichton310d6232015-09-10 10:56:31 -0700262 };
263
264 // Parse the libc crate
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700265 let src = Path::new("../src/lib.rs");
266 let cfg = Vec::new();
Alex Crichton31504842015-09-10 23:43:41 -0700267 let krate = parse::parse_crate_from_file(src, cfg, &sess);
268
269 // expand macros
270 let ecfg = expand::ExpansionConfig::default("libc".to_string());
271 let exts = vec![
272 (intern("macro_rules"), SyntaxExtension::MacroRulesTT),
273 ];
274 let mut krate = expand::expand_crate(&sess, ecfg, Vec::new(),
275 exts, &mut Vec::new(), krate);
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700276
Alex Crichton310d6232015-09-10 10:56:31 -0700277 // Strip the crate down to just what's configured for our target
278 for (k, v) in tg.cfg_list() {
279 let s = InternedString::new;
280 krate.config.push(match v {
281 Some(v) => attr::mk_name_value_item_str(s(k), s(v)),
282 None => attr::mk_word_item(s(k)),
283 });
284 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700285 let mut gated_cfgs = Vec::new();
286 let krate = syntax::config::strip_unconfigured_items(&sess.span_diagnostic,
287 krate,
288 &mut gated_cfgs);
289
Alex Crichton310d6232015-09-10 10:56:31 -0700290 // Probe the crate to find all structs (used to convert type names to names
291 // in C).
292 let mut structs = StructFinder {
293 structs: HashSet::new(),
294 };
295 visit::walk_crate(&mut structs, &krate);
296 tg.structs = structs.structs;
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700297
Alex Crichton0df7c102015-09-10 16:35:37 -0700298 // Prep the C file by emitting header stuff
299 for define in tg.defines() {
300 t!(writeln!(tg.c, "#define {}", define));
301 }
Alex Crichton310d6232015-09-10 10:56:31 -0700302 for header in tg.headers() {
303 t!(writeln!(tg.c, "#include <{}>", header));
Alex Crichton16083062015-09-09 22:59:24 -0700304 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700305
306 // Walk the crate, emitting test cases for everything found
Alex Crichton310d6232015-09-10 10:56:31 -0700307 visit::walk_crate(&mut tg, &krate);
Alex Crichton5a284332015-09-13 23:33:33 -0700308 tg.emit_run_all();
Alex Crichton16083062015-09-09 22:59:24 -0700309
Alex Crichton310d6232015-09-10 10:56:31 -0700310 // Compile our C shim to be linked into tests
Alex Crichtonac2bd852015-09-10 17:21:20 -0700311 let mut cfg = gcc::Config::new();
312 cfg.file(out.join("all.c"));
313
314 if tg.target.contains("msvc") {
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700315 cfg.flag("/W3").flag("/Wall").flag("/WX")
316 .flag("/wd4820") // weird warning about adding padding?
Alex Crichton7da9b102015-09-10 20:57:14 -0700317 .flag("/wd4100") // don't warn about unused parameters
318 .flag("/wd4996"); // don't warn about deprecated functions
Alex Crichtonac2bd852015-09-10 17:21:20 -0700319 } else {
Alex Crichtonb01a8cc2015-09-10 17:37:22 -0700320 cfg.flag("-Wall").flag("-Wextra").flag("-Werror")
Alex Crichton6d3cfdb2015-09-15 14:53:01 -0700321 .flag("-Wno-unused-parameter")
322 .flag("-Wno-type-limits");
Alex Crichtonac2bd852015-09-10 17:21:20 -0700323 }
324
325 drop(tg);
326 cfg.compile("liball.a");
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700327}
328
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700329impl<'a> TestGenerator<'a> {
330 fn test_type(&mut self, ty: &str) {
Alex Crichton310d6232015-09-10 10:56:31 -0700331 match ty {
Alex Crichtond3d77922015-09-11 17:03:39 -0700332 // sighandler_t is crazy across platforms
Alex Crichton310d6232015-09-10 10:56:31 -0700333 "sighandler_t" => return,
Alex Crichtond3d77922015-09-11 17:03:39 -0700334
335 // Not actually defined on android, but it's not hurting anyone
336 "in_port_t" if self.target.contains("android") => return,
Alex Crichton310d6232015-09-10 10:56:31 -0700337 _ => {}
338 }
Alex Crichton22378822015-09-10 19:59:23 -0700339 let c = self.rust_ty_to_c_ty(ty);
Alex Crichton310d6232015-09-10 10:56:31 -0700340 self.test_size_align(ty, &c);
Alex Crichton6d3cfdb2015-09-15 14:53:01 -0700341 self.test_sign(ty, &c);
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700342 }
Alex Crichton16083062015-09-09 22:59:24 -0700343
Alex Crichton3e5155b2015-09-09 23:46:19 -0700344 fn test_struct(&mut self, ty: &str, s: &ast::StructDef) {
Alex Crichton22378822015-09-10 19:59:23 -0700345 let cty = self.rust_ty_to_c_ty(ty);
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700346 self.test_size_align(ty, &cty);
Alex Crichton3e5155b2015-09-09 23:46:19 -0700347
Alex Crichton5a284332015-09-13 23:33:33 -0700348 self.tests.push(format!("field_offset_size_{}", ty));
Alex Crichton310d6232015-09-10 10:56:31 -0700349 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700350 fn field_offset_size_{ty}() {{
Alex Crichton5a284332015-09-13 23:33:33 -0700351 println!("verifying struct {ty}");
Alex Crichton310d6232015-09-10 10:56:31 -0700352 "#, ty = ty));
Alex Crichton3e5155b2015-09-09 23:46:19 -0700353 for field in s.fields.iter() {
354 let name = match field.node.kind {
355 ast::NamedField(name, ast::Public) => name,
356 ast::NamedField(_, ast::Inherited) => continue,
357 ast::UnnamedField(..) => panic!("no tuple structs in FFI"),
358 };
359
Alex Crichton310d6232015-09-10 10:56:31 -0700360 let cfield = self.rust2cfield(ty, &name.to_string());
Alex Crichton3e5155b2015-09-09 23:46:19 -0700361
Alex Crichton310d6232015-09-10 10:56:31 -0700362 t!(writeln!(self.c, r#"
Alex Crichton671376b2015-09-10 17:39:03 -0700363 uint64_t __test_offset_{ty}_{rust_field}(void) {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700364 return offsetof({cty}, {c_field});
365 }}
Alex Crichton671376b2015-09-10 17:39:03 -0700366 uint64_t __test_size_{ty}_{rust_field}(void) {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700367 {cty}* foo = NULL;
368 return sizeof(foo->{c_field});
369 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700370 "#, ty = ty, cty = cty, rust_field = name, c_field = cfield));
371 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700372 extern {{
373 fn __test_offset_{ty}_{field}() -> u64;
374 fn __test_size_{ty}_{field}() -> u64;
375 }}
376 unsafe {{
377 let foo = 0 as *const {ty};
378 same(offset_of!({ty}, {field}),
379 __test_offset_{ty}_{field}(),
380 "field offset {field} of {ty}");
381 same(mem::size_of_val(&(*foo).{field}) as u64,
382 __test_size_{ty}_{field}(),
383 "field size {field} of {ty}");
384 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700385 "#, ty = ty, field = name));
Alex Crichton3e5155b2015-09-09 23:46:19 -0700386 }
Alex Crichton310d6232015-09-10 10:56:31 -0700387 t!(writeln!(self.rust, r#"
Alex Crichton3e5155b2015-09-09 23:46:19 -0700388 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700389 "#));
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700390 }
391
392 fn test_size_align(&mut self, rust: &str, c: &str) {
Alex Crichton310d6232015-09-10 10:56:31 -0700393 t!(writeln!(self.c, r#"
Alex Crichton671376b2015-09-10 17:39:03 -0700394 uint64_t __test_size_{ty}(void) {{ return sizeof({cty}); }}
395 uint64_t __test_align_{ty}(void) {{ return alignof({cty}); }}
Alex Crichton310d6232015-09-10 10:56:31 -0700396 "#, ty = rust, cty = c));
397 t!(writeln!(self.rust, r#"
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700398 fn size_align_{ty}() {{
Alex Crichton16083062015-09-09 22:59:24 -0700399 extern {{
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700400 fn __test_size_{ty}() -> u64;
401 fn __test_align_{ty}() -> u64;
Alex Crichton16083062015-09-09 22:59:24 -0700402 }}
Alex Crichton5a284332015-09-13 23:33:33 -0700403 println!("verifying type {ty} align/size");
Alex Crichton16083062015-09-09 22:59:24 -0700404 unsafe {{
Alex Crichton3e5155b2015-09-09 23:46:19 -0700405 same(mem::size_of::<{ty}>() as u64,
Alex Crichton5a284332015-09-13 23:33:33 -0700406 __test_size_{ty}(), "{ty} size");
Alex Crichtonc8b895c2015-09-10 13:24:15 -0700407 same(align::<{ty}>() as u64,
Alex Crichton5a284332015-09-13 23:33:33 -0700408 __test_align_{ty}(), "{ty} align");
Alex Crichton16083062015-09-09 22:59:24 -0700409 }}
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700410 }}
Alex Crichton310d6232015-09-10 10:56:31 -0700411 "#, ty = rust));
Alex Crichton5a284332015-09-13 23:33:33 -0700412 self.tests.push(format!("size_align_{}", rust));
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700413 }
414
Alex Crichton6d3cfdb2015-09-15 14:53:01 -0700415 fn test_sign(&mut self, rust: &str, c: &str) {
416 match c {
417 "float" |
418 "double" => return,
419 _ => {}
420 }
421 t!(writeln!(self.c, r#"
422 uint32_t __test_signed_{ty}(void) {{
423 return ((({cty}) -1) < 0);
424 }}
425 "#, ty = rust, cty = c));
426 t!(writeln!(self.rust, r#"
427 fn sign_{ty}() {{
428 extern {{
429 fn __test_signed_{ty}() -> u32;
430 }}
431 println!("verifying type {ty} sign");
432 unsafe {{
433 same(((!(0 as {ty})) < (0 as {ty})) as u32,
434 __test_signed_{ty}(), "{ty} signed");
435 }}
436 }}
437 "#, ty = rust));
438 self.tests.push(format!("sign_{}", rust));
439 }
440
Alex Crichton22378822015-09-10 19:59:23 -0700441 fn rust_ty_to_c_ty(&self, mut rust_ty: &str) -> String {
442 let mut cty = self.rust2c(&rust_ty.replace("*mut ", "")
443 .replace("*const ", ""));
444 while rust_ty.starts_with("*") {
445 if rust_ty.starts_with("*const") {
446 cty = format!("const {}*", cty);
447 rust_ty = &rust_ty[7..];
448 } else {
449 cty = format!("{}*", cty);
450 rust_ty = &rust_ty[5..];
451 }
452 }
453 return cty
454 }
455
Alex Crichton0df7c102015-09-10 16:35:37 -0700456 fn test_const(&mut self, name: &str, rust_ty: &str) {
Alex Crichton31504842015-09-10 23:43:41 -0700457 let mingw = self.target.contains("windows-gnu");
458
459 // Apparently these don't exist in mingw headers?
460 match name {
461 "MEM_RESET_UNDO" |
462 "FILE_ATTRIBUTE_NO_SCRUB_DATA" |
463 "FILE_ATTRIBUTE_INTEGRITY_STREAM" |
464 "ERROR_NOTHING_TO_TERMINATE" if mingw => return,
465 _ => {}
466 }
467
Alex Crichton22378822015-09-10 19:59:23 -0700468 let cty = self.rust_ty_to_c_ty(rust_ty);
Alex Crichton31504842015-09-10 23:43:41 -0700469
470 // SIG_IGN has weird types on platforms, just worry about it as a size_t
Alex Crichton0df7c102015-09-10 16:35:37 -0700471 let cast = if name == "SIG_IGN" {"(size_t)"} else {""};
Alex Crichton31504842015-09-10 23:43:41 -0700472
Alex Crichton0df7c102015-09-10 16:35:37 -0700473 t!(writeln!(self.c, r#"
Alex Crichton13a6f2d2015-09-10 18:10:58 -0700474 int __test_const_{name}({cty} *outptr) {{
475 *outptr = {cast}({name});
476 return 1;
Alex Crichtone7afdd82015-09-10 17:15:20 -0700477 }}
Alex Crichton0df7c102015-09-10 16:35:37 -0700478 "#, name = name, cast = cast, cty = cty));
479 t!(writeln!(self.rust, r#"
Alex Crichton0df7c102015-09-10 16:35:37 -0700480 fn const_{name}() {{
481 extern {{
Alex Crichtone7afdd82015-09-10 17:15:20 -0700482 fn __test_const_{name}(out: *mut {ty}) -> c_int;
Alex Crichton0df7c102015-09-10 16:35:37 -0700483 }}
Alex Crichton5a284332015-09-13 23:33:33 -0700484 println!("verifying const {name} value");
Alex Crichton0df7c102015-09-10 16:35:37 -0700485 unsafe {{
Alex Crichtone7afdd82015-09-10 17:15:20 -0700486 let mut o = mem::zeroed();
487 if __test_const_{name}(&mut o) == 0 {{
Alex Crichton5a284332015-09-13 23:33:33 -0700488 panic!("{name} not defined");
Alex Crichtone7afdd82015-09-10 17:15:20 -0700489 }} else {{
Alex Crichton5a284332015-09-13 23:33:33 -0700490 same({name}, o, "{name} value");
Alex Crichtone7afdd82015-09-10 17:15:20 -0700491 }}
Alex Crichton0df7c102015-09-10 16:35:37 -0700492 }}
493 }}
494 "#, ty = rust_ty, name = name));
Alex Crichton5a284332015-09-13 23:33:33 -0700495 self.tests.push(format!("const_{}", name));
Alex Crichton0df7c102015-09-10 16:35:37 -0700496 }
497
Alex Crichton7da9b102015-09-10 20:57:14 -0700498 fn test_extern_fn(&mut self, name: &str, cname: &str,
499 args: &[String], ret: &str,
Alex Crichton31504842015-09-10 23:43:41 -0700500 variadic: bool, abi: Abi) {
Alex Crichton22378822015-09-10 19:59:23 -0700501 match name {
502 // manually verified
503 "execv" |
504 "execve" |
505 "execvp" |
Alex Crichton7da9b102015-09-10 20:57:14 -0700506 "execvpe" |
Alex Crichton22378822015-09-10 19:59:23 -0700507 "glob" |
508 "getrlimit" |
509 "setrlimit" |
Alex Crichtone8606192015-09-10 20:19:44 -0700510 "signal" |
Alex Crichton22378822015-09-10 19:59:23 -0700511 "getopt" => return,
512 _ => {}
513 }
514 let args = if args.len() == 0 && !variadic {
515 "void".to_string()
516 } else {
517 args.iter().map(|a| self.rust_ty_to_c_ty(a)).collect::<Vec<_>>()
518 .connect(", ") + if variadic {", ..."} else {""}
519 };
520 let cret = self.rust_ty_to_c_ty(ret);
Alex Crichton31504842015-09-10 23:43:41 -0700521 let abi = match abi {
522 Abi::C => "",
523 Abi::Stdcall => "__stdcall ",
524 Abi::System if self.target.contains("i686-pc-windows") => {
525 "__stdcall "
526 }
527 Abi::System => "",
528 a => panic!("unknown ABI: {}", a),
529 };
Alex Crichton22378822015-09-10 19:59:23 -0700530 t!(writeln!(self.c, r#"
Alex Crichton31504842015-09-10 23:43:41 -0700531 {ret} ({abi}*__test_fn_{name}(void))({args}) {{
Alex Crichton7da9b102015-09-10 20:57:14 -0700532 return {cname};
Alex Crichton22378822015-09-10 19:59:23 -0700533 }}
Alex Crichton31504842015-09-10 23:43:41 -0700534 "#, name = name, cname = cname, args = args, ret = cret, abi = abi));
Alex Crichton22378822015-09-10 19:59:23 -0700535 t!(writeln!(self.rust, r#"
Alex Crichton22378822015-09-10 19:59:23 -0700536 fn fn_{name}() {{
537 extern {{
538 fn __test_fn_{name}() -> size_t;
539 }}
Alex Crichton5a284332015-09-13 23:33:33 -0700540 println!("verifying function {name} pointer");
Alex Crichton22378822015-09-10 19:59:23 -0700541 unsafe {{
542 same({name} as usize,
Alex Crichton5a284332015-09-13 23:33:33 -0700543 __test_fn_{name}() as usize,
544 "{name} function pointer");
Alex Crichton22378822015-09-10 19:59:23 -0700545 }}
546 }}
547 "#, name = name));
Alex Crichton5a284332015-09-13 23:33:33 -0700548 self.tests.push(format!("fn_{}", name));
Alex Crichton22378822015-09-10 19:59:23 -0700549 }
550
551 fn assert_no_generics(&self, _i: ast::Ident, generics: &ast::Generics) {
552 assert!(generics.lifetimes.len() == 0);
553 assert!(generics.ty_params.len() == 0);
554 assert!(generics.where_clause.predicates.len() == 0);
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700555 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700556
557 fn ty2name(&self, ty: &ast::Ty) -> String {
558 match ty.node {
559 ast::TyPath(_, ref path) => {
560 path.segments.last().unwrap().identifier.to_string()
561 }
562 ast::TyPtr(ref t) => {
563 format!("*{} {}", match t.mutbl {
564 ast::MutImmutable => "const",
565 ast::MutMutable => "mut",
566 }, self.ty2name(&t.ty))
567 }
Alex Crichton22378822015-09-10 19:59:23 -0700568 ast::TyBareFn(ref t) => {
569 assert!(t.lifetimes.len() == 0);
570 let (ret, mut args, variadic) = self.decl2rust(&t.decl);
571 assert!(!variadic);
572 if args.len() == 0 {
573 args.push("void".to_string());
574 }
575 format!("{}(*)({})", ret, args.connect(", "))
576 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700577 _ => panic!("unknown ty {:?}", ty),
578 }
579 }
Alex Crichton22378822015-09-10 19:59:23 -0700580
581 fn decl2rust(&self, decl: &ast::FnDecl) -> (String, Vec<String>, bool) {
582 let args = decl.inputs.iter().map(|arg| {
583 self.ty2name(&arg.ty)
584 }).collect::<Vec<_>>();
585 let ret = match decl.output {
586 ast::NoReturn(..) |
587 ast::DefaultReturn(..) => "void".to_string(),
588 ast::Return(ref t) => self.ty2name(t),
589 };
590 (ret, args, decl.variadic)
591 }
Alex Crichton5a284332015-09-13 23:33:33 -0700592
593 fn emit_run_all(&mut self) {
594 t!(writeln!(self.rust, "
595 fn run_all() {{
596 "));
597 for test in self.tests.iter() {
598 if test.starts_with("fn_") {
599 // FIXME: weird dllimport issues with windows?
600 t!(writeln!(self.rust, "if cfg!(not(windows)) {{ {}(); }}",
601 test));
602 } else {
603 t!(writeln!(self.rust, "{}();", test));
604 }
605 }
606 t!(writeln!(self.rust, "
607 }}
608 "));
609 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700610}
611
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700612impl<'a, 'v> Visitor<'v> for TestGenerator<'a> {
Alex Crichton22378822015-09-10 19:59:23 -0700613 fn visit_item(&mut self, i: &'v ast::Item) {
Alex Crichton31504842015-09-10 23:43:41 -0700614 let prev_abi = self.abi;
Alex Crichton22378822015-09-10 19:59:23 -0700615 match i.node {
616 ast::ItemTy(_, ref generics) => {
617 self.assert_no_generics(i.ident, generics);
618 self.test_type(&i.ident.to_string());
619 }
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700620
Alex Crichton22378822015-09-10 19:59:23 -0700621 ast::ItemStruct(ref s, ref generics) => {
622 self.assert_no_generics(i.ident, generics);
623 let is_c = i.attrs.iter().any(|a| {
Alex Crichtona9adfbf2015-09-09 23:21:27 -0700624 attr::find_repr_attrs(self.sh, a).iter().any(|a| {
625 *a == ReprAttr::ReprExtern
626 })
Alex Crichton22378822015-09-10 19:59:23 -0700627 });
628 if !is_c {
629 panic!("{} is not marked #[repr(C)]", i.ident);
630 }
631 self.test_struct(&i.ident.to_string(), s);
632 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700633
Alex Crichton22378822015-09-10 19:59:23 -0700634 ast::ItemConst(ref ty, _) => {
635 let ty = self.ty2name(ty);
636 self.test_const(&i.ident.to_string(), &ty);
637 }
Alex Crichton0df7c102015-09-10 16:35:37 -0700638
Alex Crichton31504842015-09-10 23:43:41 -0700639 ast::ItemForeignMod(ref fm) => {
640 self.abi = fm.abi;
641 }
642
Alex Crichton22378822015-09-10 19:59:23 -0700643 _ => {}
644 }
Alex Crichton31504842015-09-10 23:43:41 -0700645 visit::walk_item(self, i);
646 self.abi = prev_abi;
Alex Crichton22378822015-09-10 19:59:23 -0700647 }
648
649 fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) {
650 match i.node {
651 ast::ForeignItemFn(ref decl, ref generics) => {
652 self.assert_no_generics(i.ident, generics);
653 let (ret, args, variadic) = self.decl2rust(decl);
Alex Crichton7da9b102015-09-10 20:57:14 -0700654 let cname = match attr::first_attr_value_str_by_name(&i.attrs,
655 "link_name") {
656 Some(ref i) if !i.to_string().contains("$") => {
657 i.to_string()
658 }
659 _ => i.ident.to_string(),
660 };
Alex Crichton31504842015-09-10 23:43:41 -0700661 let abi = self.abi;
Alex Crichton7da9b102015-09-10 20:57:14 -0700662 self.test_extern_fn(&i.ident.to_string(), &cname, &args, &ret,
Alex Crichton31504842015-09-10 23:43:41 -0700663 variadic, abi);
Alex Crichton22378822015-09-10 19:59:23 -0700664 }
665 ast::ForeignItemStatic(_, _) => {
666 }
667 }
668 visit::walk_foreign_item(self, i)
669 }
Alex Crichton8e5f0cd2015-09-09 22:46:19 -0700670}
Alex Crichton310d6232015-09-10 10:56:31 -0700671
672impl<'v> Visitor<'v> for StructFinder {
Alex Crichton22378822015-09-10 19:59:23 -0700673 fn visit_item(&mut self, i: &'v ast::Item) {
674 match i.node {
675 ast::ItemStruct(..) => {
676 self.structs.insert(i.ident.to_string());
677 }
678 ast::ItemEnum(..) => {
679 self.structs.insert(i.ident.to_string());
680 }
Alex Crichton310d6232015-09-10 10:56:31 -0700681
Alex Crichton22378822015-09-10 19:59:23 -0700682 _ => {}
683 }
684 visit::walk_item(self, i)
685 }
Alex Crichton310d6232015-09-10 10:56:31 -0700686}