Skip to content

Commit

Permalink
1. add optee-utee-build crate
Browse files Browse the repository at this point in the history
2. use optee-utee-build to build hello_world example
3. fix pipeline
  • Loading branch information
ivila committed Dec 20, 2024
1 parent 9b1af78 commit 128540f
Show file tree
Hide file tree
Showing 14 changed files with 840 additions and 146 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ jobs:
curl https://storage.googleapis.com/git-repo-downloads/repo-1 > ~/bin/repo && chmod a+x ~/bin/repo
export PATH=~/bin:$PATH
mkdir -p ~/optee-qemuv8 && cd ~/optee-qemuv8 &&
repo init -u https://github.com/OP-TEE/manifest.git -m qemu_v8.xml &&
repo init -u https://github.com/OP-TEE/manifest.git -b 4.4.0 -m qemu_v8.xml &&
repo sync -j4 --no-clone-bundle
- name: Build images and run tests
run: |
Expand Down Expand Up @@ -221,7 +221,7 @@ jobs:
curl https://storage.googleapis.com/git-repo-downloads/repo-1 > ~/bin/repo && chmod a+x ~/bin/repo
export PATH=~/bin:$PATH
mkdir -p ~/optee-qemuv8 && cd ~/optee-qemuv8 &&
repo init -u https://github.com/OP-TEE/manifest.git -m qemu_v8.xml &&
repo init -u https://github.com/OP-TEE/manifest.git -b 4.4.0 -m qemu_v8.xml &&
repo sync -j4 --no-clone-bundle
- name: Build images and run tests
run: |
Expand Down
1 change: 1 addition & 0 deletions .licenserc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ header:
- 'DISCLAIMER-WIP'
- '*.json'
- 'examples/tls_server-rs/ta/test-ca/**'
- 'optee-utee-build/test_files/**'
2 changes: 1 addition & 1 deletion examples/hello_world-rs/ta/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ optee-utee-sys = { path = "../../../optee-utee/optee-utee-sys" }
optee-utee = { path = "../../../optee-utee" }

[build_dependencies]
uuid = { version = "1.6.1", default-features = false }
proto = { path = "../proto" }
optee-utee-build = { path = "../../../optee-utee-build" }

[profile.release]
panic = "abort"
Expand Down
2 changes: 1 addition & 1 deletion examples/hello_world-rs/ta/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ 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\"
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
Expand Down
86 changes: 4 additions & 82 deletions examples/hello_world-rs/ta/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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_standard("0.1", "This is a hello world example.", "Hello World TA");
optee_utee_build::build(RustEdition::Before2024, proto::UUID, 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(())
}
12 changes: 0 additions & 12 deletions examples/hello_world-rs/ta/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
32 changes: 32 additions & 0 deletions optee-utee-build/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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 <[email protected]>"]
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"
150 changes: 150 additions & 0 deletions optee-utee-build/src/builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// 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::code_generator;
use crate::Error;
use crate::RustEdition;
use crate::TAConfig;

const DEFAULT_HEADER_FILE_NAME: &str = "user_ta_header.rs";

pub struct Config {
out_dir: Option<PathBuf>,
edition: RustEdition,
header_file_name: Option<String>,
ta_config: TAConfig,
}

impl Config {
pub fn new(edition: RustEdition, ta_config: TAConfig) -> Self {
Self {
out_dir: Option::None,
header_file_name: 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 build(self, uuid: &str) -> Result<(), Error> {
let out = match self.out_dir.clone() {
Some(v) => v,
None => PathBuf::from(std::env::var("OUT_DIR")?),
};
self.write_header_file(out.clone(), uuid)?;
self.link(out)?;
Ok(())
}
}

impl Config {
fn write_header_file(&self, out: PathBuf, uuid: &str) -> 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 = code_generator::generate(self.edition.clone(), &self.ta_config, uuid)?;
buffer.write_all(header_codes.as_bytes())?;
Ok(())
}

fn write_and_link_ta_lds(&self, out: 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" => {
println!("cargo:rustc-link-arg=-Wl,--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.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.display());
println!("cargo:rerun-if-changed={}", ta_lds_file_path.display());
println!("cargo:rustc-link-arg=-T{}", ta_lds_file_path.display());
Ok(())
}

fn link(&self, out: PathBuf) -> 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)?);

self.write_and_link_ta_lds(out.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");
println!("cargo:rustc-link-arg=-Wl,--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=-Wl,--dynamic-list=dyn_list");

Ok(())
}
}
Loading

0 comments on commit 128540f

Please sign in to comment.