Skip to content

Commit b071a20

Browse files
authored
Merge pull request #5 from datachainlab/fix-debugger-support
Fix to give `-ggdb` option if debug is enabled Signed-off-by: Jun Kimura <junkxdev@gmail.com>
2 parents 6c0d920 + e1c4b9f commit b071a20

File tree

9 files changed

+166
-59
lines changed

9 files changed

+166
-59
lines changed

cargo-sgx/src/main.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -301,15 +301,13 @@ fn create_enclave_so(
301301
if enclave_dir_script.exists() {
302302
Some(enclave_dir_script)
303303
} else {
304-
// Generate default version script if needed
305-
let default_script = output
306-
.parent()
307-
.unwrap_or(Path::new("."))
308-
.join(ENCLAVE_LDS_FILE);
309-
if !default_script.exists() {
310-
create_version_script(&default_script)?;
311-
}
312-
Some(default_script)
304+
// Generate default version script in the enclave directory (where Cargo.toml is located)
305+
println!(
306+
"Creating default {ENCLAVE_LDS_FILE} in {}",
307+
enclave_dir.display()
308+
);
309+
create_version_script(&enclave_dir_script)?;
310+
Some(enclave_dir_script)
313311
}
314312
};
315313

@@ -347,6 +345,7 @@ fn create_version_script(path: &Path) -> Result<()> {
347345
g_global_data;
348346
enclave_entry;
349347
g_peak_heap_used;
348+
g_peak_rsrv_mem_committed;
350349
local:
351350
*;
352351
};
@@ -549,6 +548,7 @@ fn create_enclave_lds(dir: &Path, force: bool) -> Result<()> {
549548
return Ok(());
550549
}
551550

551+
println!("Creating {ENCLAVE_LDS_FILE}...");
552552
create_version_script(&path)?;
553553
Ok(())
554554
}

samples/hello-rust/Makefile

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
# Paths
22
SGX_SDK ?= /opt/sgxsdk
3+
DEBUG := 0
4+
ifeq ($(DEBUG), 0)
5+
PROFILE := release
6+
CARGO_FLAGS := --release
7+
else
8+
PROFILE := debug
9+
export SGX_DEBUG := 1
10+
endif
311
SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign
4-
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/release/enclave.so
12+
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/$(PROFILE)/enclave.so
513
Signed_Enclave := bin/enclave.signed.so
614
Enclave_Config := enclave/Enclave.config.xml
715
Enclave_Key := enclave/Enclave_private.pem
8-
App_Binary := app/target/release/app
16+
App_Binary := app/target/$(PROFILE)/app
917

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

@@ -15,11 +23,11 @@ build: build-enclave build-app
1523

1624
build-enclave:
1725
@echo "Building enclave (including .so generation)..."
18-
cd enclave && cargo sgx build --release
26+
cd enclave && cargo sgx build $(CARGO_FLAGS)
1927

2028
build-app:
2129
@echo "Building app..."
22-
cd app && cargo build --release
30+
cd app && cargo build $(CARGO_FLAGS)
2331
@echo "Copying app binary to bin/..."
2432
@cp $(App_Binary) bin/
2533

