Skip to content

Commit

Permalink
build: ensure memcpy is optimzed in SGX
Browse files Browse the repository at this point in the history
  • Loading branch information
Taowyoo committed Jun 29, 2023
1 parent dcad2b1 commit b21224e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
12 changes: 11 additions & 1 deletion mbedtls-sys/build/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,12 @@ impl BuildConfig {
if FEATURES.have_platform_component("time", "custom") {
writeln!(f, "long long mbedtls_time(long long*);")?;
}
f.write_all(config::SUFFIX.as_bytes())
f.write_all(config::SUFFIX.as_bytes())?;

if features::env_have_target_cfg("env", "sgx") {
f.write_all(config::INLINE_MEMCPY_SUFFIX.as_bytes())?;
}
Ok(())
})
.expect("config.h I/O error");
}
Expand Down Expand Up @@ -105,6 +110,11 @@ impl BuildConfig {
cflags.push("-D_FORTIFY_SOURCE=0".into());
cflags.push("-fno-stack-protector".into());
}
if features::env_have_target_cfg("env", "sgx") {
// In SGX, define memcpy to another string, so could ensure the inline functions added above in config.h
// always take effect. This is necessary because source file may include `string.h` before include `config.h`.
cflags.push("-Dmemcpy=not_memcpy_".into());
}

BuildConfig {
config_h,
Expand Down
14 changes: 14 additions & 0 deletions mbedtls-sys/build/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,3 +444,17 @@ pub const SUFFIX: &'static str = r#"
#include "mbedtls/target_config.h"
#endif
"#;

pub const INLINE_MEMCPY_SUFFIX: &'static str = r#"
// In SGX, use following macro to ensure all calls to memcpy is calling __builtin_memcpy
// so that ensure compiler can optimize it
#define memcpy not_memcpy_
#include <string.h>
#undef memcpy
#ifndef MEMCPY_WRAPPER_
#define MEMCPY_WRAPPER_
static inline void memcpy(void *dst, const void *src, size_t n) {
__builtin_memcpy(dst, src, n);
}
#endif
"#;
2 changes: 1 addition & 1 deletion mbedtls-sys/build/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl Features {
}
}

fn env_have_target_cfg(var: &'static str, value: &'static str) -> bool {
pub(super) fn env_have_target_cfg(var: &'static str, value: &'static str) -> bool {
let env = format!("CARGO_CFG_TARGET_{}", var).to_uppercase().replace("-", "_");
env::var_os(env).map_or(false, |s| s == value)
}
Expand Down

0 comments on commit b21224e

Please sign in to comment.