初始提交

This commit is contained in:
2025-05-13 22:00:58 +08:00
commit e4c030b0c0
564 changed files with 78858 additions and 0 deletions

View File

@ -0,0 +1,51 @@
import argparse
import os
import shutil
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="copy_files_to_interim")
parser.add_argument('proj_root_dir', help="proj root dir")
args = parser.parse_args()
proj_root_dir = args.proj_root_dir
target_dir = os.path.join(proj_root_dir, "interim_binary", "ws63", "bin", "boot_bin")
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
hilink_target_dir = os.path.join(proj_root_dir, "interim_binary", "ws63", "bin", "hilink_bin")
if not os.path.isdir(hilink_target_dir):
os.makedirs(hilink_target_dir)
# key is src file, value is dest file or dir
copy_map = {
'output/ws63/acore/ws63-loaderboot/loaderboot.bin' : target_dir,
'output/ws63/acore/ws63-loaderboot/root_loaderboot_sign.bin' : target_dir,
'output/ws63/acore/ws63-liteos-app/efuse_cfg.bin' : target_dir,
'output/ws63/acore/ws63-ssb/ssb.bin' : target_dir,
'output/ws63/acore/ws63-ssb/ssb_sign.bin' : target_dir,
'output/ws63/acore/ws63-flashboot/flashboot.bin' : target_dir,
'output/ws63/acore/ws63-flashboot/flashboot_sign.bin' : target_dir,
'output/ws63/acore/ws63-flashboot/flashboot_backup_sign.bin' : target_dir,
'output/ws63/acore/ws63-liteos-hilink/ws63-liteos-hilink.bin' : hilink_target_dir,
'output/ws63/acore/ws63-liteos-hilink/ws63-liteos-hilink-sign.bin' : hilink_target_dir,
}
for src_file, dest in copy_map.items():
src_file = os.path.join(proj_root_dir, src_file)
if not os.path.isfile(src_file):
print(f'[!][copy_files_to_interim] File `{src_file}` not found, will skip it !')
continue
filename = src_file.split('/')[-1]
if dest != hilink_target_dir and not os.path.isfile(os.path.join(dest, filename)):
continue
try:
shutil.copy(src_file, dest)
except BaseException as e:
print(e)
exit(-1)

View File

@ -0,0 +1,2 @@
burn,name,start_bit,bit_width,value,lock
0,CHIP_ID,0,8,0x00000000,PG0
1 burn name start_bit bit_width value lock
2 0 CHIP_ID 0 8 0x00000000 PG0

View File

