Trusted Firmware-A · source analysis

BL2 image descriptor와 순차 적재

BL2가 platform image policy를 따라 BL31, BL32, BL33을 인증하고 reserved memory에 배치하는 전체 loop를 읽습니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. TF-A LTS 2.14.3 이후에는 보안 수정이 있습니다. 제품 적용 시 공식 변경 기록과 사용 플랫폼의 errata를 확인하세요.

Series
03 / 12
Baseline
LTS 2.14.3
Commit
f5e765a3443f
Source
bl2/bl2_main.c:18-106 (발췌 범위)

BL2 image descriptor와 순차 적재 단계에서 실제로 바뀌는 상태는 무엇인가?

BL2는 단순 복사기가 아니다. parent certificate, image ID, load region, executable 여부와 다음 image parameter list를 한꺼번에 관리한다.

각 image의 destination은 허용된 secure/non-secure 영역에 있고 선행 인증서와 payload 인증이 성공한 뒤 executable parameter에 공개되어야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. BL2 image descriptor와 순차 적재에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01bl_mem_params_node_t
02image_info_t
03entry_point_info_t
04bl_params_t

bl_mem_params_node_t / bl_params_t를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
BL1 handoff
BL2 platform setup
image descriptor walk
load/auth images
BL31 params

화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.

단계별 입력과 출력

각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01BL1 handoffBL2 trusted boot stagebl_mem_params_node_tBL2 platform setup
02BL2 platform setupBL1 handoff 완료 상태image_info_timage descriptor walk
03image descriptor walkBL2 platform setup 완료 상태entry_point_info_tload/auth images
04load/auth imagesimage descriptor walk 완료 상태bl_params_tBL31 params
05BL31 paramsload/auth images 완료 상태bl_params_t이 단계의 처리 결과를 사용하는 코드

분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.

주소와 객체의 이동을 그림으로 읽기

아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.

그림 3. BL2 image descriptor와 순차 적재의 실행 순서

각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.

01BL1 handoff
02BL2 platform setup
03image descriptor walk
04load/auth images
05BL31 params
그림 4. image descriptor가 BL31 parameter가 되는 과정

왼쪽에서 만든 상태를 오른쪽 단계가 처음 사용하는 관계를 표시한다.

01image_idpolicy/UUID 선택image_info
02auth parentcertificate 검증authenticated payload
03load_infodestination boundsloaded image
04ep_infoSPSR·security stateBL31 params

원본 코드

