Skip to content

Commit b21224e

Browse files
committed
build: ensure memcpy is optimzed in SGX
1 parent dcad2b1 commit b21224e

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

mbedtls-sys/build/build.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,12 @@ impl BuildConfig {
6363
if FEATURES.have_platform_component("time", "custom") {
6464
writeln!(f, "long long mbedtls_time(long long*);")?;
6565
}
66-
f.write_all(config::SUFFIX.as_bytes())
66+
f.write_all(config::SUFFIX.as_bytes())?;
67+
68+
if features::env_have_target_cfg("env", "sgx") {
69+
f.write_all(config::INLINE_MEMCPY_SUFFIX.as_bytes())?;
70+
}
71+
Ok(())
6772
})
6873
.expect("config.h I/O error");
6974
}
@@ -105,6 +110,11 @@ impl BuildConfig {
105110
cflags.push("-D_FORTIFY_SOURCE=0".into());
106111
cflags.push("-fno-stack-protector".into());
107112
}
113+
if features::env_have_target_cfg("env", "sgx") {
114+
// In SGX, define memcpy to another string, so could ensure the inline functions added above in config.h
115+
// always take effect. This is necessary because source file may include `string.h` before include `config.h`.
116+
cflags.push("-Dmemcpy=not_memcpy_".into());
117+
}
108118

109119
BuildConfig {
110120
config_h,

mbedtls-sys/build/config.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,3 +444,17 @@ pub const SUFFIX: &'static str = r#"
444444
#include "mbedtls/target_config.h"
445445
#endif
446446
"#;
447+
448+
pub const INLINE_MEMCPY_SUFFIX: &'static str = r#"
449+
// In SGX, use following macro to ensure all calls to memcpy is calling __builtin_memcpy
450+
// so that ensure compiler can optimize it
451+
#define memcpy not_memcpy_
452+
#include <string.h>
453+
#undef memcpy
454+
#ifndef MEMCPY_WRAPPER_
455+
#define MEMCPY_WRAPPER_
456+
static inline void memcpy(void *dst, const void *src, size_t n) {
457+
__builtin_memcpy(dst, src, n);
458+
}
459+
#endif
460+
"#;

mbedtls-sys/build/features.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ impl Features {
9191
}
9292
}
9393

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

0 commit comments

Comments
 (0)