QUESTION
OP-TEE AArch64 _start와 TF-A 인자 단계에서 실제로 바뀌는 상태는 무엇인가?
TF-A가 넘긴 x0-x3, 현재 EL, MMU/cache 상태와 load address를 첫 명령부터 추적한다. pageable image를 복사하는 구간과 아직 참조할 수 없는 전역도 구분한다.
C 함수 진입 전 stack, BSS, relocation destination과 vector base가 유효하고 TF-A가 넘긴 pageable/FDT 인자가 보존되어야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.
STRUCTURE
객체와 주소가 놓이는 구조
_start / boot arguments / early stack를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.
CALL PATH
실행 흐름
화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.
STATE LEDGER
단계별 입력과 출력
각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.
| # | 단계 | 진입 시 신뢰할 상태 | 성공 뒤 남아야 할 상태 | 다음 소비자 |
|---|---|---|---|---|
| 01 | BL31 ERET | S-EL1 early assembly context | secure load address | _start |
| 02 | _start | BL31 ERET 완료 상태 | boot arguments | boot args preserve |
| 03 | boot args preserve | _start 완료 상태 | init stack | relocate/BSS |
| 04 | relocate/BSS | boot args preserve 완료 상태 | identity map/vector | MMU enable |
| 05 | MMU enable | relocate/BSS 완료 상태 | identity map/vector | C init |
| 06 | C init | MMU enable 완료 상태 | identity map/vector | 이 단계의 처리 결과를 사용하는 코드 |
분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.
VISUAL WALKTHROUGH
주소와 객체의 이동을 그림으로 읽기
아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.
각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.
왼쪽에서 만든 상태를 오른쪽 단계가 처음 사용하는 관계를 표시한다.
x0→pageable part→init_primaryx1→unused/platform arg→entry contractx2→FDT/boot data→platform initPC/SPSR→S-EL1 entry→_startUPSTREAM SOURCE
원본 코드
아래 코드는 OP-TEE OS 4.10.0의 core/arch/arm/kernel/entry_a64.S에서 141-229줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.
141
142 .macro init_pauth_secondary_cpu
143 msr spsel, #1
144 ldp x0, x1, [sp, #THREAD_CORE_LOCAL_KEYS]
145 msr spsel, #0
146 write_apiakeyhi x0
147 write_apiakeylo x1
148 mrs x0, sctlr_el1
149 orr x0, x0, #SCTLR_ENIA
150 msr sctlr_el1, x0
151 isb
152 .endm
153
154 .macro init_pan
155 read_feat_pan x0
156 cmp x0, #0
157 b.eq 1f
158 mrs x0, sctlr_el1
159 bic x0, x0, #SCTLR_SPAN
160 msr sctlr_el1, x0
161 write_pan_enable
162 1:
163 .endm
164
165FUNC _start , :
166 /*
167 * Temporary copy of boot argument registers, will be passed to
168 * boot_save_args() further down.
169 */
170 mov x19, x0
171 mov x20, x1
172 mov x21, x2
173 mov x22, x3
174
175 adr x0, reset_vect_table
176 msr vbar_el1, x0
177 isb
178
179#ifdef CFG_PAN
180 init_pan
181#endif
182
183 set_sctlr_el1
184 isb
185
186#ifdef CFG_WITH_PAGER
187 /*
188 * Move init code into correct location and move hashes to a
189 * temporary safe location until the heap is initialized.
190 *
191 * The binary is built as:
192 * [Pager code, rodata and data] : In correct location
193 * [Init code and rodata] : Should be copied to __init_start
194 * [struct boot_embdata + data] : Should be saved before
195 * initializing pager, first uint32_t tells the length of the data
196 */
197 adr x0, __init_start /* dst */
198 adr x1, __data_end /* src */
199 adr x2, __init_end
200 sub x2, x2, x0 /* init len */
201 ldr w4, [x1, x2] /* length of hashes etc */
202 add x2, x2, x4 /* length of init and hashes etc */
203 /* Copy backwards (as memmove) in case we're overlapping */
204 add x0, x0, x2 /* __init_start + len */
205 add x1, x1, x2 /* __data_end + len */
206 adr_l x3, boot_cached_mem_end
207 str x0, [x3]
208 adr x2, __init_start
209copy_init:
210 ldp x3, x4, [x1, #-16]!
211 stp x3, x4, [x0, #-16]!
212 cmp x0, x2
213 b.gt copy_init
214#else
215 /*
216 * The binary is built as:
217 * [Core, rodata and data] : In correct location
218 * [struct boot_embdata + data] : Should be moved to right before
219 * __vcore_free_end, the first uint32_t tells the length of the
220 * struct + data
221 */
222 adr_l x1, __data_end /* src */
223 ldr w2, [x1] /* struct boot_embdata::total_len */
224 /* dst */
225 adr_l x0, __vcore_free_end
226 sub x0, x0, x2
227 /* round down to beginning of page */
228 bic x0, x0, #(SMALL_PAGE_SIZE - 1)
229 adr_l x3, boot_embdata_ptr
READING CONTRACT
발췌 범위와 읽기 기준
원문 141-229줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 FUNC _start , :은 L165에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
TF-A가 넘긴 x0-x3, 현재 EL, MMU/cache 상태와 load address를 첫 명령부터 추적한다. pageable image를 복사하는 구간과 아직 참조할 수 없는 전역도 구분한다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. assembly 초기화 뒤 호출되는 primary C 초기화
core/arch/arm/kernel/boot.c 871-993줄이다.
871}
872
873static bool add_padding_to_pool(vaddr_t va, size_t len, void *ptr __unused)
874{
875#ifdef CFG_NS_VIRTUALIZATION
876 nex_malloc_add_pool((void *)va, len);
877#else
878 malloc_add_pool((void *)va, len);
879#endif
880 return true;
881}
882
883static void init_primary(unsigned long pageable_part)
884{
885 vaddr_t va = 0;
886
887 /*
888 * Mask asynchronous exceptions before switch to the thread vector
889 * as the thread handler requires those to be masked while
890 * executing with the temporary stack. The thread subsystem also
891 * asserts that the foreign interrupts are blocked when using most of
892 * its functions.
893 */
894 thread_set_exceptions(THREAD_EXCP_ALL);
895 primary_save_cntfrq();
896 init_vfp_sec();
897
898 if (IS_ENABLED(CFG_CRYPTO_WITH_CE))
899 check_crypto_extensions();
900
901 init_asan();
902
903 /*
904 * By default whole OP-TEE uses malloc, so we need to initialize
905 * it early. But, when virtualization is enabled, malloc is used
906 * only by TEE runtime, so malloc should be initialized later, for
907 * every virtual partition separately. Core code uses nex_malloc
908 * instead.
909 */
910#ifdef CFG_WITH_PAGER
911 /* Add heap2 first as heap1 may be too small as initial bget pool */
912 malloc_add_pool(__heap2_start, __heap2_end - __heap2_start);
913#endif
914#ifdef CFG_NS_VIRTUALIZATION
915 nex_malloc_add_pool(__nex_heap_start, __nex_heap_end -
916 __nex_heap_start);
917#else
918 malloc_add_pool(__heap1_start, __heap1_end - __heap1_start);
919#endif
920 IMSG_RAW("\n");
921 if (IS_ENABLED(CFG_DYN_CONFIG)) {
922 size_t sz = sizeof(struct thread_core_local) *
923 CFG_TEE_CORE_NB_CORE;
924 void *p = boot_mem_alloc(sz, alignof(void *) * 2);
925
926#ifdef CFG_NS_VIRTUALIZATION
927 nex_malloc_add_pool(p, sz);
928#else
929 malloc_add_pool(p, sz);
930#endif
931 }
932
933 core_mmu_save_mem_map();
934 core_mmu_init_phys_mem();
935 boot_mem_foreach_padding(add_padding_to_pool, NULL);
936 va = boot_mem_release_unused();
937 if (!IS_ENABLED(CFG_WITH_PAGER)) {
938 /*
939 * We must update boot_cached_mem_end to reflect the memory
940 * just unmapped by boot_mem_release_unused().
941 */
942 assert(va && va <= boot_cached_mem_end);
943 boot_cached_mem_end = va;
944 }
945
946 if (IS_ENABLED(CFG_DYN_CONFIG)) {
947 /*
948 * This is needed to enable virt_page_alloc() now that
949 * boot_mem_alloc() can't be used any longer.
950 */
951 if (IS_ENABLED(CFG_NS_VIRTUALIZATION))
952 nex_page_alloc_init();
953 else
954 page_alloc_init();
955 }
956
957 if (IS_ENABLED(CFG_WITH_PAGER)) {
958 /*
959 * Pager: init_runtime() calls thread_kernel_enable_vfp()
960 * so we must set a current thread right now to avoid a
961 * chicken-and-egg problem (thread_init_boot_thread() sets
962 * the current thread but needs things set by
963 * init_runtime()).
964 */
965 thread_get_core_local()->curr_thread = 0;
966 init_pager_runtime(pageable_part);
967 }
968
969 /* Initialize canaries around the stacks */
970 thread_init_canaries();
971 thread_init_per_cpu();
972}
973
974static bool cpu_nmfi_enabled(void)
975{
976#if defined(ARM32)
977 return read_sctlr() & SCTLR_NMFI;
978#else
979 /* Note: ARM64 does not feature non-maskable FIQ support. */
980 return false;
981#endif
982}
983
984/*
985 * Note: this function is weak just to make it possible to exclude it from
986 * the unpaged area.
987 */
988void __weak boot_init_primary_late(unsigned long fdt __unused,
989 unsigned long manifest __unused)
990{
991 size_t fdt_size = CFG_DTB_MAX_SIZE;
992
993 if (IS_ENABLED(CFG_TRANSFER_LIST) && mapped_tl) {
02. pageable image를 검증하고 pager runtime을 구성
core/arch/arm/kernel/boot.c 464-646줄이다.
464#ifdef CFG_CORE_ASLR
465 unsigned int reloc_offs = (vaddr_t)__pageable_start - VCORE_START_VA;
466 const struct boot_embdata *embdata = (const void *)__init_end;
467 const void *reloc = __init_end + embdata->reloc_offset;
468
469 return fobj_ro_reloc_paged_alloc(num_pages, hashes, reloc_offs,
470 reloc, embdata->reloc_len, store);
471#else
472 return fobj_ro_paged_alloc(num_pages, hashes, store);
473#endif
474}
475
476static void init_pager_runtime(unsigned long pageable_part)
477{
478 size_t n;
479 size_t init_size = (size_t)(__init_end - __init_start);
480 size_t pageable_start = (size_t)__pageable_start;
481 size_t pageable_end = (size_t)__pageable_end;
482 size_t pageable_size = pageable_end - pageable_start;
483 vaddr_t tzsram_end = TZSRAM_BASE + TZSRAM_SIZE - TEE_LOAD_ADDR +
484 VCORE_START_VA;
485 size_t hash_size = (pageable_size / SMALL_PAGE_SIZE) *
486 TEE_SHA256_HASH_SIZE;
487 const struct boot_embdata *embdata = (const void *)__init_end;
488 const void *tmp_hashes = NULL;
489 tee_mm_entry_t *mm = NULL;
490 struct fobj *fobj = NULL;
491 uint8_t *paged_store = NULL;
492 uint8_t *hashes = NULL;
493
494 assert(pageable_size % SMALL_PAGE_SIZE == 0);
495 assert(embdata->total_len >= embdata->hashes_offset +
496 embdata->hashes_len);
497 assert(hash_size == embdata->hashes_len);
498
499 tmp_hashes = __init_end + embdata->hashes_offset;
500
501 /*
502 * This needs to be initialized early to support address lookup
503 * in MEM_AREA_TEE_RAM
504 */
505 tee_pager_early_init();
506
507 hashes = malloc(hash_size);
508 IMSG_RAW("\n");
509 IMSG("Pager is enabled. Hashes: %zu bytes", hash_size);
510 assert(hashes);
511 asan_memcpy_unchecked(hashes, tmp_hashes, hash_size);
512
513 /*
514 * The pager is about the be enabled below, eventual temporary boot
515 * memory allocation must be removed now.
516 */
517 boot_mem_release_tmp_alloc();
518
519 carve_out_asan_mem();
520
521 mm = nex_phys_mem_ta_alloc(pageable_size);
522 assert(mm);
523 paged_store = phys_to_virt(tee_mm_get_smem(mm),
524 MEM_AREA_SEC_RAM_OVERALL, pageable_size);
525 /*
526 * Load pageable part in the dedicated allocated area:
527 * - Move pageable non-init part into pageable area. Note bootloader
528 * may have loaded it anywhere in TA RAM hence use memmove().
529 * - Copy pageable init part from current location into pageable area.
530 */
531 memmove(paged_store + init_size,
532 phys_to_virt(pageable_part,
533 core_mmu_get_type_by_pa(pageable_part),
534 __pageable_part_end - __pageable_part_start),
535 __pageable_part_end - __pageable_part_start);
536 asan_memcpy_unchecked(paged_store, __init_start, init_size);
537 /*
538 * Undo eventual relocation for the init part so the hash checks
539 * can pass.
540 */
541 undo_init_relocation(paged_store);
542
543 /* Check that hashes of what's in pageable area is OK */
544 DMSG("Checking hashes of pageable area");
545 for (n = 0; (n * SMALL_PAGE_SIZE) < pageable_size; n++) {
546 const uint8_t *hash = hashes + n * TEE_SHA256_HASH_SIZE;
547 const uint8_t *page = paged_store + n * SMALL_PAGE_SIZE;
548 TEE_Result res;
549
550 DMSG("hash pg_idx %zu hash %p page %p", n, hash, page);
551 res = hash_sha256_check(hash, page, SMALL_PAGE_SIZE);
552 if (res != TEE_SUCCESS) {
553 EMSG("Hash failed for page %zu at %p: res 0x%x",
554 n, (void *)page, res);
555 panic();
556 }
557 }
558
559 /*
560 * Assert prepaged init sections are page aligned so that nothing
561 * trails uninited at the end of the premapped init area.
562 */
563 assert(!(init_size & SMALL_PAGE_MASK));
564
565 /*
566 * Initialize the virtual memory pool used for main_mmu_l2_ttb which
567 * is supplied to tee_pager_init() below.
568 */
569 init_virt_pool(&core_virt_mem_pool);
570
571 /*
572 * Assign alias area for pager end of the small page block the rest
573 * of the binary is loaded into. We're taking more than needed, but
574 * we're guaranteed to not need more than the physical amount of
575 * TZSRAM.
576 */
577 mm = tee_mm_alloc2(&core_virt_mem_pool,
578 (vaddr_t)core_virt_mem_pool.lo +
579 core_virt_mem_pool.size - TZSRAM_SIZE,
580 TZSRAM_SIZE);
581 assert(mm);
582 tee_pager_set_alias_area(mm);
583
584 /*
585 * Claim virtual memory which isn't paged.
586 * Linear memory (flat map core memory) ends there.
587 */
588 mm = tee_mm_alloc2(&core_virt_mem_pool, VCORE_UNPG_RX_PA,
589 (vaddr_t)(__pageable_start - VCORE_UNPG_RX_PA));
590 assert(mm);
591
592 /*
593 * Allocate virtual memory for the pageable area and let the pager
594 * take charge of all the pages already assigned to that memory.
595 */
596 mm = tee_mm_alloc2(&core_virt_mem_pool, (vaddr_t)__pageable_start,
597 pageable_size);
598 assert(mm);
599 fobj = ro_paged_alloc(mm, hashes, paged_store);
600 assert(fobj);
601 tee_pager_add_core_region(tee_mm_get_smem(mm), PAGED_REGION_TYPE_RO,
602 fobj);
603 fobj_put(fobj);
604
605 tee_pager_add_pages(pageable_start, init_size / SMALL_PAGE_SIZE, false);
606 tee_pager_add_pages(pageable_start + init_size,
607 (pageable_size - init_size) / SMALL_PAGE_SIZE,
608 true);
609 if (pageable_end < tzsram_end)
610 tee_pager_add_pages(pageable_end, (tzsram_end - pageable_end) /
611 SMALL_PAGE_SIZE, true);
612
613 /*
614 * There may be physical pages in TZSRAM before the core load address.
615 * These pages can be added to the physical pages pool of the pager.
616 * This setup may happen when a the secure bootloader runs in TZRAM
617 * and its memory can be reused by OP-TEE once boot stages complete.
618 */
619 tee_pager_add_pages(core_virt_mem_pool.lo,
620 (VCORE_UNPG_RX_PA - core_virt_mem_pool.lo) /
621 SMALL_PAGE_SIZE,
622 true);
623
624 print_pager_pool_size();
625}
626#else /*!CFG_WITH_PAGER*/
627static void init_pager_runtime(unsigned long pageable_part __unused)
628{
629}
630#endif
631
632#if defined(CFG_DT)
633static int add_optee_dt_node(struct dt_descriptor *dt)
634{
635 int offs;
636 int ret;
637
638 if (fdt_path_offset(dt->blob, "/firmware/optee") >= 0) {
639 DMSG("OP-TEE Device Tree node already exists!");
640 return 0;
641 }
642
643 offs = fdt_path_offset(dt->blob, "/firmware");
644 if (offs < 0) {
645 offs = add_dt_path_subnode(dt, "/", "firmware");
646 if (offs < 0)
DETAILS
내부 동작을 더 깊게 읽기
진입 조건을 먼저 고정한다
BL31 ERET에서 들어온 실행은 S-EL1 early assembly context에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.
TF-A가 넘긴 x0-x3, 현재 EL, MMU/cache 상태와 load address를 첫 명령부터 추적한다. pageable image를 복사하는 구간과 아직 참조할 수 없는 전역도 구분한다.
중심 객체의 생성과 공개를 나눈다
이 글의 중심 객체는 _start / boot arguments / early stack다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.
빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.
주소, 크기와 정렬을 계산한다
부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.
성공 flag와 실제 완료 시점을 맞춘다
_start → boot args preserve → relocate/BSS → MMU enable 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.
다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.
제어권을 넘기기 전에 확인할 조건을 정리한다
정상 경로는 C init에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.
호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.
IMPLEMENTATION NOTES
구현을 읽을 때 놓치기 쉬운 부분
BL31 ERET에서 C init까지 제어권이 이동하는 조건
BL31의 secure ERET가 OP-TEE _start로 들어온 뒤 relocation, BSS, MMU와 primary/secondary 경로를 준비하는 assembly를 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. BL31 ERET → _start → boot args preserve → relocate/BSS → MMU enable → C init 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 S-EL1 early assembly context에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.
TF-A가 넘긴 x0-x3, 현재 EL, MMU/cache 상태와 load address를 첫 명령부터 추적한다. pageable image를 복사하는 구간과 아직 참조할 수 없는 전역도 구분한다. 따라서 첫 지점에서 _start / boot arguments / early stack의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 C 함수 진입 전 stack, BSS, relocation destination과 vector base가 유효하고 TF-A가 넘긴 pageable/FDT 인자가 보존되어야 한다.
secure load address와 identity map/vector의 생성 시점과 수명
이 글에서 함께 나타나는 객체는 secure load address, boot arguments, init stack, identity map/vector이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.
_start / boot arguments / early stack을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.
성공 로그만으로 놓치기 쉬운 오류
대표적인 실패 조건은 잘못된 load address: relocation self-overlap; BSS 범위 오류: boot arg 손상; CurrentEL 불일치: system register trap이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.
재현에는 _start에서 x0-x3/SP/CurrentEL 기록; tee.elf symbol과 runtime PC 대조; pager on/off entry 경로 비교를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.
DEEP ANALYSIS
레지스터에서 오류 판정까지 상세 분석
AArch64 _start는 TF-A가 넘긴 x0-x3를 보존하면서 OP-TEE가 C 코드를 실행할 수 있는 최소 상태를 만드는 구간이다. reset vector와 달리 S-EL1에서 시작하며, BL31이 설치한 SPSR/SCR와 secure physical load address를 전제로 VBAR_EL1, 임시 stack, BSS, relocation, MMU 상태를 순서대로 다룬다.
CFG_WITH_PAGER나 ASLR이 켜지면 link address와 실제 load address가 다를 수 있고 init/embedded data를 겹치지 않게 뒤에서 앞으로 복사하는 코드가 나타난다. 각 memcpy 방향과 source/destination end를 실제 linker symbol로 계산해야 self-overwrite 여부를 판단할 수 있다.
S-EL1 AArch64 실행을 가리켜야 한다.
pageable address 또는 boot info 등 build mode가 기대하는 인자를 담는다.
_start 실제 byte가 놓인 secure executable 주소여야 한다.
cache/MMU/alignment bit를 OP-TEE 초기화 순서에 맞춰 설정한다.
현재 core에 대응하고 init/embedded data 복사 범위와 겹치지 않아야 한다.
각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.
진입 레지스터와 메모리 계약
함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.
| # | 입력 상태 | 생산자 | 정상 조건 | 확인 이유 |
|---|---|---|---|---|
| 01 | CurrentEL | BL31 BL32 ep_info | S-EL1 AArch64 실행을 가리켜야 한다. | SCTLR_EL1, VBAR_EL1, TTBR 접근의 전제다. |
| 02 | x0-x3 | TF-A/platform BL32 ABI | pageable address 또는 boot info 등 build mode가 기대하는 인자를 담는다. | x19-x22에 보존되어 boot_init_primary에 다시 전달된다. |
| 03 | PC/load PA | FIP loader와 ep_info.pc | _start 실제 byte가 놓인 secure executable 주소여야 한다. | relocation offset과 core_mmu_tee_load_pa의 기준이다. |
| 04 | SCTLR_EL1 | BL31/entry code | cache/MMU/alignment bit를 OP-TEE 초기화 순서에 맞춰 설정한다. | BSS/relocation과 page-table 전환의 memory semantics를 결정한다. |
| 05 | temporary SP | entry assembly/linker | 현재 core에 대응하고 init/embedded data 복사 범위와 겹치지 않아야 한다. | C runtime 전 assembly 호출과 boot thread가 사용한다. |
핵심 구조체 필드의 생산자, 소비자와 수명
구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.
| # | 객체 또는 필드 | 생산자 | 소비자 | 수명과 불변 조건 |
|---|---|---|---|---|
| 01 | x19-x22 saved boot args | _start | boot_init_primary | early assembly 전체에서 callee-saved register로 유지된다. |
| 02 | reset_vect_table/VBAR_EL1 | _start | early exception | 정식 vector 전에도 abort를 포착할 수 있도록 먼저 설치된다. |
| 03 | __init_start/__init_end | linker | early copy/execute | relocation과 init 완료 뒤 pageable/runtime 영역과 수명이 달라진다. |
| 04 | __bss_start/__bss_end | linker | zeroing loop와 C globals | C code 진입 전에 정확히 zero여야 하며 boot arg storage를 덮지 않는다. |
| 05 | boot_embdata_ptr | early relocation | MMU/pager/init | embedded metadata 이동 뒤 새 주소를 가리키며 old range를 참조하면 안 된다. |
| 06 | thread_core_local/tmp stack | entry assembly | thread/exception code | primary core가 정식 per-CPU structure를 만들 때까지 임시 owner다. |
함수 내부 실행 순서
소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.
- 01
_start가 x0-x3를 x19-x22에 보존해 relocation과 register setup 중 유실되지 않게 한다.
- 02
초기 exception을 잡을 reset vector를 VBAR_EL1에 설치하고 SCTLR_EL1 정책을 정규화한다.
- 03
pager/ASLR 구성에 따라 init와 embedded data의 source/destination/length를 계산한다.
- 04
겹침 방향을 고려해 뒤에서 앞으로 copy하고 새 boot_embdata_ptr와 cached memory end를 기록한다.
- 05
BSS와 nex BSS 중 zero 대상만 지우며 nozi/stack/canary 같은 보존 영역을 구분한다.
- 06
실제 _start load PA와 compiled TEE_LOAD_ADDR 차이로 relocation offset을 계산·적용한다.
- 07
primary thread_core_local, temporary/abort stack과 current thread invalid state를 초기화한다.
- 08
MMU table 생성에 필요한 load/virtual layout을 넘기고 cache maintenance와 barrier 뒤 translation을 전환한다.
- 09
보존한 x0-x3를 복원해 boot_init_primary 또는 C primary init 경로로 진입한다.
빌드 설정이 바꾸는 실제 코드 경로
동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.
| # | 설정 | 바뀌는 동작 | 확인 방법 |
|---|---|---|---|
| 01 | CFG_WITH_PAGER | init resident copy와 pageable backing 인자 처리가 추가된다. | x0 의미와 __pageable_part_* symbol을 대조한다. |
| 02 | CFG_CORE_ASLR | load address와 runtime mapping offset을 사용한다. | core_mmu_tee_load_pa와 runtime PC 차이를 기록한다. |
| 03 | CFG_MEMTAG/BTI/PAUTH | SCTLR/TCR와 key 초기화 명령이 entry에 추가된다. | CPU feature detect와 enable register를 확인한다. |
| 04 | CFG_CORE_NB_CORE | temporary stack/core-local 배치 수를 결정한다. | MPIDR linear index가 배열 범위 안인지 본다. |
증상에서 최초 불일치 지점까지 추적하기
마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.
| # | 관찰 증상 | 중단 위치 | 기록할 값 | 판정 |
|---|---|---|---|---|
| 01 | _start 200줄 이전 data abort | copy loop | src/dst/end, load PA, linker symbol | init/embedded data self-overlap 또는 잘못된 segment size를 찾는다. |
| 02 | C 진입 시 global이 임의 값 | BSS zero loop | BSS start/end와 boot argument storage | 잘못된 linker boundary 또는 zero 누락을 확인한다. |
| 03 | MMU enable 직후 instruction abort | translation enable 전후 | TTBR/TCR/MAIR/SCTLR, PC VA/PA | relocation과 mapping의 runtime VA 불일치를 판정한다. |
| 04 | secondary core가 primary stack을 사용 | core index와 stack calculation | MPIDR, core_pos, SP, thread_core_local | platform core mapping 또는 temporary stack stride 오류를 찾는다. |
OBJECT LIFETIME
객체와 수명
| 대상 | 만들어지는 시점 | 유효 범위 | 확인할 조건 |
|---|---|---|---|
_start / boot arguments / early stack | _start | C init 또는 오류 정리 완료까지 | 진입 전제와 상태 계약 |
| 입력 buffer / metadata | BL31 ERET | parse와 검증이 끝날 때까지 | 길이, 정렬, 소유권, 변조 가능성 |
| 등록된 list / descriptor | boot args preserve | 하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지 | 중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리 |
| hardware 또는 persistent state | 실제 write/probe가 완료된 뒤 | reset 또는 명시적 해제·갱신까지 | 쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원 |
최종 부트로더 이미지 | link/image 생성 시점 | 다음 stage가 새 image로 교체할 때까지 | 적재 주소, 진입점, 섹션, 헤더의 일치 여부 |
FAILURE PATH
실패 지점과 증상
| # | 조건 | 관찰되는 증상 | 먼저 볼 단계 |
|---|---|---|---|
| 01 | 잘못된 load address | relocation self-overlap | _start |
| 02 | BSS 범위 오류 | boot arg 손상 | boot args preserve |
| 03 | CurrentEL 불일치 | system register trap | relocate/BSS |
로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.
EVIDENCE
소스 밖에서 확인할 증거
소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.
| # | 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|---|
| 01 | 빌드 산출물 | make PLATFORM=<platform> CFG_TEE_CORE_LOG_LEVEL=4 | tee.elf, tee.bin과 pageable/pager 구성이 같은 설정에서 생성됐는지 확인한다. |
| 02 | ELF 배치 | ${CROSS_COMPILE64}readelf -W -lS out/arm/core/tee.elf | secure RAM 안에서 text, data, pager, pageable 구간이 어떤 주소와 권한으로 배치되는지 확인한다. |
| 03 | 심볼과 주소 | ${CROSS_COMPILE64}nm -n out/arm/core/tee.elf | grep 'FUNC _start ,' | entry, thread, TA manager 함수의 링크 주소를 원본 설명과 연결한다. |
| 04 | 명령과 예외 경로 | ${CROSS_COMPILE64}objdump -drS out/arm/core/tee.elf | SMC entry, world switch, abort 복귀가 실제 register save/restore와 어떻게 이어지는지 대조한다. |
| 05 | Normal world 왕복 | xtest; dmesg | grep -i optee | secure console과 Linux OP-TEE driver 로그를 함께 보고 SMC, RPC, shared memory 왕복의 양쪽 증거를 맞춘다. |
LAB
직접 확인할 실험
- 01_start에서 x0-x3/SP/CurrentEL 기록
_start진입 전후에 secure load address의 주소·크기·반환값과 timestamp를 함께 남긴다. - 02tee.elf symbol과 runtime PC 대조
boot args preserve진입 전후에 boot arguments의 주소·크기·반환값과 timestamp를 함께 남긴다. - 03pager on/off entry 경로 비교
relocate/BSS진입 전후에 init stack의 주소·크기·반환값과 timestamp를 함께 남긴다.
PRIMARY REFERENCES