@ -0,0 +1,161 @@
#!/usr/bin/env python3
# coding=utf-8
import csv
import struct
import hashlib
import os
import re
from sys import version_info
def str_to_hex(s):
return ' '.join([hex(ord(c)).replace('0x', '') for c in s])
def print_bytes(bytes):
if version_info.major == 3:
c = bytes.hex()
print(c)
else:
c = bytes.encode('hex')
print(c)
number = 0
value_len = 0
buf = b''
csv_dir = os.path.split(os.path.realpath(__file__))[0]
csv_path = os.path.join(csv_dir, "efuse.csv")
bin_path = os.path.join(csv_dir + "/../../../../../output/ws63/acore/ws63-liteos-app/", 'efuse_cfg.bin')
def get_flash_key_param():
cfg_file = os.path.join(csv_dir + "/../", 'sign_config', 'encry_config.cfg')
file1 = open(cfg_file)
omrk1=""
for line in file1:
rs = re.search("Omrk1=", line)
if rs:
omrk1 = line[6:-1]
if omrk1 == "":
raise Exception("ERR: get_flash_key_param err, omrk1 is null", cfg_file)
result = ""
for i in range(0, len(omrk1), 4):
result += (" " + omrk1[i:i+4])
line = ''.join(result[1:].split(" ")[::-1])
result = ""
for i in range(0, len(line), 8):
result += (" 0x" + line[i+4:i+8] + line[i:i+4])
file1.close()
return result[1:]
def get_root_key_hash():
cfg_file = os.path.join(csv_dir + "/../", 'sign_config', 'root_pubk.bin.hash')
file1 = open(cfg_file)
line = file1.readline()
if line == "":
raise Exception("ERR: get_root_key_hash err, hash is null", cfg_file)
result = ""
for i in range(0, len(line), 8):
result += (" 0x" + line[i+6:i+8] + line[i+4:i+6] + line[i+2:i+4] + line[i:i+2])
file1.close()
return result[1:]
def del_old_csv_key():
with open(csv_path, 'r') as file1:
lines = list(csv.reader(file1))
for line in lines[::-1]:
if 'sec_verify_enable' in line:
lines.remove(line)
elif 'otp_oem_mrk' in line:
lines.remove(line)
elif 'root_key_hash' in line:
lines.remove(line)
with open(csv_path, 'w') as file2:
writer = csv.writer(file2)
writer.writerows(lines)
def read_cfg_value(cfg_file, key):
with open(cfg_file) as f:
for line in f:
if not line.startswith('#') and '=' in line:
k, v = line.split('=')
if k.strip() == key:
return v.strip()
return None
def set_new_csv_key():
efuse_file = open(csv_path, 'a+', newline='')
root_pubk = os.path.join(csv_dir + "/../", 'sign_config', 'root_pubk.bin.hash')
cfg_file = os.path.join(csv_dir + "/../", 'sign_config', 'flash_bin_ecc.cfg')
sen_en = read_cfg_value(cfg_file, 'SignSuite')
# 安全启动开关&根公钥hash
if os.path.exists(root_pubk) and sen_en == '0':
sec_en = "\n1,sec_verify_enable,960,1,0x1,PG0"
root_key_hash = "\n1,root_key_hash,672,256,", get_root_key_hash() ,",PG5"
efuse_file.writelines(sec_en)
efuse_file.writelines(root_key_hash)
cfg_file = os.path.join(csv_dir + "/../", 'sign_config', 'liteos_app_bin_ecc.cfg')
encry_en = read_cfg_value(cfg_file, 'SignSuite')
PlainKey = read_cfg_value(cfg_file, 'PlainKey')
demo = '8ABDA082DB74753577FF2D1E7D79DAC7'
# flash加密秘钥
if encry_en == '1' and PlainKey != demo:
flash_key = "\n1,otp_oem_mrk,352,128,", get_flash_key_param() ,",PG3"
efuse_file.writelines(flash_key)
efuse_file.close()
def del_null_rows():
with open(csv_path, 'r') as file1:
reader = csv.reader(file1)
rows = [row for row in reader]
rows = [row for row in rows if any(row)]
with open(csv_path, 'w', newline='') as file2:
writer = csv.writer(file2)
writer.writerows(rows)
def set_key_to_eufse():
if os.path.exists(csv_path):
del_old_csv_key()
set_new_csv_key()
del_null_rows()
set_key_to_eufse()
# 用reader读取csv文件
#Use the reader to read the CSV file.
with open(csv_path, 'r') as csvFile:
reader = csv.reader(csvFile)
for line in reader:
if line and (line[0] == "1"):
size = int(line[3])
if (size <= 32):
value_len = 4
elif (size <= 64):
value_len = 8
else:
value_len = size // 8
result = struct.pack('BBHHH', 0, 8, int(line[2]), size, value_len)
value_str = line[4]
value_list = value_str.split(" ")
value_struct = b''
for i in range(value_len // 4):
value = int(value_list[i], 16)
value_struct = value_struct + struct.pack('I', value)
print_bytes(value_struct)
buf = buf + result + value_struct
number = number + 1
header = struct.pack('BBHIII', 0, 48, number, len(buf) + 48, 0, 0)
data = header + buf
data_len = len(data)
print("data size: ", data_len)
if data_len % 64 != 0:
max_size = int((data_len / 64)+1) * 64
if data_len < max_size:
data = data + bytes([0] * int(max_size - data_len))
print("finally size: ", len(data))
hash = hashlib.sha256(data).digest()
bin_data = hash + data
with open(bin_path, 'wb+') as f:
f.write(bin_data)

View File

@ -0,0 +1,270 @@
#!/usr/bin/env python3
# encoding=utf-8
# Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2022-2022. All rights reserved.
import os
import json
import sys
import platform
import subprocess
import shutil
import re
from utils.build_utils import root_path, exec_shell, compare_bin, output_root
from utils.indie_upgrade_utils import make_indie_upg_src, dump_indie_upg_check_file
from typing import Dict, Any
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
def do_cmd(target_name: str, hook_name: str, env: Dict[str, Any])->bool:
python_path = sys.executable
print("python path: ", python_path)
# 生成接口映射表
if hook_name == 'build_pre' and "CONFIG_SUPPORT_HILINK_INDIE_UPGRADE" in env.get("defines"):
if not make_indie_upg_src():
return False
# sdk中执行sample的编译守护
if hook_name == 'build_pre' and env.get('build_type', '') == 'GuardSDKSample':
print("==================env==================")
for k, v in env.items():
print(f"{k}:{v}")
print("==================env==================")
# 生成sdk
build_sdk()
# 切换当前工作目录
cwd = os.getcwd()
in_sdk_root = os.path.join(output_root,'package', 'ws63','sdk')
os.chdir(in_sdk_root)
# 在sdk中按设定的menuconfig配置编译
guard_sample(target_name, env)
os.chdir(cwd)
if target_name == "ws63-liteos-msmart" and hook_name == 'build_pre': # 源码编译
print("info: start build ws63-liteos-app for msmart in source.")
module_handle_script_path = os.path.join(root_path, "application", "samples", "custom", "ws63", "msmart", "build_module.py")
errcode = exec_shell([python_path, module_handle_script_path], None, True)
return True
if target_name == "ws63-liteos-app" and not config_check(root_path, "ws63-liteos-msmart") and os.path.isfile(os.path.join(root_path, "application", "samples", "custom", "ws63", "msmart", "build_module.py")) and hook_name == 'build_pre':
# SDK 编译 msmart
print("info: start build ws63-liteos-app for msmart in SDK.")
module_handle_script_path = os.path.join(root_path, "application", "samples", "custom", "ws63", "msmart", "build_module.py")
errcode = exec_shell([python_path, module_handle_script_path], None, True)
return True
target_array = ['ws63-flashboot', 'ws63-loaderboot']
if not os.path.isfile(os.path.join(root_path, "output", "ws63", "acore", "boot_bin", "flashboot.bin")) and target_name not in target_array and hook_name == 'build_pre':
print("flashboot start build .....")
errcode = exec_shell([python_path, 'build.py', 'ws63-flashboot'], None, True)
if not os.path.isfile(os.path.join(root_path, "output", "ws63", "acore", "boot_bin", "loaderboot.bin")) and target_name not in target_array and hook_name == 'build_pre':
print("loaderboot start build .....")
errcode = exec_shell([python_path, 'build.py', 'ws63-loaderboot'], None, True)
if hook_name == 'build_pre':
return True
if target_name == 'ws63-liteos-app' and root_path.endswith('output/sdk') and hook_name == 'build_post':
print("start build ws63-liteos-app-haier target")
# 海尔代码编译
build_haier_script = os.path.join(root_path, '../../application/samples/custom/ws63/haier/boards/HI3863/GCC/build.sh')
errcode = subprocess.run(['bash', build_haier_script])
if errcode.returncode != 0:
print("run build.sh failed!")
sys.exit(1)
# 拷贝海尔编译结果
src_folder = os.path.join(root_path, '../../application/samples/custom/ws63/haier/boards/HI3863/GCC/libs/libhrapplication.a')
dest_folder = os.path.join(root_path, '../../application/samples/custom/ws63/haier/boards/HI3863/sdk/application/ws63-liteos-app/libhrapplication.a')
shutil.copyfile(src_folder, dest_folder)
# 编译最终fwpkg
build_app_script = os.path.join(root_path, '../../application/samples/custom/ws63/haier/boards/HI3863/sdk/build.py')
errcode = exec_shell(['python3', build_app_script, "-c", "ws63-liteos-app"], None, True)
if errcode != 0:
print("build ws63-liteos-app-haier target failed!")
sys.exit(1)
# 拷贝最终编译结果到package目录
dest_folder = os.path.join(root_path, '../package/ws63/ws63_haier')
if os.path.exists(dest_folder):
print("ws63-liteos-app-haier exist")
return True
src_folder = os.path.join(root_path, '../../application/samples/custom/ws63/haier/boards/HI3863/sdk/output/ws63')
shutil.copytree(src_folder, dest_folder)
print("end build ws63-liteos-app-haier target")
return True
if target_name == 'ws63-liteos-mfg' and hook_name == 'build_post':
errcode = exec_shell([python_path, "build.py", "ws63-liteos-app"], None, True)
return True
if hook_name != 'build_post':
return True
if env.get('gen_mem_bin'):
script_path = os.path.join(SCRIPT_DIR, 'get_mem_bin.sh')
print("gen_mem_bin ing...")
errcode = exec_shell(['bash', script_path, root_path, target_name, env.get('bin_name')], None, True)
if errcode != 0:
print("gen_mem_bin failed!")
return False
print("gen_mem_bin done!")
if env.get('generate_efuse_bin'):
copy_py = os.path.join(SCRIPT_DIR, 'efuse_cfg_gen.py')
print("generate_efuse_bin ing...")
errcode = exec_shell([sys.executable, copy_py], None, True)
if errcode != 0:
print("generate_efuse_bin failed!")
return False
shutil.copy(os.path.join(root_path, 'output/ws63/acore/ws63-liteos-app/efuse_cfg.bin'), os.path.join(root_path, 'output/ws63/acore/boot_bin'))
print("generate_efuse_bin done!")
if env.get('copy_files_to_interim'):
# copy_files_to_interim
copy_py = os.path.join(SCRIPT_DIR, 'copy_files_to_interim.py')
print("copy_files_to_interim ing...")
errcode = exec_shell([sys.executable, copy_py, root_path], None, True)
if errcode != 0:
print("copy_files_to_interim failed!")
return False
print("copy_files_to_interim done!")
if "CONFIG_SUPPORT_HILINK_INDIE_UPGRADE" in env.get("defines"):
dump_indie_upg_check_file(os.path.join(root_path, "output", "ws63", "acore", target_name), target_name)
if env.get('pke_rom_bin'):
# gen pke_rom_bin
gen_pke_rom_bin_sh = os.path.join(SCRIPT_DIR, 'pke_rom.sh')
if os.path.exists(os.path.join(root_path, \
'drivers/chips/ws63/rom/rom_boot/drivers/drivers/hal/security_unified/hal_cipher/pke/rom_lib.c')):
print("generate pke_rom_bin ing...")
errcode = exec_shell(['sh', gen_pke_rom_bin_sh, root_path], None, True)
if errcode != 0:
print("generate pke_rom_bin failed!")
return False
print("generate pke_rom_bin done!")
# verify pke rom bin
if env.get('fixed_pke'):
bin1 = os.path.join(root_path, "output", env.get('chip'), env.get('core'), 'pke_rom', 'pke_rom.bin')
bin2 = env.get('fixed_pke_path', '').replace('<root>', root_path)
if not compare_bin(bin1, bin2):
print(f"Verify pke rom bin ERROR! :{bin1} is not same with {bin2}")
return False
if env.get('rom_in_one'):
# gen rom_in_one
if "windows" in platform.platform().lower():
rom_in_one = os.path.join(SCRIPT_DIR, 'rom_in_one.py')
print("generate rom_in_one ing...")
errcode = exec_shell([python_path, rom_in_one, root_path, env.get('bin_name')], None, True)
else:
rom_in_one = os.path.join(SCRIPT_DIR, 'rom_in_one.sh')
print("generate rom_in_one ing...")
errcode = exec_shell(['sh', rom_in_one, root_path, env.get('bin_name')], None, True)
if errcode != 0:
print("generate rom_in_one failed!")
return False
print("generate rom_in_one done!")
# verify codepoint bin
bin1 = os.path.join(root_path, "output", env.get('chip'), env.get('core'), \
target_name, env.get('bin_name')+'_rompack.bin')
if env.get('fixed_rom_in_one') and os.path.isfile(bin1):# only rompack bin exists
bin2 = env.get('fixed_rom_in_one_path', '').replace('<root>', root_path)
if not compare_bin(bin1, bin2):
print(f"Verify rom_in_one bin ERROR! :{bin1} is not same with {bin2}")
return False
if env.get('fixed_bin_name'):
bin1 = os.path.join(root_path, "output", env.get('chip'), env.get('core'), \
target_name, env.get('fixed_bin_name'))
bin2 = env.get('fixed_bin_path', '').replace('<root>', root_path)
if not compare_bin(bin1, bin2):
print(f"Verify bin ERROR! :{bin1} is not same with {bin2}")
return False
nv_handle = os.path.join(SCRIPT_DIR, 'nv_handle.py')
exec_shell([python_path, nv_handle], None, True)
return True
def config_check(root_path, target_name):
config_file_path = os.path.join(root_path, "build", "config", "target_config", "ws63", "config.py")
with open(config_file_path, "r", encoding="utf-8") as f:
for i in f:
if target_name in i:
print(target_name, " in config.py.")
return True
return False
def build_sdk():
if os.path.isdir(output_root):
shutil.rmtree(output_root)
errcode = exec_shell(["python3", "build.py", "pack_ws63_sdk"], None, True)
if errcode != 0:
print(f"build target pack_ws63_sdk failed!")
sys.exit(1)
else:
print(f"build target pack_ws63_sdk success!")
def guard_sample(target_name, env):
cfg_dir = os.path.dirname(SCRIPT_DIR)
build_target = env.get('build_target', '')
build_target_cop = build_target.replace('-', "_")
in_sdk_root = os.path.join(output_root, 'package', 'ws63','sdk')
in_sdk_menuconfig_dir = os.path.join(in_sdk_root, 'build', 'config','target_config', env.get('chip'), 'menuconfig', env.get('core'))
base_cfg_path = os.path.join(in_sdk_menuconfig_dir, f'{build_target_cop}.config')
base_cfg_path_bak = base_cfg_path + ".bak"
shutil.move(base_cfg_path, base_cfg_path_bak)
in_sdk_output_root = os.path.join(in_sdk_root, 'output')
source_fwpkg_dir = os.path.join(in_sdk_output_root, env.get('chip'), 'fwpkg', f'{build_target}')
dest_fwpkg_dir = os.path.join(in_sdk_output_root, env.get('chip'), 'GuardSample', target_name)
os.makedirs(dest_fwpkg_dir, exist_ok=True)
# 汇总结果编译sample是否成功
build_result_content = []
build_result_log_path = os.path.join(dest_fwpkg_dir, "build_result.log")
for cfg_path in env.get('menuconfigs', []):
cfg_base_name = os.path.splitext(os.path.basename(cfg_path))[0]
cfg_full_path = os.path.join(cfg_dir, cfg_path)
if not os.path.isfile(cfg_full_path):
continue
shutil.copyfile(cfg_full_path, base_cfg_path)
errcode = exec_shell(["python3", "build.py", "-c", build_target], None, True)
if errcode != 0:
print(f"build target:{target_name}\tusing menuconfig:{cfg_full_path} failed!")
build_result_content.append(f"[ERROR] build target:{target_name}\tusing menuconfig:{cfg_full_path} failed!")
else:
print(f"build target:{target_name}\tusing menuconfig:{cfg_full_path} success!")
build_result_content.append(f"[INFO] build target:{target_name}\tusing menuconfig:{cfg_full_path} success!")
all_in_one_fwpkg_path = os.path.join(source_fwpkg_dir, f'{build_target}_all.fwpkg')
if os.path.isfile(all_in_one_fwpkg_path):
dest_fwpkg = os.path.join(dest_fwpkg_dir, f'{cfg_base_name}_all.fwpkg')
shutil.copyfile(all_in_one_fwpkg_path, dest_fwpkg)
else:
print(f"not find {all_in_one_fwpkg_path}!")
build_result_content.append(f"[ERROR] not find {all_in_one_fwpkg_path}!")
continue
load_only_fwpkg_path = os.path.join(source_fwpkg_dir,f'{build_target}_load_only.fwpkg')
if os.path.isfile(load_only_fwpkg_path):
dest_fwpkg = os.path.join(dest_fwpkg_dir, f'{cfg_base_name}_load_only.fwpkg')
shutil.copyfile(load_only_fwpkg_path, dest_fwpkg)
else:
print(f"not find {load_only_fwpkg_path}!")
build_result_content.append(f"[ERROR] not find {load_only_fwpkg_path}!")
with open(build_result_log_path, 'w') as w_f:
w_f.write("\r\n".join(build_result_content))
shutil.move(base_cfg_path_bak, base_cfg_path)
print(f"fwpkg is created in :{dest_fwpkg_dir}")
os._exit(0)

View File

@ -0,0 +1,81 @@
#!/bin/sh
# Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
set -e
ROOT_PATH=$(realpath $1)
TARGET_NAME=$2
BIN_NAME=$3
ELF_PATH=${ROOT_PATH}/output/ws63/acore/${TARGET_NAME}/${BIN_NAME}.elf
TOOLCHAIN=${ROOT_PATH}/tools/bin/compiler/riscv/cc_riscv32_musl_105/cc_riscv32_musl_fp/bin/riscv32-linux-musl-
WORK_DIR=${ROOT_PATH}/output/ws63/mem_bins
MEMFILE=${ROOT_PATH}/output/ws63/acore/${TARGET_NAME}/${BIN_NAME}.mem
SRAM_PKT_RAM=${ROOT_PATH}/output/ws63/mem_bins/sram_pkt_ram.bin
SRAM_ALL=${ROOT_PATH}/output/ws63/mem_bins/SRAM_START_ADDR_0xA00000.bin
SRAM=${ROOT_PATH}/output/ws63/mem_bins/sram.bin
OBJCOPY=${TOOLCHAIN}objcopy
READELF=${TOOLCHAIN}readelf
get_section_meminfo(){
local elf_path=$1
local section_name=$2
${READELF} -S ${elf_path}|grep " ${section_name} "|awk '{if($1=="["){print $5,$6,$7,$4}else{print $4,$5,$6,$3}}'
}
get_mem_sections(){
local memfile=$1
local mem_name=$2
cat ${memfile} | grep -Pzo "(?s)\n\s*${mem_name}.+?\n\s*\n"|awk '{print $1}'|grep -aP "^\."
}
gen_section_to_bin(){
local elf_path=$1
local section_name_list=($(echo $2))
local first_section_name=$3
local output_bin_path=$4
local mem_info
local params=()
local lma
local first_mem_info=($(get_section_meminfo $elf_path $first_section_name))
for section_name in ${section_name_list[@]};do
if [ "$section_name" = "$first_section_name" ];then
params+="-j ${first_section_name} --change-section-lma=${first_section_name}=0 "
if [ "${first_mem_info[3]}" = "NOBITS" ];then
params+="--set-section-flags=${first_section_name}=contents "
fi
continue
fi
mem_info=($(get_section_meminfo $elf_path $section_name))
if [ $((0x${mem_info[2]} - 0)) -eq 0 ];then echo "skip $section_name";continue;fi
lma=$((0x${mem_info[0]} - 0x${first_mem_info[0]}))
params+="-j $section_name --change-section-lma=${section_name}=${lma} "
if [ "${mem_info[3]}" = "NOBITS" ];then
params+="--set-section-flags=${section_name}=contents "
fi
done
${OBJCOPY} --gap-fill 0x00 -O binary ${params[@]} ${elf_path} ${output_bin_path}
}
dtcm_sections=($(get_mem_sections $MEMFILE DTCM))
itcm_sections=($(get_mem_sections $MEMFILE ITCM))
sram_sections=($(get_mem_sections $MEMFILE SRAM))
mkdir -p $WORK_DIR
pushd ${WORK_DIR}
gen_section_to_bin ${ELF_PATH} "${dtcm_sections[*]}" ${dtcm_sections[0]} DTCM_START_ADDR_0x180000.bin
gen_section_to_bin ${ELF_PATH} "${itcm_sections[*]}" ${itcm_sections[0]} ITCM_START_ADDR_0x14c000.bin
gen_section_to_bin ${ELF_PATH} "${sram_sections[*]}" ${sram_sections[0]} sram.bin
dd if=/dev/zero of=${ROOT_PATH}/output/ws63/mem_bins/sram_pkt_ram.bin bs=49152 seek=0 count=1 conv=sync
cat ${ROOT_PATH}/output/ws63/mem_bins/sram_pkt_ram.bin ${ROOT_PATH}/output/ws63/mem_bins/sram.bin > ${ROOT_PATH}/output/ws63/mem_bins/SRAM_START_ADDR_0xA00000.bin
dd if=/dev/zero of=${ROOT_PATH}/output/ws63/mem_bins/flash_gap.bin bs=266240 seek=0 count=1 conv=sync
cat ${ROOT_PATH}/output/ws63/mem_bins/flash_gap.bin ${ROOT_PATH}/output/ws63/acore/$3/$3-sign.bin > ${ROOT_PATH}/output/ws63/mem_bins/FLASH.bin
python3 ${ROOT_PATH}/build/config/target_config/ws63/script/process_sfc_hex.py ${ROOT_PATH}/output/ws63/mem_bins/FLASH.bin ${ROOT_PATH}/output/ws63/mem_bins/SFC_DATA 2097152
rm -rf FLASH.bin flash_gap.bin sram.bin sram_pkt_ram.bin temp.hex
popd

View File

@ -0,0 +1,107 @@
import json
from xml.dom.minidom import Document
import re
import os
NV_JSON_FILE_DIR = ["./output/ws63/acore/nv_bin/temp/cfg/acore_nv.json"]
NV_TXT_FILE_DIR = ["./output/ws63/acore/nv_bin/temp/acore.etypes"]
NV_XML_PATH = "./output/ws63/database/cco/system/hdbcfg/mss_nvi_db.xml"
TXT_PATH = "./output/ws63/database/cco/system/nv/nv_struct_def.txt"
def nv_json_handle():
file_dic = {}
for file_path in NV_JSON_FILE_DIR:
if not os.path.isfile(file_path):
print("[!][nv handle]warning: ", file_path, " not found!")
break
nv_dic = {}
with open(file_path, "r") as f:
nv_api = json.load(f)
for i in nv_api["common"].keys():
if nv_api["common"][i] != 0:
nv_dic[i] = nv_api["common"][i]
file_dic[file_path] = nv_dic
return file_dic
def dic_to_nv(nv_dic: dict):
if not nv_dic:
print("[!][nv handle]warning: dic is Null.")
return
nv_data = Document()
root_node = nv_data.createElement("DebugKits")
nv_data.appendChild(root_node)
group_num = 0
for file_name in nv_dic.keys():
print("NV file reading: ", file_name)
group_num += 1
group_id = hex(group_num)
file_cont = nv_dic[file_name]
# first node, GROUP attribute
first_son_node = nv_data.createElement("GROUP")
root_node.appendChild(first_son_node)
first_son_node.setAttribute("ID", group_id)
first_son_node.setAttribute("NAME", "NV")
first_son_node.setAttribute("PARAM_DEF_FILE", os.path.relpath(TXT_PATH, os.path.dirname(NV_XML_PATH)))
for nv_name in file_cont.keys():
son_node = nv_data.createElement("NV")
first_son_node.appendChild(son_node)
son_node.setAttribute("CATEGORY", "FTM")
son_node.setAttribute("DESCRIPTION", "FTM")
son_node.setAttribute("DEV", "CCO")
son_node.setAttribute("ID", file_cont[nv_name]["key_id"])
son_node.setAttribute("NAME", nv_name)
son_node.setAttribute("PARAM_NAME", file_cont[nv_name]["structure_type"])
print("nv xml writing in: ", NV_XML_PATH)
try:
f = open(NV_XML_PATH, "w", encoding="utf-8")
f.write(nv_data.toprettyxml())
f.close()
except FileNotFoundError:
print("[!][nv handle]warning: ", NV_XML_PATH, " not found!")
pass
except:
print("[!][nv handle]warning: NV error!")
pass
def struct_to_txt():
struct_list = []
for file_path in NV_TXT_FILE_DIR:
if not os.path.isfile(file_path):
print("[!][nv handle]warning: ", file_path, " not found!")
break
print("struct file reading: ", file_path)
with open(file_path, "r", encoding="utf-8") as f:
data = f.readlines()
ret = re.findall("(typedef.*?;)", "".join(data))
ret2 = re.findall("(typedef struct {.*?}.*?;)", "".join(data), re.S)
struct_list.extend(ret)
struct_list.extend(ret2)
print("struct writing in:", TXT_PATH)
try:
with open(TXT_PATH, "w", encoding="utf-8") as t_file:
t_file.write('''#include "base_datatype_def.txt"\n''')
for i in struct_list:
t_file.write(i + "\n")
except FileNotFoundError:
print("[!][nv handle]warning: ", TXT_PATH, " not found!")
pass
except:
print("[!][nv handle]warning: NV error!")
pass
return
if __name__ == '__main__':
work_dir = os.getcwd()
print("current work direction: ", work_dir)
dic = nv_json_handle()
if dic:
dic_to_nv(dic)
struct_to_txt()
os.chdir(work_dir)

View File

@ -0,0 +1,30 @@
#!/bin/sh
# Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
set -e
root_dir=$1
out_dir=${root_dir}/output/ws63/acore/pke_rom
create_hex_py=${root_dir}/build/script/utils/create_hex.py
objcopy_tool=${root_dir}/tools/bin/compiler/riscv/cc_riscv32_musl_105/cc_riscv32_musl/bin/riscv32-linux-musl-objcopy
gcc_tool=${root_dir}/tools/bin/compiler/riscv/cc_riscv32_musl_105/cc_riscv32_musl/bin/riscv32-linux-musl-gcc
rom_lib_c=${root_dir}/drivers/chips/ws63/rom/rom_boot/drivers/drivers/hal/security_unified/hal_cipher/pke/rom_lib.c
td_type_h=${root_dir}/drivers/chips/ws63/rom/rom_boot/middleware/utils/common_headers/native/td_type.h
if [ ! -d ${out_dir} ];then
mkdir ${out_dir}
fi
cat ${rom_lib_c}|grep -Pzo ".*g_instr_rom\[\]\s*=\s*\{[\s\S]+\}\s*;"|sed 's/\x0//g' > ${out_dir}/rom_lib.c
rom_lib_file_path=${out_dir}/rom_lib.o
${gcc_tool} -include ${td_type_h} -c ${out_dir}/rom_lib.c -o ${rom_lib_file_path}
if [ -f ${rom_lib_file_path} ]; then
${objcopy_tool} -O binary -j "\.rodata" ${rom_lib_file_path} ${out_dir}/pke_rom_raw.bin
tr '\000' '\377' < /dev/zero|dd of=${out_dir}/pke_rom.bin bs=3k count=1
dd if=${out_dir}/pke_rom_raw.bin of=${out_dir}/pke_rom.bin seek=0 conv=notrunc
# generate hex
python3 ${create_hex_py} ${out_dir}/pke_rom.bin ${out_dir}/pke_rom.hex
fi
exit 0

View File

@ -0,0 +1,50 @@
import struct
import sys
def create_hex_file(target, source):
with open(str(source), "rb") as binfile, open(str(target), "wb") as hexfile:
while True:
bindata = binfile.read(4)
if not bindata:
break
longdata, = struct.unpack("<L", bindata)
hexstr = '{:x}'.format(longdata) # dec to hex number str
hexstr = '%s\n' % '{:0>8}'.format(hexstr).upper()
hexfile.write(str.encode(hexstr))
binfile.close()
hexfile.close()
def create_sfc_file(target, source, input_len):
len = 0
with open(str(source), "r") as hexfile, open(str(target), "w") as sfcfile:
for line in hexfile.readlines():
#print("len is %d" % len(line))
sfcfile.writelines(line[6:8])
sfcfile.writelines("\n")
sfcfile.writelines(line[4:6])
sfcfile.writelines("\n")
sfcfile.writelines(line[2:4])
sfcfile.writelines("\n")
sfcfile.writelines(line[0:2])
sfcfile.writelines("\n")
len += 4
while len < int(input_len) :
sfcfile.writelines('FF')
sfcfile.writelines("\n")
len += 1
hexfile.close()
sfcfile.close()
if __name__ == "__main__":
if len(sys.argv) == 4:
bin_file_name = sys.argv[1]
hex_file_name = "temp.hex"
sfc_file_name = sys.argv[2]
len = sys.argv[3]
else:
print('hhhhhhhhhhhhhhhhh')
sys.exit(0)
create_hex_file(hex_file_name, bin_file_name)
create_sfc_file(sfc_file_name, hex_file_name, len)
print('success')

View File

@ -0,0 +1,45 @@
import sys
import os
def merge(file_first, file_second, file_out):
ret = open(file_out, 'wb')
with open(file_first, 'rb') as file_1:
for i in file_1:
ret.write(i)
with open(file_second, 'rb') as file_2:
for i in file_2:
ret.write(i)
ret.close()
def move_file(src_path, dst_path, file_name):
src_file = os.path.join(src_path, file_name)
if not os.path.exists(dst_path):
os.mkdir(dst_path)
dst_file = os.path.join(dst_path, file_name)
shutil.move(src_file, dst_file)
# instead of linux dd
# max_size: number of k
def python_dd(file_name, max_size):
file_size = os.path.getsize(file_name)
print(file_name, "size: ", file_size)
if file_size < max_size * 1024:
file_content = open(file_name, 'wb')
file_content.write(b'0' * (max_size * 1024 - file_size))
root_dir = sys.argv[1]
bin_name = sys.argv[2]
out_dir = os.path.join(root_dir, "output/ws63/acore/", bin_name)
romboot_bin = os.path.join(root_dir, "/output/ws63/acore/ws63-romboot/romboot.bin")
if not os.path.isfile(romboot_bin):
print("[*] romboot not found, codepoint files will not be one!")
sys.exit()
python_dd(romboot_bin, 36)
merge(romboot_bin, romboot_bin + "_rom.bin", romboot_bin + "_rompack.bin")

View File

@ -0,0 +1,38 @@
#!/bin/sh
# Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
set -e
root_dir=$1
bin_name=$2
out_dir=${root_dir}/output/ws63/acore/${bin_name}
romboot_bin_dir=${root_dir}/output/ws63/acore/ws63-romboot
romboot_bin=${root_dir}/output/ws63/acore/ws63-romboot/romboot.bin
create_hex_py=${root_dir}/build/script/utils/create_hex.py
if [ ! -f ${romboot_bin} ];then
echo "[*] romboot not found, codepoint files will not be one!"
exit 0
fi
pushd ${out_dir}
# Fill romboot bin to 36K
dd if=${romboot_bin} of=romboot.36K.bin bs=36K seek=0 count=1 conv=sync
# All in one rompack file
cat romboot.36K.bin ${bin_name}_rom.bin > ${bin_name}_rompack.bin
python3 ${create_hex_py} ${bin_name}_rompack.bin ${bin_name}_rompack.hex
# Split the rompack bin file into three parts: 128k, 128k, 48k
dd bs=128k count=1 if=${bin_name}_rompack.bin of=${bin_name}_rompack_part1.128k.bin
python3 ${create_hex_py} ${bin_name}_rompack_part1.128k.bin ${bin_name}_rompack_part1.128k.hex
dd bs=128k count=1 skip=1 if=${bin_name}_rompack.bin of=${bin_name}_rompack_part2.128k.bin
python3 ${create_hex_py} ${bin_name}_rompack_part2.128k.bin ${bin_name}_rompack_part2.128k.hex
dd bs=128k skip=2 if=${bin_name}_rompack.bin of=${bin_name}_rompack_part3.tmp.bin
dd bs=48k count=1 conv=sync if=${bin_name}_rompack_part3.tmp.bin of=${bin_name}_rompack_part3.48k.bin
rm -f ${bin_name}_rompack_part3.tmp.bin
python3 ${create_hex_py} ${bin_name}_rompack_part3.48k.bin ${bin_name}_rompack_part3.48k.hex
popd

View File

@ -0,0 +1,69 @@
import os
import sys
import shutil
import subprocess
current_path = os.path.dirname(os.path.realpath(__file__))
sdk_root_path = os.path.realpath(os.path.join(current_path, "../../../../../"))
sys.path.append(os.path.join(sdk_root_path, 'tools/pkg'))
from packet_create import packet_bin
def get_file_size(file_path: str)->int:
try:
return os.stat(file_path).st_size
except BaseException as e:
print(e)
exit(-1)
cmd_app = [os.path.join(sdk_root_path, "build.py"), "ws63-liteos-app"]
cmd_mfg = [os.path.join(sdk_root_path, "build.py"), "ws63-liteos-mfg"]
ret_app = subprocess.run(cmd_app, cwd=sdk_root_path)
ret_mfg = subprocess.run(cmd_mfg, cwd=sdk_root_path)
if ret_app.returncode != 0 or ret_mfg.returncode != 0:
print("build error!")
exit(-1)
boot_bin_dir = os.path.join(sdk_root_path, "interim_binary", "ws63", "bin", "boot_bin")
param_bin_dir = os.path.join(sdk_root_path, "output", "ws63", "acore", "param_bin")
nv_bin_dir = os.path.join(sdk_root_path, "output", "ws63", "acore", "nv_bin")
loadboot_bin = os.path.join(boot_bin_dir, "root_loaderboot_sign.bin")
loadboot_bx = loadboot_bin + "|0x0|0x200000|0"
# params
params_bin = os.path.join(param_bin_dir, "root_params_sign.bin")
params_bx = params_bin + f"|0x200000|{hex(get_file_size(params_bin))}|1"
# flash boot
flashboot_bin = os.path.join(boot_bin_dir, "flashboot_sign.bin")
flashboot_bx = flashboot_bin + f"|0x202000|{hex(get_file_size(flashboot_bin))}|1"
# nv
nv_bin = os.path.join(nv_bin_dir, "ws63_all_nv.bin")
nv_bx = nv_bin + f"|0x224000|{hex(get_file_size(nv_bin))}|1"
app_bin_path = os.path.join(sdk_root_path, "output/ws63/acore/ws63-liteos-app/ws63-liteos-app-sign.bin")
mfg_app_bin_path = os.path.join(sdk_root_path, "output/ws63/acore/ws63-liteos-mfg/ws63-liteos-mfg-sign.bin")
app_templat_bx = app_bin_path + f"|0x22D000|{hex(get_file_size(app_bin_path))}|1"
mfg_app_bx = mfg_app_bin_path + f"|0x42D000|{hex(0x1BA000)}|1"
# 输出目录
fwpkg_outdir = os.path.join(sdk_root_path, "output", "ws63", "fwpkg", "ws63-liteos-mfg-all")
if os.path.exists(fwpkg_outdir):
shutil.rmtree(fwpkg_outdir)
os.makedirs(fwpkg_outdir)
packet_post_agvs = list()
packet_post_agvs.append(loadboot_bx)
packet_post_agvs.append(params_bx)
packet_post_agvs.append(flashboot_bx)
packet_post_agvs.append(nv_bx)
packet_post_agvs.append(app_templat_bx)
packet_post_agvs.append(mfg_app_bx)
output_fwpkg_path = os.path.join(fwpkg_outdir, "mfg_app_sign.fwpkg")
packet_bin(output_fwpkg_path, packet_post_agvs)