You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by yu...@apache.org on 2024/12/31 07:00:11 UTC

(incubator-teaclave-trustzone-sdk) branch main updated (b65877b -> 131a55a)

This is an automated email from the ASF dual-hosted git repository.

yuanz pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-trustzone-sdk.git


    from b65877b  examples/std: workaround for building ARM32 tls TAs
     new 4ba89b5  Introduce optee-utee-build crate: 1. introduce build method to make building process simpler. 2. introduce Builder struct for developers who want to customize the    building process. 3. introduce HeaderFileGenerator struct for developers who want to    generate a header file only. 4. introduce Linker struct for developers who want to handle linking    stuff only.
     new 80b8747  Use optee-utee-build crate to build hello_world example
     new 131a55a  Doc: add tutorial about how to use optee-utee-build

The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .github/workflows/ci.yml                           |   1 +
 README.md                                          |   3 +
 docs/README.md                                     |   1 +
 docs/migrating-to-new-building-env.md              |   5 +
 docs/writing-rust-tas-using-optee-utee-build.md    | 243 ++++++++++++++
 examples/hello_world-rs/ta/Cargo.toml              |   4 +-
 examples/hello_world-rs/ta/Makefile                |   3 +-
 examples/hello_world-rs/ta/build.rs                |  86 +----
 examples/hello_world-rs/ta/src/main.rs             |  12 -
 examples/hello_world-rs/ta/ta_static.rs            | 102 ------
 .../optee-teec-sys => optee-utee-build}/Cargo.toml |  11 +-
 optee-utee-build/src/builder.rs                    | 131 ++++++++
 optee-utee-build/src/code_generator.rs             | 360 +++++++++++++++++++++
 .../src/lib.rs => optee-utee-build/src/error.rs    |  36 ++-
 {optee-teec => optee-utee-build}/src/lib.rs        |  44 ++-
 .../src/license_str.txt                            |   5 -
 optee-utee-build/src/linker.rs                     | 190 +++++++++++
 optee-utee-build/src/ta_config.rs                  | 193 +++++++++++
 .../test_files/test_edition_2024_result.rs         |  85 +++--
 .../test_files/test_edition_before_2024_result.rs  |  73 ++---
 setup.sh                                           |   6 +-
 21 files changed, 1270 insertions(+), 324 deletions(-)
 create mode 100644 docs/writing-rust-tas-using-optee-utee-build.md
 delete mode 100644 examples/hello_world-rs/ta/ta_static.rs
 copy {optee-teec/optee-teec-sys => optee-utee-build}/Cargo.toml (86%)
 create mode 100644 optee-utee-build/src/builder.rs
 create mode 100644 optee-utee-build/src/code_generator.rs
 copy examples/diffie_hellman-rs/proto/src/lib.rs => optee-utee-build/src/error.rs (61%)
 copy {optee-teec => optee-utee-build}/src/lib.rs (50%)
 copy optee-utee/optee-utee-sys/src/tee_api_private.rs => optee-utee-build/src/license_str.txt (96%)
 create mode 100644 optee-utee-build/src/linker.rs
 create mode 100644 optee-utee-build/src/ta_config.rs
 copy examples/aes-rs/ta/ta_static.rs => optee-utee-build/test_files/test_edition_2024_result.rs (75%)
 copy examples/aes-rs/ta/ta_static.rs => optee-utee-build/test_files/test_edition_before_2024_result.rs (79%)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org


(incubator-teaclave-trustzone-sdk) 03/03: Doc: add tutorial about how to use optee-utee-build

Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yuanz pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-trustzone-sdk.git

commit 131a55a35c56c6f946d9a58dc8bf5e3a28ae0d04
Author: ivila <39...@qq.com>
AuthorDate: Mon Dec 23 11:04:31 2024 +0800

    Doc: add tutorial about how to use optee-utee-build
    
    1. add document "Writing Rust TAs using optee-utee-build"
    2. suggest developers using optee-utee-build in
       "Migrating to new building env"
    3. add description about the supported host machines in README.md
    
    Signed-off-by: ivila <39...@qq.com>
    Reviewed-by: Sumit Garg <su...@linaro.org>
    Reviewed-by: Yuan Zhuang <yu...@apache.org>
---
 README.md                                       |   3 +
 docs/README.md                                  |   1 +
 docs/migrating-to-new-building-env.md           |   5 +
 docs/writing-rust-tas-using-optee-utee-build.md | 243 ++++++++++++++++++++++++
 4 files changed, 252 insertions(+)