아래 코드는 Trusted Firmware-A LTS 2.14.3의 bl2/bl2_main.c에서 18-106줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commitf5e765a3443fe21154aa908228e75ee2600085f6anchor · L42void __no_pauth bl2_main(
18#include <drivers/console.h>
19#include <drivers/fwu/fwu.h>
20#include <lib/bootmarker_capture.h>
21#include <lib/extensions/pauth.h>
22#include <lib/pmf/pmf.h>
23#include <plat/common/platform.h>
24
25#include "bl2_private.h"
26
27#ifdef __aarch64__
28#define NEXT_IMAGE	"BL31"
29#else
30#define NEXT_IMAGE	"BL32"
31#endif
32
33#if ENABLE_RUNTIME_INSTRUMENTATION
34	PMF_REGISTER_SERVICE(bl_svc, PMF_RT_INSTR_SVC_ID,
35		BL_TOTAL_IDS, PMF_DUMP_ENABLE);
36#endif
37
38/*******************************************************************************
39 * The only thing to do in BL2 is to load further images and pass control to
40 * next BL. The memory occupied by BL2 will be reclaimed by BL3x stages.
41 ******************************************************************************/
42void __no_pauth bl2_main(u_register_t arg0, u_register_t arg1, u_register_t arg2,
43	       u_register_t arg3)
44{
45	entry_point_info_t *next_bl_ep_info;
46
47	/* Enable early console if EARLY_CONSOLE flag is enabled */
48	plat_setup_early_console();
49#if RESET_TO_BL2
50
51	/* Perform early platform-specific setup */
52	bl2_el3_early_platform_setup(arg0, arg1, arg2, arg3);
53
54	/* Perform late platform-specific setup */
55	bl2_el3_plat_arch_setup();
56#else /* RESET_TO_BL2 */
57	/* Perform early platform-specific setup */
58	bl2_early_platform_setup2(arg0, arg1, arg2, arg3);
59
60	/* Perform late platform-specific setup */
61	bl2_plat_arch_setup();
62#endif /* RESET_TO_BL2 */
63
64	if (is_feat_pauth_supported()) {
65#if BL2_RUNS_AT_EL3
66		pauth_init_enable_el3();
67#else
68		pauth_init_enable_el1();
69#endif
70	}
71
72#if ENABLE_RUNTIME_INSTRUMENTATION
73	PMF_CAPTURE_TIMESTAMP(bl_svc, BL2_ENTRY, PMF_CACHE_MAINT);
74#endif
75
76	NOTICE("BL2: %s\n", build_version_string);
77	NOTICE("BL2: %s\n", build_message);
78
79	/* Perform remaining generic architectural setup in S-EL1 */
80	bl2_arch_setup();
81
82#if PSA_FWU_SUPPORT
83	fwu_init();
84#endif /* PSA_FWU_SUPPORT */
85
86	crypto_mod_init();
87
88	/* Initialize authentication module */
89	auth_mod_init();
90
91	/* Initialize the Measured Boot backend */
92	bl2_plat_mboot_init();
93
94	/* Initialize boot source */
95	bl2_plat_preload_setup();
96
97	/* Load the subsequent bootloader images. */
98	next_bl_ep_info = bl2_load_images();
99
100	/* Teardown the Measured Boot backend */
101	bl2_plat_mboot_finish();
102
103	crypto_mod_finish();
104
105#if !BL2_RUNS_AT_EL3
106#ifndef __aarch64__

발췌 범위와 읽기 기준

원문 18-106줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 void __no_pauth bl2_main(은 L42에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

BL2는 단순 복사기가 아니다. parent certificate, image ID, load region, executable 여부와 다음 image parameter list를 한꺼번에 관리한다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.

01. parent certificate까지 재귀적으로 적재·인증

common/bl_common.c 205-275줄이다.

filecommon/bl_common.canchor · L217int load_auth_image(unsigned int image_id
205#endif
206
207	return load_image(image_id, image_data);
208}
209
210/*******************************************************************************
211 * Generic function to load and authenticate an image. The image is actually
212 * loaded by calling the 'load_image()' function. Therefore, it returns the
213 * same error codes if the loading operation failed, or -EAUTH if the
214 * authentication failed. In addition, this function uses recursion to
215 * authenticate the parent images up to the root of trust (if TBB is enabled).
216 ******************************************************************************/
217int load_auth_image(unsigned int image_id, image_info_t *image_data)
218{
219	int err;
220
221	if ((plat_try_img_ops == NULL) || (plat_try_img_ops->next_instance == NULL)) {
222		err = load_auth_image_internal(image_id, image_data);
223	} else {
224		do {
225			err = load_auth_image_internal(image_id, image_data);
226			if (err != 0) {
227				if (plat_try_img_ops->next_instance(image_id) != 0) {
228					return err;
229				}
230			}
231		} while (err != 0);
232	}
233
234	if (err == 0) {
235		/*
236		 * If loading of the image gets passed (along with its
237		 * authentication in case of Trusted-Boot flow) then measure
238		 * it (if MEASURED_BOOT flag is enabled).
239		 */
240		err = plat_mboot_measure_image(image_id, image_data);
241		if (err != 0) {
242			return err;
243		}
244
245		/*
246		 * Flush the image to main memory so that it can be executed
247		 * later by any CPU, regardless of cache and MMU state.
248		 */
249		flush_dcache_range(image_data->image_base,
250				   image_data->image_size);
251	}
252
253	return err;
254}
255
256/*******************************************************************************
257 * Print the content of an entry_point_info_t structure.
258 ******************************************************************************/
259void print_entry_point_info(const entry_point_info_t *ep_info)
260{
261	INFO("Entry point address = 0x%lx\n", ep_info->pc);
262	INFO("SPSR = 0x%x\n", ep_info->spsr);
263
264#define PRINT_IMAGE_ARG(n)					\
265	VERBOSE("Argument #" #n " = 0x%llx\n",			\
266		(unsigned long long) ep_info->args.arg##n)
267
268	PRINT_IMAGE_ARG(0);
269	PRINT_IMAGE_ARG(1);
270	PRINT_IMAGE_ARG(2);
271	PRINT_IMAGE_ARG(3);
272#ifdef __aarch64__
273	PRINT_IMAGE_ARG(4);
274	PRINT_IMAGE_ARG(5);
275	PRINT_IMAGE_ARG(6);

02. memory descriptor를 BL31 handoff parameter list로 변환

common/desc_image_load.c 122-226줄이다.

filecommon/desc_image_load.canchor · L132bl_params_t *get_next_bl_params_from_mem_params_desc(void)
122	return &bl_load_info;
123}
124
125/*******************************************************************************
126 * This function creates the list of executable images, by populating and
127 * linking each `bl_params_node_t` type node, using the internal array of
128 * image descriptor provided by bl_mem_params_desc_ptr. It also populates
129 * and returns `bl_params_t` type structure that contains head of the list
130 * of executable images.
131 ******************************************************************************/
132bl_params_t *get_next_bl_params_from_mem_params_desc(void)
133{
134	unsigned int count;
135	unsigned int img_id = 0U;
136	unsigned int link_index = 0U;
137	bl_params_node_t *bl_current_exec_node = NULL;
138	bl_params_node_t *bl_last_exec_node = NULL;
139	bl_mem_params_node_t *desc_ptr;
140
141	/* If there is no image to start with, return NULL */
142	if (bl_mem_params_desc_num == 0U)
143		return NULL;
144
145	/* Get the list HEAD */
146	for (count = 0U; count < bl_mem_params_desc_num; count++) {
147
148		desc_ptr = &bl_mem_params_desc_ptr[count];
149
150		if ((EP_GET_EXE(desc_ptr->ep_info.h.attr) == EXECUTABLE) &&
151			(EP_GET_FIRST_EXE(desc_ptr->ep_info.h.attr) == EP_FIRST_EXE)) {
152			next_bl_params.head = &desc_ptr->params_node_mem;
153			link_index = count;
154			break;
155		}
156	}
157
158	/* Make sure we have a HEAD node */
159	assert(next_bl_params.head != NULL);
160
161	/* Populate the HEAD information */
162	SET_PARAM_HEAD(&next_bl_params, PARAM_BL_PARAMS, VERSION_2, 0U);
163
164	/*
165	 * Go through the image descriptor array and create the list.
166	 * This bounded loop is to make sure that we are not looping forever.
167	 */
168	for (count = 0U; count < bl_mem_params_desc_num; count++) {
169
170		desc_ptr = &bl_mem_params_desc_ptr[link_index];
171
172		/* Make sure the image is executable */
173		assert(EP_GET_EXE(desc_ptr->ep_info.h.attr) == EXECUTABLE);
174
175		/* Get the memory for current node */
176		bl_current_exec_node = &desc_ptr->params_node_mem;
177
178		/* Populate the image information */
179		bl_current_exec_node->image_id = desc_ptr->image_id;
180		bl_current_exec_node->image_info = &desc_ptr->image_info;
181		bl_current_exec_node->ep_info = &desc_ptr->ep_info;
182
183		if (bl_last_exec_node != NULL) {
184			/* Assert if loop detected */
185			assert(bl_last_exec_node->next_params_info == NULL);
186
187			/* Link the previous node to the current one */
188			bl_last_exec_node->next_params_info = bl_current_exec_node;
189		}
190
191		/* Update the last node */
192		bl_last_exec_node = bl_current_exec_node;
193
194		/* If no next hand-off image then break out */
195		img_id = desc_ptr->next_handoff_image_id;
196		if (img_id == INVALID_IMAGE_ID)
197			break;
198
199		/* Get the index for the next hand-off image */
200		link_index = get_bl_params_node_index(img_id);
201		assert((link_index > 0U) &&
202			(link_index < bl_mem_params_desc_num));
203	}
204
205	/* Invalid image is expected to terminate the loop */
206	assert(img_id == INVALID_IMAGE_ID);
207
208	return &next_bl_params;
209}
210
211/*******************************************************************************
212 * This function populates the entry point information with the corresponding
213 * config file for all executable BL images described in bl_params.
214 ******************************************************************************/
215void populate_next_bl_params_config(bl_params_t *bl2_to_next_bl_params)
216{
217	/*
218	 * With Firmware Handoff configuration data is shared dynamically, most of
219	 * the *_CONFIG files will be deprecated. Avoid populating the entry point
220	 * arguments with their information as they're discarded anyway.
221	 */
222#if !TRANSFER_LIST
223	bl_params_node_t *params_node;
224	unsigned int fw_config_id;
225	uintptr_t fw_config_base;
226	bl_mem_params_node_t *mem_params;

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

BL1 handoff에서 들어온 실행은 BL2 trusted boot stage에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.

BL2는 단순 복사기가 아니다. parent certificate, image ID, load region, executable 여부와 다음 image parameter list를 한꺼번에 관리한다.

02

중심 객체의 생성과 공개를 나눈다

이 글의 중심 객체는 bl_mem_params_node_t / bl_params_t다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.

빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.

03

주소, 크기와 정렬을 계산한다

부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.

04

성공 flag와 실제 완료 시점을 맞춘다

BL2 platform setup → image descriptor walk → load/auth images 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.

다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.

05

제어권을 넘기기 전에 확인할 조건을 정리한다

정상 경로는 BL31 params에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.

호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.

구현을 읽을 때 놓치기 쉬운 부분

01

BL1 handoff에서 BL31 params까지 제어권이 이동하는 조건

BL2가 platform image policy를 따라 BL31, BL32, BL33을 인증하고 reserved memory에 배치하는 전체 loop를 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. BL1 handoff → BL2 platform setup → image descriptor walk → load/auth images → BL31 params 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 BL2 trusted boot stage에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.

BL2는 단순 복사기가 아니다. parent certificate, image ID, load region, executable 여부와 다음 image parameter list를 한꺼번에 관리한다. 따라서 첫 지점에서 bl_mem_params_node_t / bl_params_t의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 각 image의 destination은 허용된 secure/non-secure 영역에 있고 선행 인증서와 payload 인증이 성공한 뒤 executable parameter에 공개되어야 한다.

02

bl_mem_params_node_t와 bl_params_t의 생성 시점과 수명

이 글에서 함께 나타나는 객체는 bl_mem_params_node_t, image_info_t, entry_point_info_t, bl_params_t이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.

bl_mem_params_node_t / bl_params_t을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.

03

성공 로그만으로 놓치기 쉬운 오류

대표적인 실패 조건은 descriptor 순서 오류: parent 미인증; load region 겹침: 다음 image 손상; skip loading 오설정: 빈 entry 실행이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.

재현에는 descriptor list와 FIP ToC 대조; BL32 크기를 늘려 bounds 실패 확인; bl_params list를 BL31 진입 로그와 비교를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.

레지스터에서 오류 판정까지 상세 분석

BL2의 image loading은 BL31, BL32, BL33 파일을 차례대로 memcpy하는 loop가 아니다. platform이 등록한 bl_mem_params_node_t graph에는 image ID, load 정보, executable entry, 다음 handoff image가 연결되어 있으며 인증 의존 관계와 실행 순서는 동일하지 않을 수 있다.

각 node를 읽을 때 image_info는 저장·적재 범위를, ep_info는 실행 계약을, next_handoff_image_id는 BL31에 넘길 parameter chain을 표현한다. 세 객체의 의미를 섞으면 data-only certificate에 entry point를 기대하거나 executable image의 인증 완료 전에 pc를 공개하는 오류를 놓친다.

그림 5. 이 경로를 통과하는 다섯 개의 진입 계약
01BL1 parameter

BL2가 사용할 free trusted memory와 boot parameter를 가리킨다.

02mem params list

image ID가 고유하고 dependency/next link가 유효해야 한다.

03image_info

base, max_size, 실제 image_size를 구분한다.

04ep_info

executable image만 pc/spsr/security state가 유효하다.

05BL31 params

BL31·BL32·BL33 node가 올바른 순서와 type으로 연결돼야 한다.

각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.

진입 레지스터와 메모리 계약

함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.

#입력 상태생산자정상 조건확인 이유
01BL1 parameterBL1 handoff 또는 platform reset pathBL2가 사용할 free trusted memory와 boot parameter를 가리킨다.BL2 자신의 allocator와 image destination 계산의 시작점이다.
02mem params listREGISTER_BL_IMAGE_DESCS와 platform codeimage ID가 고유하고 dependency/next link가 유효해야 한다.전체 load·handoff graph를 정의한다.
03image_infoplatform descriptor와 loaderbase, max_size, 실제 image_size를 구분한다.storage read와 bounds 검사의 기준이다.
04ep_infodescriptor와 post-image-load hookexecutable image만 pc/spsr/security state가 유효하다.BL31 parameter list에서 소비된다.
05BL31 paramsbl2_plat_get_bl31_params 또는 bl_params listBL31·BL32·BL33 node가 올바른 순서와 type으로 연결돼야 한다.BL31이 다음 image를 선택하는 유일한 입력이다.

핵심 구조체 필드의 생산자, 소비자와 수명

구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.

#객체 또는 필드생산자소비자수명과 불변 조건
01bl_mem_params_node_t.image_idplatform descriptorget_bl_mem_params_nodeboot 동안 불변이며 auth/image policy ID와 일치해야 한다.
02bl_mem_params_node_t.image_infodescriptor와 load_auth_imageI/O와 post-load hookmax_size에서 실제 image_size로 좁혀지며 destination은 유지된다.
03bl_mem_params_node_t.ep_infodescriptor/post-loadBL31 handoff preparationexecutable node에서만 다음 EL 진입까지 유효하다.
04next_handoff_image_idplatform descriptorget_next_bl_params_from_mem_params_descparameter list를 구성하는 동안 cycle과 누락이 없어야 한다.
05bl_params_t/bl_params_node_tBL2 parameter builderBL31 entryBL2 memory 또는 shared region에 놓이며 BL31이 복사·소비할 때까지 유지된다.
06skip_loading flagplatform policyimage loading looppreloaded image의 주소와 인증 책임이 다른 stage에 있음을 명확히 해야 한다.

함수 내부 실행 순서

소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.

  1. 01

    BL2가 platform memory와 I/O framework를 초기화하고 descriptor table에 접근 가능한 상태를 만든다.

  2. 02

    image descriptor의 ID, type, parent, next_handoff link를 검사해 처리 순서를 결정한다.

  3. 03

    platform policy에서 image source device와 image spec을 얻고 backend를 연다.

  4. 04

    image_info.image_base와 image_max_size를 기준으로 destination overlap과 address overflow를 검사한다.

  5. 05

    payload를 읽어 실제 image_size를 기록하고 short read와 storage 오류를 분리한다.

  6. 06

    인증 모듈이 parent certificate, signature, hash, counter를 순서대로 검증한다.

  7. 07

    post-image-load hook이 executable image의 SPSR, argument, security state와 platform-specific metadata를 보정한다.

  8. 08

    next_handoff_image_id chain을 따라 bl_params list를 만들고 BL31, BL32, BL33의 순서를 확인한다.

  9. 09

    BL31 진입 전에 cache clean과 parameter memory 수명을 보장하고 BL2 임시 영역을 더 이상 참조하지 않게 한다.

빌드 설정이 바꾸는 실제 코드 경로

동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.

#설정바뀌는 동작확인 방법
01LOAD_IMAGE_V2v2 image descriptor와 bl_params list 경로를 사용한다.platform descriptor macro와 BL31 parameter ABI를 확인한다.
02TRUSTED_BOARD_BOOTload와 auth가 한 경로에서 결합된다.data/certificate/executable node별 auth method를 출력한다.
03BL32/BL33외부 payload node의 존재와 source가 달라진다.빈 path가 skip_loading으로 잘못 처리되지 않는지 본다.
04PRELOADED_BL33_BASEstorage load 없이 이미 놓인 BL33을 참조할 수 있다.preloaded range의 owner와 cache 상태를 별도로 검증한다.

증상에서 최초 불일치 지점까지 추적하기

마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.

#관찰 증상중단 위치기록할 값판정
01특정 image ID에서만 ENOENTplat_get_image_source 반환 직후image_id, device_handle, image_spec, UUIDdescriptor는 있지만 platform I/O policy가 빠졌는지 확인한다.
02두 payload를 읽은 뒤 hash가 변함각 load 전후모든 destination start/end와 image_sizedescriptor의 max_size 또는 실제 read 길이로 인한 overlap을 찾는다.
03BL31은 뜨지만 BL32/BL33 정보를 못 찾음bl_params list 생성node type, image_id, next_params_infonext_handoff chain 누락과 cache visibility를 구분한다.
04preloaded image에서만 faultskip_loading branch와 handoff 직전preloaded base, first bytes, cache maintenanceload를 건너뛴 대신 누가 유효성을 보장하는지 확인한다.

객체와 수명

대상만들어지는 시점유효 범위확인할 조건
bl_mem_params_node_t / bl_params_tBL2 platform setupBL31 params 또는 오류 정리 완료까지진입 전제와 상태 계약
입력 buffer / metadataBL1 handoffparse와 검증이 끝날 때까지길이, 정렬, 소유권, 변조 가능성
등록된 list / descriptorimage descriptor walk하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리
hardware 또는 persistent state실제 write/probe가 완료된 뒤reset 또는 명시적 해제·갱신까지쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원
최종 부트로더 이미지link/image 생성 시점다음 stage가 새 image로 교체할 때까지적재 주소, 진입점, 섹션, 헤더의 일치 여부

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01descriptor 순서 오류parent 미인증BL2 platform setup
02load region 겹침다음 image 손상image descriptor walk
03skip loading 오설정빈 entry 실행load/auth images

로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.

소스 밖에서 확인할 증거

소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01빌드 산출물make PLAT=<platform> DEBUG=1 all fipBL1, BL2, BL31과 FIP가 같은 설정으로 만들어졌는지 전체 빌드 명령부터 기록한다.
02FIP 구성tools/fiptool/fiptool info build/<platform>/debug/fip.binFIP 안의 BL31, BL32, BL33 UUID와 offset, 크기를 확인해 실제 적재 입력을 고정한다.
03심볼과 주소${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep 'void __no_pauth bl2_main'대상 함수가 BL31의 어느 주소와 섹션에 놓였는지 확인한다.
04EL3 명령 추적${CROSS_COMPILE}objdump -drS build/<platform>/debug/bl31/bl31.elfC 코드가 EL3 system register 접근과 eret 경로로 어떻게 번역됐는지 대조한다.
05실행 시점 증거TF-A DEBUG log + CurrentEL/SCR_EL3/SPSR_EL3/x0-x3 기록어느 exception level에서 어떤 security state와 인자를 다음 이미지에 넘겼는지 serial log로 남긴다.

직접 확인할 실험

  1. 01
    descriptor list와 FIP ToC 대조

    BL2 platform setup 진입 전후에 bl_mem_params_node_t의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    BL32 크기를 늘려 bounds 실패 확인

    image descriptor walk 진입 전후에 image_info_t의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    bl_params list를 BL31 진입 로그와 비교

    load/auth images 진입 전후에 entry_point_info_t의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글