Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions cargo-sgx/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,15 +301,13 @@ fn create_enclave_so(
if enclave_dir_script.exists() {
Some(enclave_dir_script)
} else {
// Generate default version script if needed
let default_script = output
.parent()
.unwrap_or(Path::new("."))
.join(ENCLAVE_LDS_FILE);
if !default_script.exists() {
create_version_script(&default_script)?;
}
Some(default_script)
// Generate default version script in the enclave directory (where Cargo.toml is located)
println!(
"Creating default {ENCLAVE_LDS_FILE} in {}",
enclave_dir.display()
);
create_version_script(&enclave_dir_script)?;
Some(enclave_dir_script)
}
};

Expand Down Expand Up @@ -347,6 +345,7 @@ fn create_version_script(path: &Path) -> Result<()> {
g_global_data;
enclave_entry;
g_peak_heap_used;
g_peak_rsrv_mem_committed;
local:
*;
};
Expand Down Expand Up @@ -549,6 +548,7 @@ fn create_enclave_lds(dir: &Path, force: bool) -> Result<()> {
return Ok(());
}

println!("Creating {ENCLAVE_LDS_FILE}...");
create_version_script(&path)?;
Ok(())
}
Expand Down
16 changes: 12 additions & 4 deletions samples/hello-rust/Makefile
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
# Paths
SGX_SDK ?= /opt/sgxsdk
DEBUG := 0
ifeq ($(DEBUG), 0)
PROFILE := release
CARGO_FLAGS := --release
else
PROFILE := debug
export SGX_DEBUG := 1
endif
SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/release/enclave.so
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/$(PROFILE)/enclave.so
Signed_Enclave := bin/enclave.signed.so
Enclave_Config := enclave/Enclave.config.xml
Enclave_Key := enclave/Enclave_private.pem
App_Binary := app/target/release/app
App_Binary := app/target/$(PROFILE)/app

.PHONY: all build build-enclave build-app sign clean run

Expand All @@ -15,11 +23,11 @@ build: build-enclave build-app

build-enclave:
@echo "Building enclave (including .so generation)..."
cd enclave && cargo sgx build --release
cd enclave && cargo sgx build $(CARGO_FLAGS)

build-app:
@echo "Building app..."
cd app && cargo build --release
cd app && cargo build $(CARGO_FLAGS)
@echo "Copying app binary to bin/..."
@cp $(App_Binary) bin/

