QUESTION
BL33 선택과 Non-secure world 진입 단계에서 실제로 바뀌는 상태는 무엇인가?
BL33가 U-Boot인지 Linux인지보다 architecture handoff 계약이 중요하다. target EL, endianness, MMU/cache 상태와 x0-x3 의미를 구분한다.
ERET 직전 next context는 NON_SECURE이며 BL33 entry가 허용된 non-secure executable memory를 가리키고 runtime BL31 영역과 겹치지 않아야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.
STRUCTURE
객체와 주소가 놓이는 구조
entry_point_info_t / NON_SECURE cpu_context를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.
CALL PATH
실행 흐름
화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.
STATE LEDGER
단계별 입력과 출력
호출 순서를 함수 이름으로만 외우지 않고, 각 단계가 무엇을 받아 무엇을 공개하는지 적은 표다. 실제 소스에서 생산 필드가 다르면 표를 고치는 방식으로 사용한다.
| # | 단계 | 진입 시 신뢰할 상태 | 성공 뒤 남아야 할 상태 | 다음 소비자 |
|---|---|---|---|---|
| 01 | BL32 init complete | final EL3 exit to BL33 | BL33 entry_point_info | select BL33 |
| 02 | select BL33 | BL32 init complete 완료 상태 | NON_SECURE cpu_context | prepare NS context |
| 03 | prepare NS context | select BL33 완료 상태 | SPSR/SCR_EL3 | disable init mappings |
| 04 | disable init mappings | prepare NS context 완료 상태 | x0-x3 args | ERET to BL33 |
| 05 | ERET to BL33 | disable init mappings 완료 상태 | x0-x3 args | 최종 최종 부트로더 이미지 또는 다음 stage |
분석 범위의 전제와 비교해, 다음 단계의 입력 조건을 처음 어긴 생산 단계부터 조사한다.
VISUAL WALKTHROUGH
주소와 객체의 이동을 그림으로 읽기
아래 그림은 호출 이름보다 주소, 객체 수명과 handoff 경계를 먼저 볼 수 있도록 구성했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, map과 linker symbol을 대입한다.
각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.
크기는 개념 비율이다. 실제 시작·끝 주소는 platform map과 linker symbol로 대조한다.
UPSTREAM SOURCE
원본 코드
아래 코드는 Trusted Firmware-A LTS 2.14.3의 bl31/bl31_main.c에서 271-354줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.
271
272/*******************************************************************************
273 * Accessor functions to help runtime services decide which image should be
274 * executed after BL31. This is BL33 or the non-secure bootloader image by
275 * default but the Secure payload dispatcher could override this by requesting
276 * an entry into BL32 (Secure payload) first. If it does so then it should use
277 * the same API to program an entry into BL33 once BL32 initialisation is
278 * complete.
279 ******************************************************************************/
280void bl31_set_next_image_type(uint32_t security_state)
281{
282 assert(sec_state_is_valid(security_state));
283 next_image_type = security_state;
284}
285
286static uint32_t bl31_get_next_image_type(void)
287{
288 return next_image_type;
289}
290
291/*******************************************************************************
292 * This function programs EL3 registers and performs other setup to enable entry
293 * into the next image after BL31 at the next ERET.
294 ******************************************************************************/
295void __init bl31_prepare_next_image_entry(void)
296{
297 const entry_point_info_t *next_image_info;
298 uint32_t image_type;
299
300#if CTX_INCLUDE_AARCH32_REGS
301 /*
302 * Ensure that the build flag to save AArch32 system registers in CPU
303 * context is not set for AArch64-only platforms.
304 */
305 if (el_implemented(1) == EL_IMPL_A64ONLY) {
306 ERROR("EL1 supports AArch64-only. Please set build flag "
307 "CTX_INCLUDE_AARCH32_REGS = 0\n");
308 panic();
309 }
310#endif
311
312 /* Determine which image to execute next */
313 image_type = bl31_get_next_image_type();
314
315 /* Program EL3 registers to enable entry into the next EL */
316 next_image_info = bl31_plat_get_next_image_ep_info(image_type);
317 assert(next_image_info != NULL);
318 assert(image_type == GET_SECURITY_STATE(next_image_info->h.attr));
319
320 INFO("BL31: Preparing for EL3 exit to %s world\n",
321 (image_type == SECURE) ? "secure" : "normal");
322 print_entry_point_info(next_image_info);
323 cm_init_my_context(next_image_info);
324
325 /*
326 * If we are entering the Non-secure world, use
327 * 'cm_prepare_el3_exit_ns' to exit.
328 */
329 if (image_type == NON_SECURE) {
330 cm_prepare_el3_exit_ns();
331 } else {
332 cm_prepare_el3_exit(image_type);
333 }
334}
335
336/*******************************************************************************
337 * This function initializes the pointer to BL32 init function. This is expected
338 * to be called by the SPD after it finishes all its initialization
339 ******************************************************************************/
340void bl31_register_bl32_init(int32_t (*func)(void))
341{
342 bl32_init = func;
343}
344
345#if ENABLE_RME
346/*******************************************************************************
347 * This function initializes the pointer to RMM init function. This is expected
348 * to be called by the RMMD after it finishes all its initialization
349 ******************************************************************************/
350void bl31_register_rmm_init(int32_t (*func)(void))
351{
352 rmm_init = func;
353}
354#endif
READING CONTRACT
발췌 범위와 읽기 기준
원문 271-354줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void __init bl31_prepare_next_image_entry(void)은 L295에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
BL33가 U-Boot인지 Linux인지보다 architecture handoff 계약이 중요하다. target EL, endianness, MMU/cache 상태와 x0-x3 의미를 구분한다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. Non-secure context를 마지막 ERET 대상으로 준비
lib/el3_runtime/aarch64/context_mgmt.c 1705-1755줄이다.
1705 }
1706}
1707#endif /* (CTX_INCLUDE_EL2_REGS && IMAGE_BL31) */
1708
1709/*******************************************************************************
1710 * This function is used to exit to Non-secure world. If CTX_INCLUDE_EL2_REGS
1711 * is enabled, it restores EL1 and EL2 sysreg contexts instead of directly
1712 * updating EL1 and EL2 registers. Otherwise, it calls the generic
1713 * cm_prepare_el3_exit function.
1714 ******************************************************************************/
1715void cm_prepare_el3_exit_ns(void)
1716{
1717#if (CTX_INCLUDE_EL2_REGS && IMAGE_BL31)
1718#if ENABLE_ASSERTIONS
1719 cpu_context_t *ctx = cm_get_context(NON_SECURE);
1720 assert(ctx != NULL);
1721
1722 /* Assert that EL2 is used. */
1723 u_register_t scr_el3 = read_ctx_reg(get_el3state_ctx(ctx), CTX_SCR_EL3);
1724 assert(((scr_el3 & SCR_HCE_BIT) != 0UL) &&
1725 (el_implemented(2U) != EL_IMPL_NONE));
1726#endif /* ENABLE_ASSERTIONS */
1727
1728 /* Restore EL2 sysreg contexts */
1729 cm_el2_sysregs_context_restore(NON_SECURE);
1730 cm_set_next_eret_context(NON_SECURE);
1731#else
1732 cm_prepare_el3_exit(NON_SECURE);
1733#endif /* (CTX_INCLUDE_EL2_REGS && IMAGE_BL31) */
1734}
1735
1736#if ((IMAGE_BL1) || (IMAGE_BL31 && (!CTX_INCLUDE_EL2_REGS)))
1737/*******************************************************************************
1738 * The next set of six functions are used by runtime services to save and restore
1739 * EL1 context on the 'cpu_context' structure for the specified security state.
1740 ******************************************************************************/
1741static void el1_sysregs_context_save(el1_sysregs_t *ctx)
1742{
1743 write_el1_ctx_common(ctx, spsr_el1, read_spsr_el1());
1744 write_el1_ctx_common(ctx, elr_el1, read_elr_el1());
1745
1746#if (!ERRATA_SPECULATIVE_AT)
1747 write_el1_ctx_common(ctx, sctlr_el1, read_sctlr_el1());
1748 write_el1_ctx_common(ctx, tcr_el1, read_tcr_el1());
1749#endif /* (!ERRATA_SPECULATIVE_AT) */
1750
1751 write_el1_ctx_common(ctx, cpacr_el1, read_cpacr_el1());
1752 write_el1_ctx_common(ctx, csselr_el1, read_csselr_el1());
1753 write_el1_ctx_common(ctx, sp_el1, read_sp_el1());
1754 write_el1_ctx_common(ctx, esr_el1, read_esr_el1());
1755 write_el1_ctx_common(ctx, mair_el1, read_mair_el1());
02. BL33 ep_info로 Non-secure EL1/EL2 context 구성
lib/el3_runtime/aarch64/context_mgmt.c 222-376줄이다.
222 if (is_feat_trbe_supported()) {
223 trbe_disable_realm(ctx);
224 }
225}
226#endif /* ENABLE_RME && IMAGE_BL31 */
227
228/******************************************************************************
229 * This function performs initializations that are specific to NON-SECURE state
230 * and updates the cpu context specified by 'ctx'.
231 *****************************************************************************/
232static void setup_ns_context(cpu_context_t *ctx, const struct entry_point_info *ep)
233{
234 u_register_t scr_el3;
235 el3_state_t *state;
236
237 state = get_el3state_ctx(ctx);
238 scr_el3 = read_ctx_reg(state, CTX_SCR_EL3);
239
240 /* SCR_NS: Set the NS bit */
241 scr_el3 |= SCR_NS_BIT;
242
243 /* Allow access to Allocation Tags when FEAT_MTE2 is implemented and enabled. */
244 if (is_feat_mte2_supported()) {
245 scr_el3 |= SCR_ATA_BIT;
246 }
247
248 /*
249 * Pointer Authentication feature, if present, is always enabled by
250 * default for Non secure lower exception levels. We do not have an
251 * explicit flag to set it. To prevent the leakage between the worlds
252 * during world switch, we enable it only for the non-secure world.
253 *
254 * CTX_INCLUDE_PAUTH_REGS flag, is explicitly used to enable for lower
255 * exception levels of secure and realm worlds.
256 *
257 * If the Secure/realm world wants to use pointer authentication,
258 * CTX_INCLUDE_PAUTH_REGS must be explicitly set to 1, in which case
259 * it will be enabled globally for all the contexts.
260 *
261 * SCR_EL3.API: Set to one to not trap any PAuth instructions at ELs
262 * other than EL3
263 *
264 * SCR_EL3.APK: Set to one to not trap any PAuth key values at ELs other
265 * than EL3
266 */
267 if (!is_ctx_pauth_supported()) {
268 scr_el3 |= SCR_API_BIT | SCR_APK_BIT;
269 }
270
271#if HANDLE_EA_EL3_FIRST_NS
272 /* SCR_EL3.EA: Route External Abort and SError Interrupt to EL3. */
273 scr_el3 |= SCR_EA_BIT;
274#endif
275
276#if RAS_TRAP_NS_ERR_REC_ACCESS
277 /*
278 * SCR_EL3.TERR: Trap Error record accesses. Accesses to the RAS ERR
279 * and RAS ERX registers from EL1 and EL2(from any security state)
280 * are trapped to EL3.
281 * Set here to trap only for NS EL1/EL2
282 */
283 scr_el3 |= SCR_TERR_BIT;
284#endif
285
286 /* CSV2 version 2 and above */
287 if (is_feat_csv2_2_supported()) {
288 /* Enable access to the SCXTNUM_ELx registers. */
289 scr_el3 |= SCR_EnSCXT_BIT;
290 }
291
292#ifdef IMAGE_BL31
293 /*
294 * SCR_EL3.IRQ, SCR_EL3.FIQ: Enable the physical FIQ and IRQ routing as
295 * indicated by the interrupt routing model for BL31.
296 */
297 scr_el3 |= get_scr_el3_from_routing_model(NON_SECURE);
298#endif
299
300 if (is_feat_the_supported()) {
301 /* Set the RCWMASKEn bit in SCR_EL3 to enable access to
302 * RCWMASK_EL1 and RCWSMASK_EL1 registers.
303 */
304 scr_el3 |= SCR_RCWMASKEn_BIT;
305 }
306
307 if (is_feat_sctlr2_supported()) {
308 /* Set the SCTLR2En bit in SCR_EL3 to enable access to
309 * SCTLR2_ELx registers.
310 */
311 scr_el3 |= SCR_SCTLR2En_BIT;
312 }
313
314 if (is_feat_d128_supported()) {
315 /* Set the D128En bit in SCR_EL3 to enable access to 128-bit
316 * versions of TTBR0_EL1, TTBR1_EL1, RCWMASK_EL1, RCWSMASK_EL1,
317 * PAR_EL1 and TTBR1_EL2, TTBR0_EL2 and VTTBR_EL2 registers.
318 */
319 scr_el3 |= SCR_D128En_BIT;
320 }
321
322 if (is_feat_fpmr_supported()) {
323 /* Set the EnFPM bit in SCR_EL3 to enable access to FPMR
324 * register.
325 */
326 scr_el3 |= SCR_EnFPM_BIT;
327 }
328
329 if (is_feat_aie_supported()) {
330 /* Set the AIEn bit in SCR_EL3 to enable access to (A)MAIR2
331 * system registers from NS world.
332 */
333 scr_el3 |= SCR_AIEn_BIT;
334 }
335
336 if (is_feat_pfar_supported()) {
337 /* Set the PFAREn bit in SCR_EL3 to enable access to the PFAR
338 * system registers from NS world.
339 */
340 scr_el3 |= SCR_PFAREn_BIT;
341 }
342
343 write_ctx_reg(state, CTX_SCR_EL3, scr_el3);
344
345 /* Initialize EL2 context registers */
346#if (CTX_INCLUDE_EL2_REGS && IMAGE_BL31)
347 if (is_feat_hcx_supported()) {
348 /*
349 * Initialize register HCRX_EL2 with its init value.
350 * As the value of HCRX_EL2 is UNKNOWN on reset, there is a
351 * chance that this can lead to unexpected behavior in lower
352 * ELs that have not been updated since the introduction of
353 * this feature if not properly initialized, especially when
354 * it comes to those bits that enable/disable traps.
355 */
356 write_el2_ctx_hcx(get_el2_sysregs_ctx(ctx), hcrx_el2,
357 HCRX_EL2_INIT_VAL);
358 }
359
360 if (is_feat_fgt_supported()) {
361 /*
362 * Initialize HFG*_EL2 registers with a default value so legacy
363 * systems unaware of FEAT_FGT do not get trapped due to their lack
364 * of initialization for this feature.
365 */
366 write_el2_ctx_fgt(get_el2_sysregs_ctx(ctx), hfgitr_el2,
367 HFGITR_EL2_INIT_VAL);
368 write_el2_ctx_fgt(get_el2_sysregs_ctx(ctx), hfgrtr_el2,
369 HFGRTR_EL2_INIT_VAL);
370 write_el2_ctx_fgt(get_el2_sysregs_ctx(ctx), hfgwtr_el2,
371 HFGWTR_EL2_INIT_VAL);
372 }
373#else
374 /* Initialize EL1 context registers */
375 setup_el1_context(ctx, ep);
376#endif /* (CTX_INCLUDE_EL2_REGS && IMAGE_BL31) */
DETAILS
내부 동작을 더 깊게 읽기
진입 조건을 먼저 고정한다
BL32 init complete에서 들어온 실행은 final EL3 exit to BL33에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.
BL33가 U-Boot인지 Linux인지보다 architecture handoff 계약이 중요하다. target EL, endianness, MMU/cache 상태와 x0-x3 의미를 구분한다.
중심 객체의 생성과 공개를 나눈다
이 글의 중심 객체는 entry_point_info_t / NON_SECURE cpu_context다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.
빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.
주소, 크기와 정렬을 계산한다
부트 코드의 오류는 논리보다 주소 계산에서 먼저 드러나는 경우가 많다. source range, destination range, header가 말하는 payload size, block 또는 page 단위를 표로 적고 각 구간의 끝 주소를 직접 계산한다. 끝 주소는 start + size - 1인지 exclusive end인지 API 계약을 확인한다.
성공 flag와 실제 완료 시점을 맞춘다
select BL33 → prepare NS context → disable init mappings 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.
다른 CPU, interrupt handler, USB completion 또는 shell command가 상태를 관찰할 수 있다면 memory ordering과 lock 범위도 함께 읽는다.
마지막 handoff의 계약을 적는다
정상 경로는 ERET to BL33에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.
반환하는 경로라면 caller가 오류와 부분 성공을 구분하고 다음 후보 또는 복구 경로를 선택하는지 확인한다.
IMPLEMENTATION NOTES
구현을 읽을 때 놓치기 쉬운 부분
BL32 init complete에서 ERET to BL33까지 제어권이 이동하는 조건
BL32 초기화를 마친 BL31이 BL33 entry와 SPSR를 non-secure context에 넣고 마지막 ERET으로 U-Boot 또는 Linux에 제어권을 넘기는 경로를 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. BL32 init complete → select BL33 → prepare NS context → disable init mappings → ERET to BL33 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 final EL3 exit to BL33에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.
BL33가 U-Boot인지 Linux인지보다 architecture handoff 계약이 중요하다. target EL, endianness, MMU/cache 상태와 x0-x3 의미를 구분한다. 따라서 첫 지점에서 entry_point_info_t / NON_SECURE cpu_context의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 ERET 직전 next context는 NON_SECURE이며 BL33 entry가 허용된 non-secure executable memory를 가리키고 runtime BL31 영역과 겹치지 않아야 한다.
BL33 entry_point_info와 x0-x3 args의 생성 시점과 수명
이 글에서 함께 나타나는 객체는 BL33 entry_point_info, NON_SECURE cpu_context, SPSR/SCR_EL3, x0-x3 args이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.
entry_point_info_t / NON_SECURE cpu_context을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.
성공 로그만으로 놓치기 쉬운 실패 경계
대표적인 실패 조건은 target EL 불일치: BL33 첫 exception; SCR.NS 누락: secure 상태로 U-Boot 실행; reserved memory 누락: Linux가 BL31/OP-TEE 덮어씀이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.
재현에는 BL33 entry와 U-Boot ELF symbol 대조; ERET 직전 SCR/SPSR/x0-x3 기록; Linux DT reserved-memory와 secure carveout 비교를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.
DEEP ANALYSIS
레지스터에서 오류 판정까지 상세 분석
BL33 handoff는 TF-A가 마지막으로 Normal World 실행 환경을 조립하는 지점이다. BL33이 U-Boot, UEFI, 직접 부팅되는 Linux 중 무엇인지는 platform에 따라 달라도, non-secure memory의 entry address, target EL, execution width, x0-x3 argument와 cache/MMU 상태는 명시적으로 일치해야 한다.
BL31은 자신과 OP-TEE가 사용하는 secure carveout을 Normal World에 넘기지 않는다. 따라서 entry context뿐 아니라 DT reserved-memory, memory controller firewall, BL33이 보는 DRAM map까지 대조해야 Linux가 나중에 secure RAM을 page allocator에 넣는 문제를 막을 수 있다.
non-secure executable memory의 정렬된 entry여야 한다.
target EL1/EL2, AArch64/AArch32, interrupt mask가 payload ABI와 맞아야 한다.
NS=1, RW/HCE와 exception routing이 target 환경과 일치해야 한다.
U-Boot/UEFI/Linux가 기대하는 DTB·parameter convention을 따른다.
BL31·OP-TEE secure region이 non-secure RAM에서 제외돼야 한다.
각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.
진입 레지스터와 메모리 계약
함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.
| # | 입력 상태 | 생산자 | 정상 조건 | 확인 이유 |
|---|---|---|---|---|
| 01 | BL33 ep_info.pc | BL2/post-load hook | non-secure executable memory의 정렬된 entry여야 한다. | ELR_EL3에 설치돼 최초 Normal World PC가 된다. |
| 02 | BL33 ep_info.spsr | platform | target EL1/EL2, AArch64/AArch32, interrupt mask가 payload ABI와 맞아야 한다. | ERET 뒤 PSTATE를 결정한다. |
| 03 | SCR_EL3 | context management | NS=1, RW/HCE와 exception routing이 target 환경과 일치해야 한다. | Non-secure world와 hypervisor access를 설정한다. |
| 04 | x0-x3 | platform boot protocol | U-Boot/UEFI/Linux가 기대하는 DTB·parameter convention을 따른다. | 첫 함수의 argument register가 된다. |
| 05 | memory map | platform/DT/firewall | BL31·OP-TEE secure region이 non-secure RAM에서 제외돼야 한다. | handoff 이후의 격리와 allocator 안전성을 보장한다. |
핵심 구조체 필드의 생산자, 소비자와 수명
구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.
| # | 객체 또는 필드 | 생산자 | 소비자 | 수명과 불변 조건 |
|---|---|---|---|---|
| 01 | BL33 entry_point_info | BL2/platform | bl31_prepare_next_image_entry | NON_SECURE cpu_context에 복사될 때까지 유효하다. |
| 02 | NON_SECURE cpu_context | context management | 최초 ERET와 이후 SMC | CPU별 Normal World context로 runtime 동안 유지된다. |
| 03 | x0-x3 parameter data | bootloader/platform | BL33 first-stage code | pointer가 가리키는 DT/parameter memory는 BL33이 복사·소비할 때까지 유지된다. |
| 04 | secure carveout | platform memory controller와 DT | OP-TEE/BL31 | reset까지 secure owner가 독점하며 NS mapping이 생기면 안 된다. |
| 05 | BL31 resident region | linker/platform map | EL3 runtime | Linux가 실행된 뒤에도 PSCI/SMC 처리를 위해 보존된다. |
| 06 | init mappings | BL31 architecture setup | handoff cleanup | 필요 없어진 mapping을 제거해도 runtime text/data와 device mapping은 남아야 한다. |
함수 내부 실행 순서
소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.
- 01
BL32 초기화가 있다면 dispatcher의 성공 return을 확인하고 secure context를 resident 상태로 남긴다.
- 02
BL31이 NON_SECURE type의 next image_info와 entry_point_info를 선택한다.
- 03
entry PC가 non-secure address range, alignment, image size 안에 있는지 platform 규칙으로 검증한다.
- 04
target EL과 execution width에 맞는 SPSR_EL3를 만들고 interrupt mask 초기값을 결정한다.
- 05
x0-x3 boot argument와 그 pointer가 가리키는 DTB/parameter 영역의 수명을 확인한다.
- 06
NON_SECURE cpu_context에 ELR, SPSR, SCR, general register와 필요한 EL1/EL2 state를 설치한다.
- 07
secure carveout과 BL31 region이 DT와 firewall에서 Normal World에 노출되지 않았는지 대조한다.
- 08
init-only mapping, console, cache maintenance를 정리하고 target context를 active로 선택한다.
- 09
ERET로 BL33에 들어간 뒤 최초 exception/SMC가 다시 BL31로 돌아오는 경로까지 확인한다.
빌드 설정이 바꾸는 실제 코드 경로
동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.
| # | 설정 | 바뀌는 동작 | 확인 방법 |
|---|---|---|---|
| 01 | BL33 | Normal World firmware image와 FIP entry를 선택한다. | unpack hash와 ep_info.pc가 해당 binary entry와 맞는지 본다. |
| 02 | PRELOADED_BL33_BASE | BL2 load 대신 미리 놓인 image를 사용한다. | preloaded owner, size, cache clean 책임을 기록한다. |
| 03 | RESET_TO_BL31 | BL31이 platform에서 BL33 정보를 직접 얻을 수 있다. | BL2 parameter가 없는 경로의 ep_info 생성자를 확인한다. |
| 04 | SPD=opteed | BL33 전에 BL32 init과 secure carveout 요구가 추가된다. | BL32 실패 시 BL33 진행 정책이 fail-closed인지 확인한다. |
| 05 | ARM_LINUX_KERNEL_AS_BL33 계열 platform 경로 | x0 DTB와 target EL 규약이 직접 Linux entry에 맞춰진다. | U-Boot handoff 규약과 섞지 않는다. |
증상에서 최초 불일치 지점까지 추적하기
마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.
| # | 관찰 증상 | 중단 위치 | 기록할 값 | 판정 |
|---|---|---|---|---|
| 01 | ERET 뒤 첫 instruction abort | BL31 exit와 BL33 entry | ELR, SPSR, SCR, opcode, memory attribute | entry 주소·target EL·mapping 중 첫 불일치를 찾는다. |
| 02 | U-Boot는 뜨지만 DTB를 못 찾음 | BL33 첫 함수 | x0-x3, DTB magic/address, cache state | platform argument convention 불일치를 확인한다. |
| 03 | Linux 부팅 중 secure RAM page fault | DT memory/reserved-memory와 OP-TEE map | secure base/size, memblock reservation | handoff memory map에서 carveout이 빠졌는지 판정한다. |
| 04 | 첫 PSCI/SMC 복귀에서 crash | EL3 vector 재진입 | BL31 resident mapping, per-CPU NS context | handoff cleanup이 runtime state를 지웠는지 확인한다. |
OBJECT LIFETIME
객체와 수명
| 대상 | 만들어지는 시점 | 유효 범위 | 확인할 조건 |
|---|---|---|---|
entry_point_info_t / NON_SECURE cpu_context | select BL33 | ERET to BL33 또는 오류 정리 완료까지 | 진입 전제와 상태 계약 |
| 입력 buffer / metadata | BL32 init complete | parse와 검증이 끝날 때까지 | 길이, 정렬, 소유권, 변조 가능성 |
| 등록된 list / descriptor | prepare NS context | subsystem 종료 또는 image handoff까지 | 이중 등록, dangling pointer, 오류 unwind |
| hardware 또는 persistent state | 실제 write/probe가 완료된 뒤 | reset 또는 명시적 해제·갱신까지 | flush, timeout, 전원 차단, rollback |
최종 부트로더 이미지 | link/image 생성 시점 | 다음 stage가 새 image로 교체할 때까지 | load address, entry, section과 header 일치 |
FAILURE PATH
실패 지점과 증상
| # | 조건 | 관찰되는 증상 | 먼저 볼 단계 |
|---|---|---|---|
| 01 | target EL 불일치 | BL33 첫 exception | select BL33 |
| 02 | SCR.NS 누락 | secure 상태로 U-Boot 실행 | prepare NS context |
| 03 | reserved memory 누락 | Linux가 BL31/OP-TEE 덮어씀 | disable init mappings |
로그가 끊긴 마지막 함수만 고치지 않는다. 그 함수가 받은 주소, size, flag가 만들어진 앞 단계까지 올라가고, 오류 뒤 등록 객체와 hardware 상태가 남았는지도 확인한다.
EVIDENCE
소스 밖에서 확인할 증거
소스 해석은 실제 빌드 산출물과 target 로그로 닫아야 한다. 아래 명령의 보드 이름과 toolchain prefix는 사용 중인 빌드 환경에 맞게 바꾼다.
| # | 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|---|
| 01 | 빌드 산출물 | make PLAT=<platform> DEBUG=1 all fip | BL1, BL2, BL31과 FIP가 같은 설정으로 만들어졌는지 전체 빌드 명령부터 기록한다. |
| 02 | FIP 구성 | tools/fiptool/fiptool info build/<platform>/debug/fip.bin | FIP 안의 BL31, BL32, BL33 UUID와 offset, 크기를 확인해 실제 적재 입력을 고정한다. |
| 03 | 심볼과 주소 | ${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep 'void __init bl31_prepare_next_image_entry' | 대상 함수가 BL31의 어느 주소와 섹션에 놓였는지 확인한다. |
| 04 | EL3 명령 추적 | ${CROSS_COMPILE}objdump -drS build/<platform>/debug/bl31/bl31.elf | C 코드가 EL3 system register 접근과 eret 경로로 어떻게 번역됐는지 대조한다. |
| 05 | 실행 시점 증거 | TF-A DEBUG log + CurrentEL/SCR_EL3/SPSR_EL3/x0-x3 기록 | 어느 exception level에서 어떤 security state와 인자를 다음 이미지에 넘겼는지 serial log로 남긴다. |
LAB
직접 확인할 실험
- 01BL33 entry와 U-Boot ELF symbol 대조
select BL33진입 전후에 BL33 entry_point_info의 주소·크기·반환값과 timestamp를 함께 남긴다. - 02ERET 직전 SCR/SPSR/x0-x3 기록
prepare NS context진입 전후에 NON_SECURE cpu_context의 주소·크기·반환값과 timestamp를 함께 남긴다. - 03Linux DT reserved-memory와 secure carveout 비교
disable init mappings진입 전후에 SPSR/SCR_EL3의 주소·크기·반환값과 timestamp를 함께 남긴다.
PRIMARY REFERENCES