samples/hello-rust/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,51 @@ Remove all build artifacts:
6767
make clean
6868
```
6969

70+
### Debug with sgx-gdb
71+
72+
The Intel SGX SDK provides `sgx-gdb`, a GDB extension for debugging SGX enclaves.
73+
74+
#### Build for Debugging
75+
76+
**Important**: To use the debugger, you must build with debug symbols:
77+
78+
```bash
79+
make clean
80+
make DEBUG=1 all
81+
```
82+
83+
This builds both the enclave and application with debug information (`-g` flag).
84+
85+
#### Basic Debugging
86+
87+
To debug the application and enclave:
88+
89+
```bash
90+
cd bin
91+
SGX_DEBUG=1 sgx-gdb ./app
92+
```
93+
94+
#### Memory Usage Analysis
95+
96+
You can use the SGX Enclave Memory Measurement Tool (EMMT) to analyze enclave memory usage:
97+
98+
```bash
99+
cd bin
100+
SGX_DEBUG=1 sgx-gdb -ex="enable sgx_emmt" -ex=r --args ./app
101+
```
102+
103+
This will show peak memory usage after the enclave exits:
104+
105+
```
106+
[+] Init Enclave Successful 3077026240004098!
107+
[+] ecall_sample success...
108+
[+] Enclave returned: Hello from enclave: Hello, world!
109+
Enclave: "/path/to/sgx-sdk-rs/samples/hello-rust/bin/enclave.signed.so"
110+
[Peak stack used]: 5 KB
111+
[Peak heap used]: 4 KB
112+
[Peak reserved memory used]: 0 KB
113+
```
114+
70115
## Understanding the Code
71116

72117
- **app/**: Contains the untrusted host application that loads and communicates with the enclave

samples/hello-rust/app/src/main.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
use sgx_types::*;
1919
use sgx_urts::SgxEnclave;
20+
use std::env;
2021

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

@@ -35,13 +36,18 @@ extern "C" {
3536
fn init_enclave() -> SgxResult<SgxEnclave> {
3637
let mut launch_token: sgx_launch_token_t = [0; 1024];
3738
let mut launch_token_updated: i32 = 0;
38-
// call sgx_create_enclave to initialize an enclave instance
39-
// Debug Support: set 2nd parameter to 1
40-
let debug = 1;
39+
let debug = match env::var("SGX_DEBUG") {
40+
Ok(val) => match val.as_str() {
41+
"1" => 1,
42+
_ => 0,
43+
},
44+
Err(_) => 0,
45+
};
4146
let mut misc_attr = sgx_misc_attribute_t {
4247
secs_attr: sgx_attributes_t { flags: 0, xfrm: 0 },
4348
misc_select: 0,
4449
};
50+
// call sgx_create_enclave to initialize an enclave instance
4551
SgxEnclave::create(
4652
ENCLAVE_FILE,
4753
debug,

samples/hello-rust/enclave/Enclave.lds

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ enclave.so
55
g_global_data;
66
enclave_entry;
77
g_peak_heap_used;
8+
g_peak_rsrv_mem_committed;
89
local:
910
*;
1011
};

sgx-build/src/lib.rs

Lines changed: 54 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -94,39 +94,6 @@ pub struct SgxBuilder {
9494
}
9595

9696
impl SgxBuilder {
97-
/// Get the target directory for EDL artifacts
98-
fn get_edl_target_dir() -> PathBuf {
99-
// First, try CARGO_TARGET_DIR which is explicitly set
100-
if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
101-
return PathBuf::from(target_dir).join("edl");
102-
}
103-
104-
// Otherwise, require OUT_DIR to be set (should always be set in build.rs context)
105-
let out_dir = env::var("OUT_DIR")
106-
.expect("OUT_DIR not set. This function should only be called from build.rs");
107-
108-
let out_path = PathBuf::from(out_dir);
109-
110-
// Find the target directory by looking for a directory named "target"
111-
// while traversing up the directory tree
112-
let mut current_dir = out_path.as_path();
113-
loop {
114-
if let Some(file_name) = current_dir.file_name() {
115-
if file_name == "target" {
116-
return current_dir.join("edl");
117-
}
118-
}
119-
120-
match current_dir.parent() {
121-
Some(parent) => current_dir = parent,
122-
None => panic!(
123-
"Could not find 'target' directory in OUT_DIR path: {}",
124-
out_path.display()
125-
),
126-
}
127-
}
128-
}
129-
13097
/// Create a new EnclaveBuilder with default settings from environment
13198
pub fn new() -> Self {
13299
let sgx_sdk = env::var("SGX_SDK").unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string());
@@ -141,8 +108,7 @@ impl SgxBuilder {
141108
"x64".to_string()
142109
}
143110
});
144-
let debug =
145-
env::var("SGX_DEBUG").is_ok() || env::var("DEBUG").is_ok() || cfg!(debug_assertions);
111+
let debug = env::var("SGX_DEBUG").unwrap_or_default() == "1" || cfg!(debug_assertions);
146112
let mitigation_cve_2020_0551 = match env::var("MITIGATION_CVE_2020_0551")
147113
.or_else(|_| env::var("MITIGATION-CVE-2020-0551"))
148114
{
@@ -164,6 +130,51 @@ impl SgxBuilder {
164130
}
165131
}
166132

133+
/// Print cargo rerun-if-env-changed for common environment variables
134+
fn print_common_env_rerun() {
135+
println!("cargo:rerun-if-env-changed=SGX_SDK");
136+
println!("cargo:rerun-if-env-changed=SGX_MODE");
137+
println!("cargo:rerun-if-env-changed=SGX_ARCH");
138+
println!("cargo:rerun-if-env-changed=SGX_DEBUG");
139+
println!("cargo:rerun-if-env-changed=MITIGATION_CVE_2020_0551");
140+
println!("cargo:rerun-if-env-changed=MITIGATION-CVE-2020-0551");
141+
}
142+
143+
/// Get the target directory for EDL artifacts
144+
fn get_edl_target_dir() -> PathBuf {
145+
// First, try CARGO_TARGET_DIR which is explicitly set
146+
if let Ok(target_dir) = env::var("CARGO_TARGET_DIR") {
147+
println!("cargo:rerun-if-env-changed=CARGO_TARGET_DIR");
148+
return PathBuf::from(target_dir).join("edl");
149+
}
150+
151+
// Otherwise, require OUT_DIR to be set (should always be set in build.rs context)
152+
println!("cargo:rerun-if-env-changed=OUT_DIR");
153+
let out_dir = env::var("OUT_DIR")
154+
.expect("OUT_DIR not set. This function should only be called from build.rs");
155+
156+
let out_path = PathBuf::from(out_dir);
157+
158+
// Find the target directory by looking for a directory named "target"
159+
// while traversing up the directory tree
160+
let mut current_dir = out_path.as_path();
161+
loop {
162+
if let Some(file_name) = current_dir.file_name() {
163+
if file_name == "target" {
164+
return current_dir.join("edl");
165+
}
166+
}
167+
168+
match current_dir.parent() {
169+
Some(parent) => current_dir = parent,
170+
None => panic!(
171+
"Could not find 'target' directory in OUT_DIR path: {}",
172+
out_path.display()
173+
),
174+
}
175+
}
176+
}
177+
167178
/// Detect GCC version
168179
fn detect_gcc_version() -> Option<(u32, u32, u32)> {
169180
let output = Command::new("gcc").arg("--version").output().ok()?;
@@ -233,6 +244,7 @@ impl SgxBuilder {
233244

234245
// Add additional search paths if needed
235246
if let Ok(sgx_edl_search_paths) = env::var("SGX_EDL_SEARCH_PATHS") {
247+
println!("cargo:rerun-if-env-changed=SGX_EDL_SEARCH_PATHS");
236248
for path in sgx_edl_search_paths.split(':') {
237249
cmd.args(["--search-path", path]);
238250
}
@@ -352,6 +364,7 @@ impl SgxBuilder {
352364
// Debug/Release specific flags
353365
if self.debug {
354366
build
367+
.flag("-ggdb")
355368
.flag("-O0")
356369
.flag("-g")
357370
.define("DEBUG", None)
@@ -506,6 +519,9 @@ impl SgxBuilder {
506519
// Tell cargo to rerun if EDL changes
507520
println!("cargo:rerun-if-changed={}", edl_path.display());
508521

522+
// Tell cargo to rerun if environment variables change
523+
Self::print_common_env_rerun();
524+
509525
Ok(())
510526
}
511527

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

574+
// Tell cargo to rerun if environment variables change
575+
Self::print_common_env_rerun();
576+
558577
Ok(())
559578
}
560579

unit-test/Makefile

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
11
# Paths
22
SGX_SDK ?= /opt/sgxsdk
3+
DEBUG := 0
4+
ifeq ($(DEBUG), 0)
5+
PROFILE := release
6+
CARGO_FLAGS := --release
7+
else
8+
PROFILE := debug
9+
export SGX_DEBUG := 1
10+
endif
311
SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign
4-
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/release/enclave.so
12+
Enclave_SO := enclave/target/x86_64-unknown-unknown-sgx/$(PROFILE)/enclave.so
513
Signed_Enclave := bin/enclave.signed.so
614
Enclave_Config := enclave/Enclave.config.xml
715
Enclave_Key := enclave/Enclave_private.pem
8-
App_Binary := app/target/release/app
16+
App_Binary := app/target/$(PROFILE)/app
917

10-
.PHONY: all build build-enclave build-app sign clean
18+
.PHONY: all build build-enclave build-app sign clean run
1119

1220
all: build sign
1321

1422
build: build-enclave build-app
1523

1624
build-enclave:
1725
@echo "Building enclave (including .so generation)..."
18-
cd enclave && cargo sgx build --release
26+
cd enclave && cargo sgx build $(CARGO_FLAGS)
1927

2028
build-app:
2129
@echo "Building app..."
22-
cd app && cargo build --release
30+
cd app && cargo build $(CARGO_FLAGS)
2331
@echo "Copying app binary to bin/..."
2432
@cp $(App_Binary) bin/
2533

@@ -34,3 +42,6 @@ clean:
3442
@rm -rf bin/*
3543
@cd enclave && cargo clean
3644
@cd app && cargo clean
45+
46+
run:
47+
@cd bin && ./app

unit-test/app/src/main.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
use sgx_types::*;
1919
use sgx_urts::SgxEnclave;
20+
use std::env;
2021
use std::slice;
2122
use std::str;
2223

@@ -37,13 +38,18 @@ pub unsafe extern "C" fn ocall_print_string(str_ptr: *const u8, str_len: usize)
3738
fn init_enclave() -> SgxResult<SgxEnclave> {
3839
let mut launch_token: sgx_launch_token_t = [0; 1024];
3940
let mut launch_token_updated: i32 = 0;
40-
// call sgx_create_enclave to initialize an enclave instance
41-
// Debug Support: set 2nd parameter to 1
42-
let debug = 1;
41+
let debug = match env::var("SGX_DEBUG") {
42+
Ok(val) => match val.as_str() {
43+
"1" => 1,
44+
_ => 0,
45+
},
46+
Err(_) => 0,
47+
};
4348
let mut misc_attr = sgx_misc_attribute_t {
4449
secs_attr: sgx_attributes_t { flags: 0, xfrm: 0 },
4550
misc_select: 0,
4651
};
52+
// call sgx_create_enclave to initialize an enclave instance
4753
SgxEnclave::create(
4854
ENCLAVE_FILE,
4955
debug,

unit-test/enclave/Enclave.lds

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
enclave.so
2+
{
3+
global:
4+
g_global_data_sim;
5+
g_global_data;
6+
enclave_entry;
7+
g_peak_heap_used;
8+
g_peak_rsrv_mem_committed;
9+
local:
10+
*;
11+
};

0 commit comments

Comments
 (0)