Expand Down
45 changes: 45 additions & 0 deletions samples/hello-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,51 @@ Remove all build artifacts:
make clean
```

### Debug with sgx-gdb

The Intel SGX SDK provides `sgx-gdb`, a GDB extension for debugging SGX enclaves.

#### Build for Debugging

**Important**: To use the debugger, you must build with debug symbols:

```bash
make clean
make DEBUG=1 all
```

This builds both the enclave and application with debug information (`-g` flag).

#### Basic Debugging

To debug the application and enclave:

```bash
cd bin
SGX_DEBUG=1 sgx-gdb ./app
```

#### Memory Usage Analysis

You can use the SGX Enclave Memory Measurement Tool (EMMT) to analyze enclave memory usage:

```bash
cd bin
SGX_DEBUG=1 sgx-gdb -ex="enable sgx_emmt" -ex=r --args ./app
```

This will show peak memory usage after the enclave exits:

```
[+] Init Enclave Successful 3077026240004098!
[+] ecall_sample success...
[+] Enclave returned: Hello from enclave: Hello, world!
Enclave: "/path/to/sgx-sdk-rs/samples/hello-rust/bin/enclave.signed.so"
[Peak stack used]: 5 KB
[Peak heap used]: 4 KB
[Peak reserved memory used]: 0 KB
```

## Understanding the Code

- **app/**: Contains the untrusted host application that loads and communicates with the enclave
Expand Down
12 changes: 9 additions & 3 deletions samples/hello-rust/app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

use sgx_types::*;
use sgx_urts::SgxEnclave;
use std::env;

static ENCLAVE_FILE: &str = "enclave.signed.so";

Expand All @@ -35,13 +36,18 @@ extern "C" {
fn init_enclave() -> SgxResult<SgxEnclave> {
let mut launch_token: sgx_launch_token_t = [0; 1024];
let mut launch_token_updated: i32 = 0;
// call sgx_create_enclave to initialize an enclave instance
// Debug Support: set 2nd parameter to 1
let debug = 1;
let debug = match env::var("SGX_DEBUG") {
Ok(val) => match val.as_str() {
"1" => 1,
_ => 0,
},
Err(_) => 0,
};
let mut misc_attr = sgx_misc_attribute_t {
secs_attr: sgx_attributes_t { flags: 0, xfrm: 0 },
misc_select: 0,
};
// call sgx_create_enclave to initialize an enclave instance
SgxEnclave::create(
ENCLAVE_FILE,
debug,
Expand Down
1 change: 1 addition & 0 deletions samples/hello-rust/enclave/Enclave.lds
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ enclave.so
g_global_data;
enclave_entry;
g_peak_heap_used;
g_peak_rsrv_mem_committed;
local:
*;
};
89 changes: 54 additions & 35 deletions sgx-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,39 +94,6 @@ pub struct SgxBuilder {
}

impl SgxBuilder {
/// Get the target directory for EDL artifacts
fn get_edl_target_dir() -> PathBuf {
// First, try CARGO_TARGET_DIR which is explicitly set
if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
return PathBuf::from(target_dir).join("edl");
}

// Otherwise, require OUT_DIR to be set (should always be set in build.rs context)
let out_dir = env::var("OUT_DIR")
.expect("OUT_DIR not set. This function should only be called from build.rs");

let out_path = PathBuf::from(out_dir);

// Find the target directory by looking for a directory named "target"
// while traversing up the directory tree
let mut current_dir = out_path.as_path();
loop {
if let Some(file_name) = current_dir.file_name() {
if file_name == "target" {
return current_dir.join("edl");
}
}

match current_dir.parent() {
Some(parent) => current_dir = parent,
None => panic!(
"Could not find 'target' directory in OUT_DIR path: {}",
out_path.display()
),
}
}
}

/// Create a new EnclaveBuilder with default settings from environment
pub fn new() -> Self {
let sgx_sdk = env::var("SGX_SDK").unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string());
Expand All @@ -141,8 +108,7 @@ impl SgxBuilder {
"x64".to_string()
}
});
let debug =
env::var("SGX_DEBUG").is_ok() || env::var("DEBUG").is_ok() || cfg!(debug_assertions);
let debug = env::var("SGX_DEBUG").unwrap_or_default() == "1" || cfg!(debug_assertions);
let mitigation_cve_2020_0551 = match env::var("MITIGATION_CVE_2020_0551")
.or_else(|_| env::var("MITIGATION-CVE-2020-0551"))
{
Expand All @@ -164,6 +130,51 @@ impl SgxBuilder {
}
}

/// Print cargo rerun-if-env-changed for common environment variables
fn print_common_env_rerun() {
println!("cargo:rerun-if-env-changed=SGX_SDK");
println!("cargo:rerun-if-env-changed=SGX_MODE");
println!("cargo:rerun-if-env-changed=SGX_ARCH");
println!("cargo:rerun-if-env-changed=SGX_DEBUG");
println!("cargo:rerun-if-env-changed=MITIGATION_CVE_2020_0551");
println!("cargo:rerun-if-env-changed=MITIGATION-CVE-2020-0551");
}

/// Get the target directory for EDL artifacts
fn get_edl_target_dir() -> PathBuf {
// First, try CARGO_TARGET_DIR which is explicitly set
if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
println!("cargo:rerun-if-env-changed=CARGO_TARGET_DIR");
return PathBuf::from(target_dir).join("edl");
}

// Otherwise, require OUT_DIR to be set (should always be set in build.rs context)
println!("cargo:rerun-if-env-changed=OUT_DIR");
let out_dir = env::var("OUT_DIR")
.expect("OUT_DIR not set. This function should only be called from build.rs");

let out_path = PathBuf::from(out_dir);

// Find the target directory by looking for a directory named "target"
// while traversing up the directory tree
let mut current_dir = out_path.as_path();
loop {
if let Some(file_name) = current_dir.file_name() {
if file_name == "target" {
return current_dir.join("edl");
}
}

match current_dir.parent() {
Some(parent) => current_dir = parent,
None => panic!(
"Could not find 'target' directory in OUT_DIR path: {}",
out_path.display()
),
}
}
}

/// Detect GCC version
fn detect_gcc_version() -> Option<(u32, u32, u32)> {
let output = Command::new("gcc").arg("--version").output().ok()?;
Expand Down Expand Up @@ -233,6 +244,7 @@ impl SgxBuilder {

// Add additional search paths if needed
if let Ok(sgx_edl_search_paths) = env::var("SGX_EDL_SEARCH_PATHS") {
println!("cargo:rerun-if-env-changed=SGX_EDL_SEARCH_PATHS");
for path in sgx_edl_search_paths.split(':') {
cmd.args(["--search-path", path]);
}
Expand Down Expand Up @@ -352,6 +364,7 @@ impl SgxBuilder {
// Debug/Release specific flags
if self.debug {
build
.flag("-ggdb")
.flag("-O0")
.flag("-g")
.define("DEBUG", None)
Expand Down Expand Up @@ -506,6 +519,9 @@ impl SgxBuilder {
// Tell cargo to rerun if EDL changes
println!("cargo:rerun-if-changed={}", edl_path.display());

// Tell cargo to rerun if environment variables change
Self::print_common_env_rerun();

Ok(())
}

Expand Down Expand Up @@ -555,6 +571,9 @@ impl SgxBuilder {
// Tell cargo to rerun if EDL changes
println!("cargo:rerun-if-changed={}", edl_path.display());

// Tell cargo to rerun if environment variables change
Self::print_common_env_rerun();

Ok(())
}

Expand Down
21 changes: 16 additions & 5 deletions unit-test/Makefile
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
# Paths
SGX_SDK ?= /opt/sgxsdk
DEBUG := 0
ifeq ($(DEBUG), 0)
PROFILE := release
CARGO_FLAGS := --release
else
PROFILE := debug
export SGX_DEBUG := 1
endif
SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/release/enclave.so
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/$(PROFILE)/enclave.so
Signed_Enclave := bin/enclave.signed.so
Enclave_Config := enclave/Enclave.config.xml
Enclave_Key := enclave/Enclave_private.pem
App_Binary := app/target/release/app
App_Binary := app/target/$(PROFILE)/app

.PHONY: all build build-enclave build-app sign clean
.PHONY: all build build-enclave build-app sign clean run

all: build sign

build: build-enclave build-app

build-enclave:
@echo "Building enclave (including .so generation)..."
cd enclave && cargo sgx build --release
cd enclave && cargo sgx build $(CARGO_FLAGS)

build-app:
@echo "Building app..."
cd app && cargo build --release
cd app && cargo build $(CARGO_FLAGS)
@echo "Copying app binary to bin/..."
@cp $(App_Binary) bin/

Expand All @@ -34,3 +42,6 @@ clean:
@rm -rf bin/*
@cd enclave && cargo clean
@cd app && cargo clean

run:
@cd bin && ./app
12 changes: 9 additions & 3 deletions unit-test/app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

use sgx_types::*;
use sgx_urts::SgxEnclave;
use std::env;
use std::slice;
use std::str;

Expand All @@ -37,13 +38,18 @@ pub unsafe extern "C" fn ocall_print_string(str_ptr: *const u8, str_len: usize)
fn init_enclave() -> SgxResult<SgxEnclave> {
let mut launch_token: sgx_launch_token_t = [0; 1024];
let mut launch_token_updated: i32 = 0;
// call sgx_create_enclave to initialize an enclave instance
// Debug Support: set 2nd parameter to 1
let debug = 1;
let debug = match env::var("SGX_DEBUG") {
Ok(val) => match val.as_str() {
"1" => 1,
_ => 0,
},
Err(_) => 0,
};
let mut misc_attr = sgx_misc_attribute_t {
secs_attr: sgx_attributes_t { flags: 0, xfrm: 0 },
misc_select: 0,
};
// call sgx_create_enclave to initialize an enclave instance
SgxEnclave::create(
ENCLAVE_FILE,
debug,
Expand Down
11 changes: 11 additions & 0 deletions unit-test/enclave/Enclave.lds
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
enclave.so
{
global:
g_global_data_sim;
g_global_data;
enclave_entry;
g_peak_heap_used;
g_peak_rsrv_mem_committed;
local:
*;
};