diff --git a/README.md b/README.md
index d821e5f..8a0b00c 100644
--- a/README.md
+++ b/README.md
@@ -157,6 +157,9 @@ Prerequisites](https://optee.readthedocs.io/en/latest/building/prerequisites.htm
 
 ### Setup Building Environment
 
+Currently, we support building on both `aarch64` and `x86_64` host machines, and
+ they share the same steps.
+
 1. Install the Rust environment and toolchains:
 
    ```sh
diff --git a/docs/README.md b/docs/README.md
index 368f799..db83a9f 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -8,3 +8,4 @@ permalink: /trustzone-sdk-docs
 * [Debugging OP-TEE TA](debugging-optee-ta.md)
 * [Expanding TA Secure Memory on QEMUv8](expanding-ta-secure-memory-on-qemuv8.md)
 * [Building Rust CA as Android ELF](building-rust-ca-as-android-elf.md)
+* [Writing Rust TAs using optee-utee-build](writing-rust-tas-using-optee-utee-build.md)
diff --git a/docs/migrating-to-new-building-env.md b/docs/migrating-to-new-building-env.md
index 3b79ba8..ce98ed6 100644
--- a/docs/migrating-to-new-building-env.md
+++ b/docs/migrating-to-new-building-env.md
@@ -2,6 +2,11 @@
 permalink: /trustzone-sdk-docs/migrating-to-new-building-env.md
 ---
 
+> After optee-utee-build release, this doc is keeping for developers 
+who intend to know the detail of building process, we suggest use 
+[optee-utee-build](./writing-rust-tas-using-optee-utee-build.md) for building 
+instead.
+
 ## Migration Guide: Moving from `master` to `main` Branch (Post-Oct 2024)
 
 Since the `main` branch (after October 2024) introduces breaking changes 
diff --git a/docs/writing-rust-tas-using-optee-utee-build.md b/docs/writing-rust-tas-using-optee-utee-build.md
new file mode 100644
index 0000000..4287a46
--- /dev/null
+++ b/docs/writing-rust-tas-using-optee-utee-build.md
@@ -0,0 +1,243 @@
+---
+permalink: /trustzone-sdk-docs/writing-rust-tas-using-optee-utee-build.md
+---
+
+Currently we provide a `optee-utee-build` crate to simplify the compilcated
+building process of TA, and we recommend everyone use it in future developement.
+
+* For legacy app structures migrating to use this crate, refer to [Migration
+  Guide](#migration-guide)
+* If you're new to development, start with [Minimal Example](#minimal-example)
+* To customize the build process, see [Customization](#customization)
+
+# Minimal Example
+
+Assuming currently we are developing a `hello_world` TA, and we want to build it
+with `optee-utee-build` crate, we can do it by following steps.
+
+Firstly, we should add `optee-utee-build` in `build-dependencies`:
+
+```shell
+cargo add --build optee-utee-build
+```
+
+Secondly, we set a `ta_config` and call `optee-utee-build::build` with it in
+build.rs:
+
+```rust
+use proto;
+use optee_utee_build::{TaConfig, Error, RustEdition};
+
+fn main() -> Result<(), Error> {
+    let ta_config = TaConfig::new_default_with_cargo_env(proto::UUID)?;
+    optee_utee_build::build(RustEdition::Before2024, ta_config)
+}
+```
+
+It will generate a `user_ta_header.rs` file and setup all the required
+configurations of the linker of rustc.
+
+Finally, we include the generated `user_ta_header.rs` in the source codes,
+normally we put it in `src/main.rs`.
+
+```rust
+// src/main.rs
+include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));
+```
+
+After that, everything finished, we can start building the TA now.
+
+For full codes, you can check the [`hello_world-rs example`](https://github.com/apache/incubator-teaclave-trustzone-sdk/tree/main/examples/hello_world-rs/ta)
+
+## Explaination of Minimal Example
+
+### 1. The TaConfig
+
+This is a struct that use for the configuration of the TA we are developing, it
+has some public fields:
+
+1. **uuid**: the identifier of TA.
+2. **ta_flags**: combination of some bitflags.  
+   for available values, you may check [user_ta_header.h in optee_os](https://github.com/OP-TEE/optee_os/blob/c2e42a8f03a5bb6b894ef85ae409f54760c1f50e/lib/libutee/include/user_ta_header.h#L13-L53)
+3. **ta_data_size**: the size in bytes of the TA allocation pool.
+4. **ta_stack_size**: the size in bytes of the stack used for TA execution.
+5. **ta_version**: a version string of TA, should be in semver format.
+6. **ta_description**: the desciption of TA.
+7. **trace_level**: the default trace level of TA.  
+   for available values, you may check [trace_levels.h in optee_os](https://github.com/OP-TEE/optee_os/blob/c2e42a8f03a5bb6b894ef85ae409f54760c1f50e/lib/libutils/ext/include/trace_levels.h#L26-L31)
+8. **trace_ext**: an extra prefix string when output trace log.
+9. **ta_framework_stack_size**: the size in bytes of the stack used for Trusted
+Core Framework.  
+   currently used for trace framework and invoke command, should not be less
+   than 2048.
+10. **ext_properties**: the extra custom properties.
+
+We can construct the `TaConfig` by providing all of the public fields manually,
+or use our standard constructor:
+
+1. **new_default**: construct a default TaConfig by providing uuid, ta_version 
+and ta_description, with other configurations set to suggested values, you can 
+update those configurations later.
+2. **new_default_with_cargo_env**: it's a constructor wrapped with new_default, 
+but take `version` and `description` from cargo.toml so simply providing a uuid 
+as parameter is enough.
+
+### 2. The RustEdition
+
+The generated `user_ta_header.rs` must be different between `edition of 2024`
+and `edition before 2024`, and currently there is no official stable way to know
+what edition we are compiling with, so we provide a argument to set with.
+
+> #### What’s the difference?
+> the generated `user_ta_header.rs` file include some const variables and global
+functions tagged with `no_mangle` and `link_section`, start from rust edition of
+2024, they must be wrapped with unsafe, or rustc will output a compilation error
+(while before edition of 2024 it must not, or rustc will output a syntax error).
+
+# Customization
+
+`optee-utee-build` provide some structs for flexible use.
+
+### 1. Builder
+
+Instead of calling the `build` function directly, you can use Builder for
+customization.
+
+Usage:
+
+```Rust
+use proto;
+use optee_utee_build::{TaConfig, Builder, Error, RustEdition, LinkType};
+
+fn main() -> Result<(), Error> {
+    let ta_config = TaConfig::new_default_with_cargo_env(proto::UUID)?;
+    Builder::new(RustEdition::Before2024, ta_config)
+      .out_dir("/tmp")
+      .header_file_name("my_generated_user_ta_header.rs")
+      .link_type(LinkType::CC)
+      .build()
+}
+```
+
+As you can see from the codes, there are some customizations of the builder:
+1. **out_dir**: change directory of output files.  
+   default to OUT_DIR by cargo.
+2. **header_file_name**: change name of output header file.  
+   default to `user_ta_header.rs`
+3. **link_type**: set link_type manually.  
+   there are some difference in parameters in
+   linkers between `CC` and `LD` types, for example, `--sort-section` in `CC` types
+   of linkers changes to `-Wl,--sort-section`, we will try to detect current linker
+   that cargo using, you can use this function to set it manually if you think our
+   detection mismatch.
+
+### 2. Linker
+For developers who prefer to use a hand-written `user_ta_header.rs` and only
+want `optee-utee-build` to handle the linking process, they can use the
+`Linker`, otherwise, try `Builder` instead.
+
+Usage:
+
+``` rust
+use optee_utee_build::{Linker, Error};
+use std::env;
+
+fn main() -> Result<(), Error> {
+  let out_dir = env::var("OUT_DIR")?;
+  Linker::auto().link_all(out_dir)?;
+  Ok(())
+}
+```
+
+When linking manually, developers construct a `Linker` and calling the
+`link_all` method by providing the out_dir, and linker will generate some
+required files (link script, etc, used by linker) into out_dir and handle all
+the linking stuff.
+
+In above codes, we use `auto` to construct the linker, it will detect current
+linker that cargo using automatically, you can use `new` function to construct
+the linker manually if you think our detection mismatch.
+```rust
+use optee_utee_build::{Linker, Error, LinkType};
+use std::env;
+
+fn main() -> Result<(), Error> {
+  let out_dir = env::var("OUT_DIR")?;
+  Linker::new(LinkerType::CC).link_all(out_dir)?;
+  Ok(())
+}
+```
+
+### 3. HeaderFileGenerator
+For developers who prefer to do the linking themselves and only want
+`optee-utee-build` to generate the header file, they can use the
+`HeaderFileGenerator`, otherwise, try `Builder` instead.
+
+Usage:
+
+```rust
+use optee_utee_build::{HeaderFileGenerator, TaConfig, RustEdition, Error};
+
+fn main() -> Result<(), Error> {
+  const UUID: &str = "26509cec-4a2b-4935-87ab-762d89fbf0b0";
+  let ta_config = TaConfig::new_default(UUID, "0.1.0", "example")?;
+  let codes = HeaderFileGenerator::new(RustEdition::Before2024).generate(&ta_config)?;
+  Ok(std::io::Write("/tmp/user_ta_header.rs", codes.as_bytes())?)
+}
+
+```
+
+# Migration Guide
+
+For developers still using `const configuration values` in `src/main.rs` and
+`custom build scripts` in `build.rs`(described in [\[migrating-to-new-building-env\]](https://github.com/apache/incubator-teaclave-trustzone-sdk/blob/main/docs/migrating-to-new-building-env.md)),
+they can upgrade to `optee-utee-build` by following step:
+
+Firstly, add `optee-utee-build` as `build-dependencies`:
+
+```shell
+cargo add --build optee-utee-build
+```
+
+Secondly, in `build.rs`, remove codes of `custom build scripts`, and use
+`optee_utee_build::build` instead:
+
+```rust
+// ... other imports
+use optee_utee_build::{TaConfig, Error}
+
+fn main() -> Result<(), Error> {
+  // should customize the ta_config with the same as const configuration values
+  // in your src/main.rs
+  let ta_config = TaConfig::new_default_with_cargo_env(proto::UUID)?
+    .ta_stack_size(10 * 1024); 
+  optee_utee_build::build(RustEdition::Before2024, ta_config)?;
+
+  // ... other build scripts
+}
+```
+
+Thirdly, remove `const configuration values` in `src/main.rs`, keep the line of
+`include user_ta_header.rs`.
+
+```rust
+/// ... other codes in src/main.rs
+
+/* remove const configuration values, move them to TaConfig in src/main.rs
+// TA configurations
+const TA_FLAGS: u32 = 0;
+const TA_DATA_SIZE: u32 = 32 * 1024;
+const TA_STACK_SIZE: u32 = 2 * 1024;
+const TA_VERSION: &[u8] = b"0.1\0";
+const TA_DESCRIPTION: &[u8] = b"This is a hello world example.\0";
+const EXT_PROP_VALUE_1: &[u8] = b"Hello World TA\0";
+const EXT_PROP_VALUE_2: u32 = 0x0010;
+const TRACE_LEVEL: i32 = 4;
+const TRACE_EXT_PREFIX: &[u8] = b"TA\0";
+const TA_FRAMEWORK_STACK_SIZE: u32 = 2048;
+*/
+
+include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));  // keep this line
+```
+
+Finally, delete the useless `ta_static.rs` and start building now.


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org


(incubator-teaclave-trustzone-sdk) 02/03: Use optee-utee-build crate to build hello_world example

Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yuanz pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-trustzone-sdk.git

commit 80b874735ec118f39a7be92559d318b99a5f5f99
Author: ivila <39...@qq.com>
AuthorDate: Fri Dec 20 17:31:13 2024 +0800

    Use optee-utee-build crate to build hello_world example
    
    1. add optee-utee-build in build-dependencies
    2. remove uuid from build-dependencies
    3. use build method from optee-utee-build instead of custom build script
    4. use gcc as linker instead of ld.bfd to avoid compilation problems on
       Arm host
    5. remove ta_static.rs file
    6. remove configuration consts in src/main.rs
    
    Signed-off-by: ivila <39...@qq.com>
    Reviewed-by: Sumit Garg <su...@linaro.org>
    Reviewed-by: Yuan Zhuang <yu...@apache.org>
---
 examples/hello_world-rs/ta/Cargo.toml   |   4 +-
 examples/hello_world-rs/ta/Makefile     |   3 +-
 examples/hello_world-rs/ta/build.rs     |  86 ++-------------------------
 examples/hello_world-rs/ta/src/main.rs  |  12 ----
 examples/hello_world-rs/ta/ta_static.rs | 102 --------------------------------
 5 files changed, 8 insertions(+), 199 deletions(-)

diff --git a/examples/hello_world-rs/ta/Cargo.toml b/examples/hello_world-rs/ta/Cargo.toml
index badab89..d272b6f 100644
--- a/examples/hello_world-rs/ta/Cargo.toml
+++ b/examples/hello_world-rs/ta/Cargo.toml
@@ -29,9 +29,9 @@ proto = { path = "../proto" }
 optee-utee-sys = { path = "../../../optee-utee/optee-utee-sys" }
 optee-utee = { path = "../../../optee-utee" }
 
-[build_dependencies]
-uuid = { version = "1.6.1", default-features = false }
+[build-dependencies]
 proto = { path = "../proto" }
+optee-utee-build = { path = "../../../optee-utee-build" }
 
 [profile.release]
 panic = "abort"
diff --git a/examples/hello_world-rs/ta/Makefile b/examples/hello_world-rs/ta/Makefile
index 72a9cb3..029e66d 100644
--- a/examples/hello_world-rs/ta/Makefile
+++ b/examples/hello_world-rs/ta/Makefile
@@ -20,7 +20,8 @@ UUID ?= $(shell cat "../uuid.txt")
 TARGET ?= aarch64-unknown-linux-gnu
 CROSS_COMPILE ?= aarch64-linux-gnu-
 OBJCOPY := $(CROSS_COMPILE)objcopy
-LINKER_CFG := target.$(TARGET).linker=\"$(CROSS_COMPILE)ld.bfd\"
+# Configure the linker to use GCC, which works on both cross-compilation and ARM machines
+LINKER_CFG := target.$(TARGET).linker=\"$(CROSS_COMPILE)gcc\"
 
 TA_SIGN_KEY ?= $(TA_DEV_KIT_DIR)/keys/default_ta.pem
 SIGN := $(TA_DEV_KIT_DIR)/scripts/sign_encrypt.py
diff --git a/examples/hello_world-rs/ta/build.rs b/examples/hello_world-rs/ta/build.rs
index fa0d195..a45e9b6 100644
--- a/examples/hello_world-rs/ta/build.rs
+++ b/examples/hello_world-rs/ta/build.rs
@@ -16,88 +16,10 @@
 // under the License.
 
 use proto;
-use std::env;
-use std::fs::File;
-use std::io::{BufRead, BufReader, Write};
-use std::path::{Path, PathBuf};
-use uuid::Uuid;
+use optee_utee_build::{TaConfig, RustEdition, Error};
 
-fn main() -> std::io::Result<()> {
-    let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
+fn main() -> Result<(), Error> {
+    let config = TaConfig::new_default_with_cargo_env(proto::UUID)?;
+    optee_utee_build::build(RustEdition::Before2024, config)
 
-    let mut buffer = File::create(out.join("user_ta_header.rs"))?;
-    buffer.write_all(include_bytes!("ta_static.rs"))?;
-
-    let tee_uuid = Uuid::parse_str(proto::UUID).unwrap();
-    let (time_low, time_mid, time_hi_and_version, clock_seq_and_node) = tee_uuid.as_fields();
-
-    write!(buffer, "\n")?;
-    write!(
-        buffer,
-        "const TA_UUID: optee_utee_sys::TEE_UUID = optee_utee_sys::TEE_UUID {{
-    timeLow: {:#x},
-    timeMid: {:#x},
-    timeHiAndVersion: {:#x},
-    clockSeqAndNode: {:#x?},
-}};",
-        time_low, time_mid, time_hi_and_version, clock_seq_and_node
-    )?;
-
-    let mut aarch64_flag = true;
-    match env::var("TARGET_TA") {
-        Ok(ref v) if v == "arm-unknown-linux-gnueabihf" || v == "arm-unknown-optee" => {
-            println!("cargo:rustc-link-arg=--no-warn-mismatch");
-            aarch64_flag = false;
-        },
-        _ => {}
-    };
-
-    let optee_os_dir = env::var("TA_DEV_KIT_DIR").unwrap();
-    let search_path = Path::new(&optee_os_dir).join("lib");
-
-    let optee_os_path = &PathBuf::from(optee_os_dir.clone());
-    let mut ta_lds = File::create(out.join("ta.lds"))?;
-    let f = File::open(optee_os_path.join("src/ta.ld.S"))?;
-    let f = BufReader::new(f);
-
-    for line in f.lines() {
-        let l = line?;
-
-        if aarch64_flag {
-            if l.starts_with('#') ||
-                l == "OUTPUT_FORMAT(\"elf32-littlearm\")" ||
-                l == "OUTPUT_ARCH(arm)" {
-                continue;
-            }
-        } else {
-            if l.starts_with('#') ||
-                l == "OUTPUT_FORMAT(\"elf64-littleaarch64\")" ||
-                l == "OUTPUT_ARCH(aarch64)" {
-                continue;
-            }
-        }
-
-        if l == "\t. = ALIGN(4096);" {
-            write!(ta_lds, "\t. = ALIGN(65536);\n")?;
-        } else {
-            write!(ta_lds, "{}\n", l)?;
-        }
-    }
-
-    println!("cargo:rustc-link-search={}", out.display());
-    println!("cargo:rerun-if-changed=ta.lds");
-
-    println!("cargo:rustc-link-search={}", search_path.display());
-    println!("cargo:rustc-link-lib=static=utee");
-    println!("cargo:rustc-link-lib=static=utils");
-    println!("cargo:rustc-link-arg=-Tta.lds");
-    println!("cargo:rustc-link-arg=-e__ta_entry");
-    println!("cargo:rustc-link-arg=-pie");
-    println!("cargo:rustc-link-arg=-Os");
-    println!("cargo:rustc-link-arg=--sort-section=alignment");
-
-    let mut dyn_list = File::create(out.join("dyn_list"))?;
-    write!(dyn_list, "{{ __elf_phdr_info; trace_ext_prefix; trace_level; ta_head; }};\n")?;
-    println!("cargo:rustc-link-arg=--dynamic-list=dyn_list");
-    Ok(())
 }
diff --git a/examples/hello_world-rs/ta/src/main.rs b/examples/hello_world-rs/ta/src/main.rs
index 8ef0567..e29f9d6 100644
--- a/examples/hello_world-rs/ta/src/main.rs
+++ b/examples/hello_world-rs/ta/src/main.rs
@@ -63,16 +63,4 @@ fn invoke_command(cmd_id: u32, params: &mut Parameters) -> Result<()> {
     }
 }
 
-// TA configurations
-const TA_FLAGS: u32 = 0;
-const TA_DATA_SIZE: u32 = 32 * 1024;
-const TA_STACK_SIZE: u32 = 2 * 1024;
-const TA_VERSION: &[u8] = b"0.1\0";
-const TA_DESCRIPTION: &[u8] = b"This is a hello world example.\0";
-const EXT_PROP_VALUE_1: &[u8] = b"Hello World TA\0";
-const EXT_PROP_VALUE_2: u32 = 0x0010;
-const TRACE_LEVEL: i32 = 4;
-const TRACE_EXT_PREFIX: &[u8] = b"TA\0";
-const TA_FRAMEWORK_STACK_SIZE: u32 = 2048;
-
 include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));
diff --git a/examples/hello_world-rs/ta/ta_static.rs b/examples/hello_world-rs/ta/ta_static.rs
deleted file mode 100644
index 20e1d97..0000000
--- a/examples/hello_world-rs/ta/ta_static.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-use core::ffi::{c_int, c_void};
-use core::mem;
-use core::primitive::u64;
-
-#[no_mangle]
-pub static mut trace_level: c_int = TRACE_LEVEL;
-
-#[no_mangle]
-pub static trace_ext_prefix: &[u8] = TRACE_EXT_PREFIX;
-
-#[no_mangle]
-#[link_section = ".ta_head"]
-pub static ta_head: optee_utee_sys::ta_head = optee_utee_sys::ta_head {
-    uuid: TA_UUID,
-    stack_size: TA_STACK_SIZE + TA_FRAMEWORK_STACK_SIZE,
-    flags: TA_FLAGS,
-    depr_entry: u64::MAX,
-};
-
-#[no_mangle]
-#[link_section = ".bss"]
-pub static ta_heap: [u8; TA_DATA_SIZE as usize] = [0; TA_DATA_SIZE as usize];
-
-#[no_mangle]
-pub static ta_heap_size: usize = mem::size_of::<u8>() * TA_DATA_SIZE as usize;
-static FLAG_BOOL: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_SINGLE_INSTANCE) != 0;
-static FLAG_MULTI: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_MULTI_SESSION) != 0;
-static FLAG_INSTANCE: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_INSTANCE_KEEP_ALIVE) != 0;
-
-#[no_mangle]
-pub static ta_num_props: usize = 9;
-
-#[no_mangle]
-pub static ta_props: [optee_utee_sys::user_ta_property; 9] = [
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_SINGLE_INSTANCE,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
-        value: &FLAG_BOOL as *const bool as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_MULTI_SESSION,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
-        value: &FLAG_MULTI as *const bool as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_KEEP_ALIVE,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
-        value: &FLAG_INSTANCE as *const bool as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_DATA_SIZE,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
-        value: &TA_DATA_SIZE as *const u32 as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_STACK_SIZE,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
-        value: &TA_STACK_SIZE as *const u32 as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_VERSION,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
-        value: TA_VERSION as *const [u8] as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: optee_utee_sys::TA_PROP_STR_DESCRIPTION,
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
-        value: TA_DESCRIPTION as *const [u8] as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: "gp.ta.description\0".as_ptr(),
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
-        value: EXT_PROP_VALUE_1 as *const [u8] as *mut _,
-    },
-    optee_utee_sys::user_ta_property {
-        name: "gp.ta.version\0".as_ptr(),
-        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
-        value: &EXT_PROP_VALUE_2 as *const u32 as *mut _,
-    },
-];
-
-#[no_mangle]
-pub unsafe extern "C" fn tahead_get_trace_level() -> c_int {
-    return trace_level;
-}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org


(incubator-teaclave-trustzone-sdk) 01/03: Introduce optee-utee-build crate: 1. introduce build method to make building process simpler. 2. introduce Builder struct for developers who want to customize the building process. 3. introduce HeaderFileGenerator struct for developers who want to generate a header file only. 4. introduce Linker struct for developers who want to handle linking stuff only.

Posted by yu...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

yuanz pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-trustzone-sdk.git

commit 4ba89b5fc4580c77581a1b97b16da7ee8afcc0bb
Author: ivila <39...@qq.com>
AuthorDate: Fri Dec 20 17:27:42 2024 +0800

    Introduce optee-utee-build crate:
    1. introduce build method to make building process simpler.
    2. introduce Builder struct for developers who want to customize the
       building process.
    3. introduce HeaderFileGenerator struct for developers who want to
       generate a header file only.
    4. introduce Linker struct for developers who want to handle linking
       stuff only.
    
    Signed-off-by: ivila <39...@qq.com>
    Reviewed-by: Sumit Garg <su...@linaro.org>
    Reviewed-by: Yuan Zhuang <yu...@apache.org>
---
 .github/workflows/ci.yml                           |   1 +
 optee-utee-build/Cargo.toml                        |  32 ++
 optee-utee-build/src/builder.rs                    | 131 ++++++++
 optee-utee-build/src/code_generator.rs             | 360 +++++++++++++++++++++
 optee-utee-build/src/error.rs                      |  43 +++
 optee-utee-build/src/lib.rs                        |  47 +++
 optee-utee-build/src/license_str.txt               |  16 +
 optee-utee-build/src/linker.rs                     | 190 +++++++++++
 optee-utee-build/src/ta_config.rs                  | 193 +++++++++++
 .../test_files/test_edition_2024_result.rs         |  97 ++++++
 .../test_files/test_edition_before_2024_result.rs  |  97 ++++++
 setup.sh                                           |   6 +-
 12 files changed, 1212 insertions(+), 1 deletion(-)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 951ed42..693e3e3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -44,6 +44,7 @@ jobs:
           # Run unit tests
           (cd optee-utee && SYS_BUILD_TYPE=unit_test cargo test --lib --features no_panic_handler -vv)
           (cd optee-teec && SYS_BUILD_TYPE=unit_test cargo test --lib -vv)
+          (cd optee-utee-build && cargo test -vv)
 
           # Build Rust optee-utee and optee-teec
           (cd optee-utee && cargo build --target aarch64-unknown-linux-gnu -vv)
diff --git a/optee-utee-build/Cargo.toml b/optee-utee-build/Cargo.toml
new file mode 100644
index 0000000..9e14ea2
--- /dev/null
+++ b/optee-utee-build/Cargo.toml
@@ -0,0 +1,32 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+[package]
+name = "optee-utee-build"
+version = "0.2.0"
+authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
+license = "Apache-2.0"
+repository = "https://github.com/apache/incubator-teaclave-trustzone-sdk.git"
+edition = "2018"
+description = "Build tool for TA"
+
+[dependencies]
+uuid = "1.11.0"
+quote = "1.0.37"
+proc-macro2 = "1.0.92"
+syn = "2.0.90"
+prettyplease = "0.2.25"
diff --git a/optee-utee-build/src/builder.rs b/optee-utee-build/src/builder.rs
new file mode 100644
index 0000000..03fc652
--- /dev/null
+++ b/optee-utee-build/src/builder.rs
@@ -0,0 +1,131 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::fs::File;
+use std::io::Write;
+use std::path::PathBuf;
+
+use crate::Error;
+use crate::HeaderFileGenerator;
+use crate::RustEdition;
+use crate::TaConfig;
+use crate::{Linker, LinkerType};
+
+const DEFAULT_HEADER_FILE_NAME: &str = "user_ta_header.rs";
+
+/// The Builder of TA, use it to handle file generation and linking stuff
+///
+/// Usage:
+///
+/// ```no_run
+/// use optee_utee_build::{TaConfig, Builder, RustEdition};
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default(UUID, "0.1.0", "example")?;
+/// Builder::new(RustEdition::Before2024, ta_config).build()?;
+/// # Ok(())
+/// # }
+/// ```
+///
+/// Or you can just use the build method, it's simpler
+/// ```no_run
+/// use optee_utee_build::{TaConfig, RustEdition};
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default(UUID, "0.1.0", "example")?;
+/// optee_utee_build::build(RustEdition::Before2024, ta_config)?;
+/// # Ok(())
+/// # }
+/// ```
+///
+/// There are some difference when cargo use different linkers, we will try
+/// to detect the linker automatically, you can set it manually if you met
+/// some problems with it.
+/// ```no_run
+/// use optee_utee_build::{TaConfig, Builder, RustEdition, LinkerType};
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default(UUID, "0.1.0", "example")?;
+/// Builder::new(RustEdition::Before2024, ta_config).linker_type(LinkerType::Ld).build()?;
+/// # Ok(())
+/// # }
+/// ```
+pub struct Builder {
+    out_dir: Option<PathBuf>,
+    edition: RustEdition,
+    header_file_name: Option<String>,
+    ta_config: TaConfig,
+    linker_type: Option<LinkerType>,
+}
+
+impl Builder {
+    pub fn new(edition: RustEdition, ta_config: TaConfig) -> Self {
+        Self {
+            out_dir: Option::None,
+            header_file_name: Option::None,
+            linker_type: Option::None,
+            edition,
+            ta_config,
+        }
+    }
+    pub fn out_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
+        self.out_dir = Option::Some(path.into());
+        self
+    }
+    pub fn header_file_name<S: Into<String>>(mut self, file_name: S) -> Self {
+        self.header_file_name = Option::Some(file_name.into());
+        self
+    }
+    pub fn linker_type(mut self, linker_type: LinkerType) -> Self {
+        self.linker_type = Option::Some(linker_type);
+        self
+    }
+    pub fn build(self) -> Result<(), Error> {
+        let out_dir = match self.out_dir.clone() {
+            Some(v) => v,
+            None => PathBuf::from(std::env::var("OUT_DIR")?),
+        };
+        self.write_header_file(out_dir.clone())?;
+        self.link(out_dir)?;
+        Ok(())
+    }
+}
+
+impl Builder {
+    fn write_header_file(&self, out: PathBuf) -> Result<(), Error> {
+        let out_header_file_name = out.join(match self.header_file_name.as_ref() {
+            Some(v) => v.as_str(),
+            None => DEFAULT_HEADER_FILE_NAME,
+        });
+        let mut buffer = File::create(out_header_file_name.clone())?;
+        let header_codes =
+            HeaderFileGenerator::new(self.edition.clone()).generate(&self.ta_config)?;
+        buffer.write_all(header_codes.as_bytes())?;
+        Ok(())
+    }
+
+    fn link(&self, out_dir: PathBuf) -> Result<(), Error> {
+        let linker = match self.linker_type.as_ref() {
+            Option::Some(v) => Linker::new(v.clone()),
+            Option::None => Linker::auto(),
+        };
+        linker.link_all(out_dir)
+    }
+}
diff --git a/optee-utee-build/src/code_generator.rs b/optee-utee-build/src/code_generator.rs
new file mode 100644
index 0000000..b3f311d
--- /dev/null
+++ b/optee-utee-build/src/code_generator.rs
@@ -0,0 +1,360 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::Error;
+use crate::{PropertyValue, TaConfig};
+use quote::{format_ident, quote};
+use std::str::FromStr;
+
+/// Start from rust edition 2024, `no_mangle` and `link_section` must be wrapped with unsafe
+#[derive(Clone)]
+pub enum RustEdition {
+    Before2024,
+    Edition2024,
+}
+
+/// Generator of head file, use it to generate a header file and then include it in user codes.
+///
+/// Use only if you just want to generate a header file, and do the linking job yourself,
+/// or you should use Builder instead.
+///
+/// Examples:
+/// ```rust
+/// use optee_utee_build::{HeaderFileGenerator, TaConfig, RustEdition};
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "26509cec-4a2b-4935-87ab-762d89fbf0b0";
+/// let ta_config = TaConfig::new_default(UUID, "0.1.0", "example")?;
+/// let codes = HeaderFileGenerator::new(RustEdition::Before2024).generate(&ta_config)?;
+/// # Ok(())
+/// # }
+/// ```
+pub struct HeaderFileGenerator {
+    code: proc_macro2::TokenStream,
+    edition: RustEdition,
+}
+
+impl HeaderFileGenerator {
+    pub fn new(edition: RustEdition) -> Self {
+        Self {
+            code: quote!(),
+            edition,
+        }
+    }
+    pub fn generate(mut self, conf: &TaConfig) -> Result<String, Error> {
+        self.write_includes();
+        self.write_configurations(conf);
+        self.write_trace(conf);
+        self.write_properties(conf)?;
+        self.write_ta_head(conf)?;
+        self.write_ta_heap();
+
+        const LICENSE_STR: &str = include_str!("./license_str.txt");
+        let f = syn::parse2(self.code).unwrap();
+        // prettyplease will remove all of the comments in it, and the
+        // maintainer will not support keeping comments,
+        // so we just add the comments to codes after formatting
+        let code_string = format!("{}\n{}", LICENSE_STR, prettyplease::unparse(&f));
+        Ok(code_string)
+    }
+}
+
+impl HeaderFileGenerator {
+    fn write_includes(&mut self) {
+        self.code.extend(quote! {
+        use core::ffi::*;
+        use core::mem;
+        use core::primitive::u64;
+                });
+    }
+
+    fn write_trace(&mut self, conf: &TaConfig) {
+        let trace_ext = string_to_binary_codes(&conf.trace_ext_prefix);
+        let trace_level = conf.trace_level;
+        let no_mangle_attribute = self.edition.no_mangle_attribute_codes();
+        self.code.extend(quote! {
+        #no_mangle_attribute
+        pub static mut trace_level: c_int = #trace_level;
+
+        #no_mangle_attribute
+        pub static trace_ext_prefix: &[u8] = #trace_ext;
+
+        #no_mangle_attribute
+        pub unsafe extern "C" fn tahead_get_trace_level() -> c_int {
+            unsafe { return trace_level; }
+        }
+                })
+    }
+    fn write_configurations(&mut self, conf: &TaConfig) {
+        let ta_version = string_to_binary_codes(&conf.ta_version);
+        let ta_description = string_to_binary_codes(&conf.ta_description);
+        let ta_flags = conf.ta_flags;
+        let ta_data_size = conf.ta_data_size;
+        let ta_stack_size = conf.ta_stack_size;
+        self.code.extend(quote! {
+        const TA_FLAGS: u32 = #ta_flags;
+        const TA_DATA_SIZE: u32 = #ta_data_size;
+        const TA_STACK_SIZE: u32 = #ta_stack_size;
+        const TA_VERSION: &[u8] = #ta_version;
+        const TA_DESCRIPTION: &[u8] = #ta_description;
+                });
+    }
+    fn write_properties(&mut self, conf: &TaConfig) -> Result<(), Error> {
+        let mut ext_property_codes =
+            Vec::<proc_macro2::TokenStream>::with_capacity(conf.ext_properties.len());
+        for (index, prop) in conf.ext_properties.iter().enumerate() {
+            let var_name = format!("EXT_PROP_VALUE_{}", index + 1);
+            let rust_type_name_codes = property_value_rust_type_declaration_codes(&prop.value);
+            let value_codes = property_value_data_codes(&prop.value)?;
+            let var_name_codes = format_ident!("{}", var_name);
+            self.code.extend(quote! {
+            const #var_name_codes: #rust_type_name_codes = #value_codes;
+                        });
+            let prop_name_codes = string_to_binary_codes(&prop.name);
+            let utee_type_name_codes = property_value_utee_type_codes(&prop.value);
+            let utee_value_conv_codes = property_value_as_utee_value_codes(&var_name, &prop.value);
+            ext_property_codes.push(quote! {
+                optee_utee_sys::user_ta_property {
+                    name: #prop_name_codes.as_ptr(),
+                    prop_type: #utee_type_name_codes,
+                    value: #utee_value_conv_codes,
+                }
+            });
+        }
+
+        const ORIGIN_PROPERTY_LEN: usize = 7;
+        let property_len = ORIGIN_PROPERTY_LEN + conf.ext_properties.len();
+        let no_mangle_attribute = self.edition.no_mangle_attribute_codes();
+        self.code.extend(quote! {
+        static FLAG_BOOL: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_SINGLE_INSTANCE) != 0;
+        static FLAG_MULTI: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_MULTI_SESSION) != 0;
+        static FLAG_INSTANCE: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_INSTANCE_KEEP_ALIVE) != 0;
+        #no_mangle_attribute
+        pub static ta_num_props: usize = #property_len;
+        #no_mangle_attribute
+        pub static ta_props: [optee_utee_sys::user_ta_property; #property_len] = [
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_SINGLE_INSTANCE,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+                value: &FLAG_BOOL as *const bool as *mut _,
+            },
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_MULTI_SESSION,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+                value: &FLAG_MULTI as *const bool as *mut _,
+            },
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_KEEP_ALIVE,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+                value: &FLAG_INSTANCE as *const bool as *mut _,
+            },
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_DATA_SIZE,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
+                value: &TA_DATA_SIZE as *const u32 as *mut _,
+            },
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_STACK_SIZE,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
+                value: &TA_STACK_SIZE as *const u32 as *mut _,
+            },
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_VERSION,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
+                value: TA_VERSION as *const [u8] as *mut _,
+            },
+            optee_utee_sys::user_ta_property {
+                name: optee_utee_sys::TA_PROP_STR_DESCRIPTION,
+                prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
+                value: TA_DESCRIPTION as *const [u8] as *mut _,
+            },
+            #(#ext_property_codes),*
+        ];
+                });
+
+        Ok(())
+    }
+    fn write_ta_head(&mut self, conf: &TaConfig) -> Result<(), Error> {
+        let uuid_value_codes = uuid_to_tee_uuid_value_codes(&conf.uuid)?;
+        let stack_size = conf.ta_stack_size + conf.ta_framework_stack_size;
+        let no_mangle_attribute = self.edition.no_mangle_attribute_codes();
+        let ta_head_session_attribute = self.edition.link_section_attribute_codes(".ta_head");
+        self.code.extend(quote! {
+        #no_mangle_attribute
+        #ta_head_session_attribute
+        pub static ta_head: optee_utee_sys::ta_head = optee_utee_sys::ta_head {
+            uuid: #uuid_value_codes,
+            stack_size: #stack_size,
+            flags: TA_FLAGS,
+            depr_entry: u64::MAX,
+        };
+                });
+
+        Ok(())
+    }
+    fn write_ta_heap(&mut self) {
+        let no_mangle_attribute = self.edition.no_mangle_attribute_codes();
+        let bss_session_attribute = self.edition.link_section_attribute_codes(".bss");
+        self.code.extend(quote! {
+        #no_mangle_attribute
+        #bss_session_attribute
+        pub static ta_heap: [u8; TA_DATA_SIZE as usize] = [0; TA_DATA_SIZE as usize];
+
+        #no_mangle_attribute
+        pub static ta_heap_size: usize = mem::size_of::<u8>() * TA_DATA_SIZE as usize;
+                })
+    }
+}
+
+fn property_value_data_codes(value: &PropertyValue) -> Result<proc_macro2::TokenStream, Error> {
+    match value {
+        PropertyValue::U32(v) => Ok(quote! { #v }),
+        PropertyValue::U64(v) => Ok(quote! { #v }),
+        PropertyValue::Bool(v) => Ok(quote! { #v }),
+        PropertyValue::Uuid(v) => uuid_to_tee_uuid_value_codes(v),
+        PropertyValue::Str(v) => Ok(string_to_binary_codes(v)),
+        PropertyValue::BinaryBlock(v) => Ok(string_to_binary_codes(v)),
+        PropertyValue::Identity(login, uuid) => {
+            identity_to_tee_identity_value_codes(login.clone(), &uuid)
+        }
+    }
+}
+
+fn uuid_to_tee_uuid_value_codes(uuid: &uuid::Uuid) -> Result<proc_macro2::TokenStream, Error> {
+    let (time_low, time_mid, time_hi_and_version, clock_seq_and_node) = uuid.as_fields();
+    Ok(quote! {
+    optee_utee_sys::TEE_UUID {
+        timeLow: #time_low,
+        timeMid: #time_mid,
+        timeHiAndVersion: #time_hi_and_version,
+        clockSeqAndNode: [#(#clock_seq_and_node),* ],
+    }
+        })
+}
+
+fn identity_to_tee_identity_value_codes(
+    login: u32,
+    uuid: &uuid::Uuid,
+) -> Result<proc_macro2::TokenStream, Error> {
+    let tee_uuid_codes = uuid_to_tee_uuid_value_codes(uuid)?;
+    Ok(quote! {
+        optee_utee_sys::TEE_Identity {
+            login: #login,
+            uuid: #tee_uuid_codes,
+        }
+    })
+}
+
+fn property_value_rust_type_declaration_codes(value: &PropertyValue) -> proc_macro2::TokenStream {
+    proc_macro2::TokenStream::from_str(match value {
+        PropertyValue::U32(_) => "u32",
+        PropertyValue::U64(_) => "u64",
+        PropertyValue::Bool(_) => "bool",
+        PropertyValue::Uuid(_) => "optee_utee_sys::TEE_UUID",
+        PropertyValue::Str(_) => "&[u8]",
+        PropertyValue::BinaryBlock(_) => "&[u8]",
+        PropertyValue::Identity(..) => "optee_utee_sys::TEE_Identity",
+    })
+    .unwrap()
+}
+
+fn property_value_as_utee_value_codes(
+    var_name: &str,
+    value: &PropertyValue,
+) -> proc_macro2::TokenStream {
+    proc_macro2::TokenStream::from_str(
+        match value {
+            PropertyValue::U32(_) => format!("&{} as *const u32 as *mut _", var_name),
+            PropertyValue::U64(_) => format!("&{} as *const u64 as *mut _", var_name),
+            PropertyValue::Bool(_) => format!("&{} as *const bool as *mut _", var_name),
+            PropertyValue::Uuid(_) => {
+                format!("&{} as *const optee_utee_sys::TEE_UUID as *mut _", var_name)
+            }
+            PropertyValue::Str(_) => format!("{} as *const [u8] as *mut _", var_name),
+            PropertyValue::BinaryBlock(_) => format!("{} as *const [u8] as *mut _", var_name),
+            PropertyValue::Identity(..) => format!(
+                "&{} as *const optee_utee_sys::TEE_Identity as *mut _",
+                var_name
+            ),
+        }
+        .as_str(),
+    )
+    .unwrap()
+}
+
+fn property_value_utee_type_codes(value: &PropertyValue) -> proc_macro2::TokenStream {
+    proc_macro2::TokenStream::from_str(match value {
+        PropertyValue::U32(_) => "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32",
+        PropertyValue::U64(_) => "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U64",
+        PropertyValue::Bool(_) => "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL",
+        PropertyValue::Uuid(_) => "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_UUID",
+        PropertyValue::Str(_) => "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING",
+        PropertyValue::BinaryBlock(_) => {
+            "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BINARY_BLOCK"
+        }
+        PropertyValue::Identity(..) => {
+            "optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_IDENTITY"
+        }
+    })
+    .unwrap()
+}
+
+fn string_to_binary_codes(s: &str) -> proc_macro2::TokenStream {
+    let wrapped = format!("b\"{}\\0\"", s);
+    proc_macro2::TokenStream::from_str(&wrapped).unwrap()
+}
+
+impl RustEdition {
+    fn no_mangle_attribute_codes(&self) -> proc_macro2::TokenStream {
+        match self {
+            RustEdition::Before2024 => quote! { #[no_mangle] },
+            RustEdition::Edition2024 => quote! { #[unsafe(no_mangle)] },
+        }
+    }
+    fn link_section_attribute_codes(&self, session_name: &str) -> proc_macro2::TokenStream {
+        match self {
+            RustEdition::Before2024 => quote! { #[link_section = #session_name] },
+            RustEdition::Edition2024 => quote! { #[unsafe(link_section = #session_name)] },
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_edition_before_2024() {
+        let uuid = "26509cec-4a2b-4935-87ab-762d89fbf0b0";
+        let conf = TaConfig::new_default(uuid, "0.1.0", "test_before_2024")
+            .unwrap()
+            .ta_data_size(1 * 1024 * 1024);
+        let generator = HeaderFileGenerator::new(RustEdition::Before2024);
+        let codes = generator.generate(&conf).unwrap();
+        let exp_result = include_str!("../test_files/test_edition_before_2024_result.rs");
+        assert_eq!(codes, exp_result);
+    }
+    #[test]
+    fn test_edition_2024() {
+        let uuid = "26509cec-4a2b-4935-87ab-762d89fbf0b0";
+        let conf = TaConfig::new_default(uuid, "0.1.0", "test_edition_2024").unwrap();
+        let generator = HeaderFileGenerator::new(RustEdition::Edition2024);
+        let codes = generator.generate(&conf).unwrap();
+        let exp_result = include_str!("../test_files/test_edition_2024_result.rs");
+        assert_eq!(codes, exp_result);
+    }
+}
diff --git a/optee-utee-build/src/error.rs b/optee-utee-build/src/error.rs
new file mode 100644
index 0000000..010f9cb
--- /dev/null
+++ b/optee-utee-build/src/error.rs
@@ -0,0 +1,43 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#[derive(Debug)]
+pub enum Error {
+    Env(std::env::VarError),
+    Io(std::io::Error),
+    Uuid(uuid::Error),
+    PropertyNotFound(String),
+    InvalidVersion(String),
+}
+
+impl From<std::io::Error> for Error {
+    fn from(value: std::io::Error) -> Self {
+        Self::Io(value)
+    }
+}
+
+impl From<std::env::VarError> for Error {
+    fn from(value: std::env::VarError) -> Self {
+        Self::Env(value)
+    }
+}
+
+impl From<uuid::Error> for Error {
+    fn from(value: uuid::Error) -> Self {
+        Self::Uuid(value)
+    }
+}
diff --git a/optee-utee-build/src/lib.rs b/optee-utee-build/src/lib.rs
new file mode 100644
index 0000000..644b0bf
--- /dev/null
+++ b/optee-utee-build/src/lib.rs
@@ -0,0 +1,47 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+mod builder;
+mod code_generator;
+mod error;
+mod linker;
+mod ta_config;
+
+pub use builder::*;
+pub use code_generator::*;
+pub use error::Error;
+pub use linker::*;
+pub use ta_config::*;
+pub use uuid::Uuid;
+
+/// a build method, use it for TA compilation
+/// Usage:
+/// ```no_run
+/// use optee_utee_build::{TaConfig, RustEdition};
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default(UUID, "0.1.0", "example")?;
+/// optee_utee_build::build(RustEdition::Before2024, ta_config)?;
+/// # Ok(())
+/// # }
+/// ```
+///
+/// You may check the Builder struct if you need some customizations.
+pub fn build(edition: RustEdition, config: TaConfig) -> Result<(), Error> {
+    Builder::new(edition, config).build()
+}
diff --git a/optee-utee-build/src/license_str.txt b/optee-utee-build/src/license_str.txt
new file mode 100644
index 0000000..b248758
--- /dev/null
+++ b/optee-utee-build/src/license_str.txt
@@ -0,0 +1,16 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
diff --git a/optee-utee-build/src/linker.rs b/optee-utee-build/src/linker.rs
new file mode 100644
index 0000000..d264359
--- /dev/null
+++ b/optee-utee-build/src/linker.rs
@@ -0,0 +1,190 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::env;
+use std::fs::File;
+use std::io::Write;
+use std::io::{BufRead, BufReader};
+use std::path::PathBuf;
+
+use crate::Error;
+
+/// The type of the linker, there are difference when using gcc/cc or ld/lld as  
+/// linker, For example, `--sort-section=alignment` parameter changes to  
+/// `-Wl,--sort-section=alignment` when using gcc as linker.
+///
+/// Cc: gcc, cc, etc.
+/// Ld: ld, lld, ld.bfd, ld.gold, etc.
+#[derive(Debug, Clone)]
+pub enum LinkerType {
+    Cc,
+    Ld,
+}
+
+/// Linker of ta, use it to handle all linking stuff.
+///
+/// Use only if you just want to handle the linking stuff, and use a  
+/// hand-written user_ta_header.rs, or you should use Builder instead.
+/// Usage:
+///
+/// ```no_run
+/// use optee_utee_build::Linker;
+/// use std::env;
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// let out_dir = env::var("OUT_DIR")?;
+/// Linker::auto().link_all(out_dir)?;
+/// # Ok(())
+/// # }
+/// ```
+///
+/// We detect the type of the linker automatically, you can set it manually if
+/// you met some problems with it.
+/// ```no_run
+/// use optee_utee_build::{Linker, LinkerType};
+/// use std::env;
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// let out_dir = env::var("OUT_DIR")?;
+/// Linker::new(LinkerType::Cc).link_all(out_dir)?;
+/// # Ok(())
+/// # }
+/// ```
+///
+pub struct Linker {
+    linker_type: LinkerType,
+}
+
+impl Linker {
+    /// Construct a Linker by manually specific the type of linker, you may use
+    /// `auto`, it would detect current linker automatically.
+    pub fn new(linker_type: LinkerType) -> Self {
+        Self { linker_type }
+    }
+    /// Construct a Linker by auto detect the type of linker, try `new` function
+    ///  if our detection mismatch.
+    pub fn auto() -> Self {
+        Self {
+            linker_type: Self::auto_detect_linker_type(),
+        }
+    }
+    /// Handle all the linking stuff.
+    ///
+    /// param out_dir is used for putting some generated files that linker would
+    ///  use.
+    pub fn link_all<P: Into<PathBuf>>(self, out_dir: P) -> Result<(), Error> {
+        const ENV_TA_DEV_KIT_DIR: &str = "TA_DEV_KIT_DIR";
+        println!("cargo:rerun-if-env-changed={}", ENV_TA_DEV_KIT_DIR);
+        let ta_dev_kit_dir = PathBuf::from(std::env::var(ENV_TA_DEV_KIT_DIR)?);
+        let out_dir: PathBuf = out_dir.into();
+
+        self.write_and_set_linker_script(out_dir.clone(), ta_dev_kit_dir.clone())?;
+
+        let search_path = ta_dev_kit_dir.join("lib");
+        println!("cargo:rustc-link-search={}", search_path.display());
+        println!("cargo:rustc-link-lib=static=utee");
+        println!("cargo:rustc-link-lib=static=utils");
+        println!("cargo:rustc-link-arg=-e__ta_entry");
+        println!("cargo:rustc-link-arg=-pie");
+        println!("cargo:rustc-link-arg=-Os");
+        match self.linker_type {
+            LinkerType::Cc => println!("cargo:rustc-link-arg=-Wl,--sort-section=alignment"),
+            LinkerType::Ld => println!("cargo:rustc-link-arg=--sort-section=alignment"),
+        };
+        let mut dyn_list = File::create(out_dir.join("dyn_list"))?;
+        write!(
+            dyn_list,
+            "{{ __elf_phdr_info; trace_ext_prefix; trace_level; ta_head; }};\n"
+        )?;
+        match self.linker_type {
+            LinkerType::Cc => println!("cargo:rustc-link-arg=-Wl,--dynamic-list=dyn_list"),
+            LinkerType::Ld => println!("cargo:rustc-link-arg=--dynamic-list=dyn_list"),
+        }
+
+        Ok(())
+    }
+}
+
+impl Linker {
+    // generate a link script file for cc/ld, and link to it
+    fn write_and_set_linker_script(
+        &self,
+        out_dir: PathBuf,
+        ta_dev_kit_dir: PathBuf,
+    ) -> Result<(), Error> {
+        const ENV_TARGET_TA: &str = "TARGET_TA";
+        println!("cargo:rerun-if-env-changed={}", ENV_TARGET_TA);
+        let mut aarch64_flag = true;
+        match env::var(ENV_TARGET_TA) {
+            Ok(ref v) if v == "arm-unknown-linux-gnueabihf" || v == "arm-unknown-optee" => {
+                match self.linker_type {
+                    LinkerType::Cc => println!("cargo:rustc-link-arg=-Wl,--no-warn-mismatch"),
+                    LinkerType::Ld => println!("cargo:rustc-link-arg=--no-warn-mismatch"),
+                };
+                aarch64_flag = false;
+            }
+            _ => {}
+        };
+
+        let f = BufReader::new(File::open(ta_dev_kit_dir.join("src/ta.ld.S"))?);
+        let ta_lds_file_path = out_dir.join("ta.lds");
+        let mut ta_lds = File::create(ta_lds_file_path.clone())?;
+        for line in f.lines() {
+            let l = line?;
+
+            if aarch64_flag {
+                if l.starts_with('#')
+                    || l == "OUTPUT_FORMAT(\"elf32-littlearm\")"
+                    || l == "OUTPUT_ARCH(arm)"
+                {
+                    continue;
+                }
+            } else {
+                if l.starts_with('#')
+                    || l == "OUTPUT_FORMAT(\"elf64-littleaarch64\")"
+                    || l == "OUTPUT_ARCH(aarch64)"
+                {
+                    continue;
+                }
+            }
+
+            if l == "\t. = ALIGN(4096);" {
+                write!(ta_lds, "\t. = ALIGN(65536);\n")?;
+            } else {
+                write!(ta_lds, "{}\n", l)?;
+            }
+        }
+
+        println!("cargo:rustc-link-search={}", out_dir.display());
+        println!("cargo:rerun-if-changed={}", ta_lds_file_path.display());
+        println!("cargo:rustc-link-arg=-T{}", ta_lds_file_path.display());
+        Ok(())
+    }
+
+    fn auto_detect_linker_type() -> LinkerType {
+        const ENV_RUSTC_LINKER: &str = "RUSTC_LINKER";
+        println!("cargo:rerun-if-env-changed={}", ENV_RUSTC_LINKER);
+        match env::var(ENV_RUSTC_LINKER) {
+            Ok(ref linker_name)
+                if linker_name.ends_with("ld") || linker_name.ends_with("ld.bfd") =>
+            {
+                LinkerType::Ld
+            }
+            _ => LinkerType::Cc,
+        }
+    }
+}
diff --git a/optee-utee-build/src/ta_config.rs b/optee-utee-build/src/ta_config.rs
new file mode 100644
index 0000000..038e6ea
--- /dev/null
+++ b/optee-utee-build/src/ta_config.rs
@@ -0,0 +1,193 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+use crate::Error;
+use std::convert::TryInto;
+
+/// Configuration options for TA
+///
+/// Examples
+///
+/// # use a default configuration
+/// ```rust
+/// use optee_utee_build::TaConfig;
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default(
+///     UUID,
+///     "0.1.0",
+///     "hello world",
+/// )?;
+/// # Ok(())
+/// # }
+/// ```
+///
+/// and since we already have `version` and `description` in `cargo.toml`,
+/// we can make it simpler by using them as parameters:
+///
+/// ```rust
+/// use optee_utee_build::TaConfig;
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default_with_cargo_env(UUID)?;
+/// # Ok(())
+/// # }
+/// ```
+///
+/// # make some modifications
+/// ```rust
+/// use optee_utee_build::TaConfig;
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// let ta_config = TaConfig::new_default(
+///     UUID,
+///     "0.1.0",
+///     "hello world",
+/// )?.ta_stack_size(10 * 1024).ta_data_size(32 * 1024);
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Debug, Clone)]
+pub struct TaConfig {
+    pub uuid: uuid::Uuid,
+    pub ta_flags: u32,
+    pub ta_data_size: u32,
+    pub ta_stack_size: u32,
+    pub ta_version: String,
+    pub ta_description: String,
+    pub trace_level: i32,
+    pub trace_ext_prefix: String,
+    pub ta_framework_stack_size: u32,
+    pub ext_properties: Vec<Property>,
+}
+
+impl TaConfig {
+    /// Generate a default config by uuid, this is a wrapper of `new_default`
+    /// function, it retrieves version and description from your TA's cargo.toml
+    /// by environment-variables provided by cargo for building script, make
+    /// constructor simpler.
+    ///
+    /// If your version and description of TA are different with the version and
+    /// description of your crate, use `new_default` to provide them manually.
+    pub fn new_default_with_cargo_env(uuid_str: &str) -> Result<Self, Error> {
+        Self::new_default(
+            uuid_str,
+            std::env::var("CARGO_PKG_VERSION")?.as_str(),
+            std::env::var("CARGO_PKG_DESCRIPTION")?.as_str(),
+        )
+    }
+    /// generate a default config
+    pub fn new_default(
+        uuid_str: &str,
+        ta_version: &str,
+        ta_description: &str,
+    ) -> Result<Self, Error> {
+        Ok(Self {
+            uuid: uuid_str.try_into()?,
+            ta_flags: 0,
+            ta_data_size: 32 * 1024,
+            ta_stack_size: 2 * 1024,
+            ta_version: ta_version.to_string(),
+            ta_description: ta_description.to_string(),
+            trace_level: 4,
+            trace_ext_prefix: "TA".to_string(),
+            ta_framework_stack_size: 2048,
+            ext_properties: Vec::new(),
+        })
+    }
+    pub fn ta_flags(mut self, flags: u32) -> Self {
+        self.ta_flags = flags;
+        self
+    }
+    pub fn ta_stack_size(mut self, stack_size: u32) -> Self {
+        self.ta_stack_size = stack_size;
+        self
+    }
+    pub fn ta_data_size(mut self, size: u32) -> Self {
+        self.ta_data_size = size;
+        self
+    }
+    pub fn trace_level(mut self, level: i32) -> Self {
+        self.trace_level = level;
+        self
+    }
+    pub fn trace_ext_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
+        self.trace_ext_prefix = prefix.into();
+        self
+    }
+    pub fn ta_framework_stack_size(mut self, stack_size: u32) -> Self {
+        self.ta_framework_stack_size = stack_size;
+        self
+    }
+    pub fn add_ext_property(mut self, name: &str, value: PropertyValue) -> Self {
+        self.ext_properties.push(Property::new(name, value));
+        self
+    }
+}
+
+/// An enum of PropertyValue, with its type and value combined
+///
+/// Usage:
+/// ```rust
+/// # use optee_utee_build::Error;
+/// # fn main() -> Result<(), Error> {
+/// # use optee_utee_build::PropertyValue;
+/// # use std::convert::TryInto;
+/// # const UUID: &str = "d93c2970-b1a6-4b86-90ac-b42830e78d9b";
+/// # const LOGIN: u32 = 1;
+/// PropertyValue::Bool(true);
+/// PropertyValue::U32(1);
+/// PropertyValue::Uuid(UUID.try_into()?);
+/// PropertyValue::Identity(LOGIN, UUID.try_into()?);
+/// // a string value, must not append '\0' at last, we will add it for you.
+/// PropertyValue::Str("hello world".to_string());
+/// // a base64 string value, must not append '\0' at last, we will add it for you.
+/// PropertyValue::BinaryBlock("c2RmYXNm".to_string());
+/// PropertyValue::U64(1);
+/// # Ok(())
+/// # }
+#[derive(Debug, Clone)]
+pub enum PropertyValue {
+    Bool(bool),
+    U32(u32),
+    Uuid(uuid::Uuid),
+    Identity(u32, uuid::Uuid),
+    Str(String),
+    BinaryBlock(String),
+    U64(u64),
+}
+
+/// A GP property pair, use it to set ta_properties
+///
+/// must not append a '\0' in name, we will add it automatically if neccessary.
+#[derive(Debug, Clone)]
+pub struct Property {
+    pub name: String,
+    /// value of the property
+    pub value: PropertyValue,
+}
+
+impl Property {
+    pub fn new(name: &str, value: PropertyValue) -> Self {
+        Self {
+            name: name.to_string(),
+            value,
+        }
+    }
+}
diff --git a/optee-utee-build/test_files/test_edition_2024_result.rs b/optee-utee-build/test_files/test_edition_2024_result.rs
new file mode 100644
index 0000000..cea8231
--- /dev/null
+++ b/optee-utee-build/test_files/test_edition_2024_result.rs
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use core::ffi::*;
+use core::mem;
+use core::primitive::u64;
+const TA_FLAGS: u32 = 0u32;
+const TA_DATA_SIZE: u32 = 32768u32;
+const TA_STACK_SIZE: u32 = 2048u32;
+const TA_VERSION: &[u8] = b"0.1.0\0";
+const TA_DESCRIPTION: &[u8] = b"test_edition_2024\0";
+#[unsafe(no_mangle)]
+pub static mut trace_level: c_int = 4i32;
+#[unsafe(no_mangle)]
+pub static trace_ext_prefix: &[u8] = b"TA\0";
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn tahead_get_trace_level() -> c_int {
+    unsafe {
+        return trace_level;
+    }
+}
+static FLAG_BOOL: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_SINGLE_INSTANCE) != 0;
+static FLAG_MULTI: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_MULTI_SESSION) != 0;
+static FLAG_INSTANCE: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_INSTANCE_KEEP_ALIVE)
+    != 0;
+#[unsafe(no_mangle)]
+pub static ta_num_props: usize = 7usize;
+#[unsafe(no_mangle)]
+pub static ta_props: [optee_utee_sys::user_ta_property; 7usize] = [
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_SINGLE_INSTANCE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+        value: &FLAG_BOOL as *const bool as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_MULTI_SESSION,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+        value: &FLAG_MULTI as *const bool as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_KEEP_ALIVE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+        value: &FLAG_INSTANCE as *const bool as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_DATA_SIZE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
+        value: &TA_DATA_SIZE as *const u32 as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_STACK_SIZE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
+        value: &TA_STACK_SIZE as *const u32 as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_VERSION,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
+        value: TA_VERSION as *const [u8] as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_DESCRIPTION,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
+        value: TA_DESCRIPTION as *const [u8] as *mut _,
+    },
+];
+#[unsafe(no_mangle)]
+#[unsafe(link_section = ".ta_head")]
+pub static ta_head: optee_utee_sys::ta_head = optee_utee_sys::ta_head {
+    uuid: optee_utee_sys::TEE_UUID {
+        timeLow: 642817260u32,
+        timeMid: 18987u16,
+        timeHiAndVersion: 18741u16,
+        clockSeqAndNode: [135u8, 171u8, 118u8, 45u8, 137u8, 251u8, 240u8, 176u8],
+    },
+    stack_size: 4096u32,
+    flags: TA_FLAGS,
+    depr_entry: u64::MAX,
+};
+#[unsafe(no_mangle)]
+#[unsafe(link_section = ".bss")]
+pub static ta_heap: [u8; TA_DATA_SIZE as usize] = [0; TA_DATA_SIZE as usize];
+#[unsafe(no_mangle)]
+pub static ta_heap_size: usize = mem::size_of::<u8>() * TA_DATA_SIZE as usize;
diff --git a/optee-utee-build/test_files/test_edition_before_2024_result.rs b/optee-utee-build/test_files/test_edition_before_2024_result.rs
new file mode 100644
index 0000000..d2a4d6e
--- /dev/null
+++ b/optee-utee-build/test_files/test_edition_before_2024_result.rs
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use core::ffi::*;
+use core::mem;
+use core::primitive::u64;
+const TA_FLAGS: u32 = 0u32;
+const TA_DATA_SIZE: u32 = 1048576u32;
+const TA_STACK_SIZE: u32 = 2048u32;
+const TA_VERSION: &[u8] = b"0.1.0\0";
+const TA_DESCRIPTION: &[u8] = b"test_before_2024\0";
+#[no_mangle]
+pub static mut trace_level: c_int = 4i32;
+#[no_mangle]
+pub static trace_ext_prefix: &[u8] = b"TA\0";
+#[no_mangle]
+pub unsafe extern "C" fn tahead_get_trace_level() -> c_int {
+    unsafe {
+        return trace_level;
+    }
+}
+static FLAG_BOOL: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_SINGLE_INSTANCE) != 0;
+static FLAG_MULTI: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_MULTI_SESSION) != 0;
+static FLAG_INSTANCE: bool = (TA_FLAGS & optee_utee_sys::TA_FLAG_INSTANCE_KEEP_ALIVE)
+    != 0;
+#[no_mangle]
+pub static ta_num_props: usize = 7usize;
+#[no_mangle]
+pub static ta_props: [optee_utee_sys::user_ta_property; 7usize] = [
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_SINGLE_INSTANCE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+        value: &FLAG_BOOL as *const bool as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_MULTI_SESSION,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+        value: &FLAG_MULTI as *const bool as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_KEEP_ALIVE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_BOOL,
+        value: &FLAG_INSTANCE as *const bool as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_DATA_SIZE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
+        value: &TA_DATA_SIZE as *const u32 as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_STACK_SIZE,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_U32,
+        value: &TA_STACK_SIZE as *const u32 as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_VERSION,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
+        value: TA_VERSION as *const [u8] as *mut _,
+    },
+    optee_utee_sys::user_ta_property {
+        name: optee_utee_sys::TA_PROP_STR_DESCRIPTION,
+        prop_type: optee_utee_sys::user_ta_prop_type::USER_TA_PROP_TYPE_STRING,
+        value: TA_DESCRIPTION as *const [u8] as *mut _,
+    },
+];
+#[no_mangle]
+#[link_section = ".ta_head"]
+pub static ta_head: optee_utee_sys::ta_head = optee_utee_sys::ta_head {
+    uuid: optee_utee_sys::TEE_UUID {
+        timeLow: 642817260u32,
+        timeMid: 18987u16,
+        timeHiAndVersion: 18741u16,
+        clockSeqAndNode: [135u8, 171u8, 118u8, 45u8, 137u8, 251u8, 240u8, 176u8],
+    },
+    stack_size: 4096u32,
+    flags: TA_FLAGS,
+    depr_entry: u64::MAX,
+};
+#[no_mangle]
+#[link_section = ".bss"]
+pub static ta_heap: [u8; TA_DATA_SIZE as usize] = [0; TA_DATA_SIZE as usize];
+#[no_mangle]
+pub static ta_heap_size: usize = mem::size_of::<u8>() * TA_DATA_SIZE as usize;
diff --git a/setup.sh b/setup.sh
index d12b817..ac7a0fd 100755
--- a/setup.sh
+++ b/setup.sh
@@ -44,4 +44,8 @@ cargo --version >/dev/null
 
 ##########################################
 # install toolchain
-apt update && apt -y install gcc-aarch64-linux-gnu gcc-arm-linux-gnueabihf
+if [[ "$(uname -m)" == "aarch64" ]]; then
+    apt update && apt -y install gcc gcc-arm-linux-gnueabihf
+else
+    apt update && apt -y install gcc-aarch64-linux-gnu gcc-arm-linux-gnueabihf
+fi


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org