From f6e079e898875e795d124cda36ee60e43323e3ac Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Wed, 8 Apr 2020 16:13:27 +0200 Subject: [PATCH] WIP Added default flags to fix alignment. There's an issue with compiling C(++) code on 64-bit CPUs running 32-bit OSes, which have 32-bit-aligned allocators. The resulting binary will use aligned accesses in release mode. See https://github.com/romanz/electrs/issues/226 for an example of such issue. This change adds default flags setting alignment to whatever the pointer alignment is. I realize the limitations of this change such as: * Works in Cargo build scripts only (the major use case for `cc` crate) * Is unnecessary if allocator actually supports 64 bit alingment * Is incorrect if allocator supports smaller alignment than what's pointer width. However, resolving this issue requires either matching on all possible triples, which I don't have the time to implement or somehow fetching the configuration for given triple, which I don't know how to do. This is also an experiment to see if it even helps at all. --- src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 8981448..fc5e30f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1620,6 +1620,24 @@ impl Build { } } + // This won't work outside of build scripts now, but should be helpful already + if let Some(target_ptr_width) = std::env::var("CARGO_CFG_TARGET_POINTER_WIDTH").map_err(|err| if let std::env::VarError::NotUnicode(_) = err { panic!("Invalid encoding of env var CARGO_CFG_TARGET_POINTER_WIDTH") }).ok() { + match cmd.family { + ToolFamily::Clang => { + cmd.args.push(format!("-fnew-alignment={}", target_ptr_width).into()); + cmd.args.push(format!("-fmax-type-align={}", target_ptr_width).into()); + }, + ToolFamily::Gnu => { + cmd.args.push(format!("-mstack-align={}", target_ptr_width).into()); + cmd.args.push(format!("-mdata-align={}", target_ptr_width).into()); + cmd.args.push(format!("-mconst-align={}", target_ptr_width).into()); + }, + ToolFamily::Msvc { .. } => { + // I don't know what needs to be set up here. + }, + } + } + if target.contains("-ios") { // FIXME: potential bug. iOS is always compiled with Clang, but Gcc compiler may be // detected instead.