Trusted Firmware-A · source analysis

FIP I/O driver의 UUID lookup과 bounds

FIP header와 ToC를 읽고 요청 UUID에 해당하는 payload offset과 길이를 io_entity로 노출하는 경로를 읽습니다.

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

Series
04 / 12
Baseline
LTS 2.14.3
Commit
f5e765a3443f
Source
drivers/io/io_fip.c:50-138 (발췌 범위)

FIP I/O driver의 UUID lookup과 bounds 단계에서 실제로 바뀌는 상태는 무엇인가?

FIP parser가 믿는 값은 storage에서 읽은 비신뢰 metadata다. terminator, serial number, offset, size와 backend length 검사를 먼저 확인한다.

반환된 entity의 모든 read는 선택한 ToC entry의 payload 범위를 넘지 않아야 하며 다른 FIP instance의 state와 섞이면 안 된다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. FIP I/O driver의 UUID lookup과 bounds에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01io_dev_info_t
02fip_toc_header
03fip_toc_entry
04io_entity_t

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
backend device open
FIP header read
ToC scan
UUID match
entity seek/read

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01backend device openBL2 storage I/O contextio_dev_info_tFIP header read
02FIP header readbackend device open 완료 상태fip_toc_headerToC scan
03ToC scanFIP header read 완료 상태fip_toc_entryUUID match
04UUID matchToC scan 완료 상태io_entity_tentity seek/read
05entity seek/readUUID match 완료 상태io_entity_t이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. FIP I/O driver의 UUID lookup과 bounds의 실행 순서

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

01backend device open
02FIP header read
03ToC scan
04UUID match
05entity seek/read
그림 4. FIP metadata와 열린 payload entity

두 열은 실행 주체와 접근 권한, 객체를 해제할 책임이 다른 경계를 비교한다.

FIP ToC

01비신뢰 storage 입력

02UUID·offset·size

03terminator 필요

04backend bounds 검사

io_entity

01한 UUID의 payload

02현재 read position

03entry 길이로 제한

04close 시 state 해제

원본 코드

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

commitf5e765a3443fe21154aa908228e75ee2600085f6anchor · L74static int fip_file_open(io_dev_info_t *dev_info
50	uintptr_t dev_spec;
51	size_t fip_size;
52	uint16_t plat_toc_flag;
53} fip_dev_state_t;
54
55/*
56 * Only one file can be open across all FIP device
57 * as backends like io_memmap don't support
58 * multiple open files. The file state and
59 * backend handle should be maintained per FIP device
60 * if the same support is available in the backend
61 */
62static fip_file_state_t current_fip_file = {0};
63static uintptr_t backend_dev_handle;
64static uintptr_t backend_image_spec;
65
66static fip_dev_state_t state_pool[MAX_FIP_DEVICES];
67static io_dev_info_t dev_info_pool[MAX_FIP_DEVICES];
68
69/* Track number of allocated fip devices */
70static unsigned int fip_dev_count;
71
72/* Firmware Image Package driver functions */
73static int fip_dev_open(const uintptr_t dev_spec, io_dev_info_t **dev_info);
74static int fip_file_open(io_dev_info_t *dev_info, const uintptr_t spec,
75			  io_entity_t *entity);
76static int fip_file_len(io_entity_t *entity, size_t *length);
77static int fip_file_read(io_entity_t *entity, uintptr_t buffer, size_t length,
78			  size_t *length_read);
79static int fip_file_close(io_entity_t *entity);
80static int fip_dev_init(io_dev_info_t *dev_info, const uintptr_t init_params);
81static int fip_dev_close(io_dev_info_t *dev_info);
82
83
84/* Return 0 for equal uuids. */
85static inline int compare_uuids(const uuid_t *uuid1, const uuid_t *uuid2)
86{
87	return memcmp(uuid1, uuid2, sizeof(uuid_t));
88}
89
90
91static inline int is_valid_header(fip_toc_header_t *header)
92{
93	if ((header->name == TOC_HEADER_NAME) && (header->serial_number != 0)) {
94		return 1;
95	} else {
96		return 0;
97	}
98}
99
100
101/* Identify the device type as a virtual driver */
102static io_type_t device_type_fip(void)
103{
104	return IO_TYPE_FIRMWARE_IMAGE_PACKAGE;
105}
106
107
108static const io_dev_connector_t fip_dev_connector = {
109	.dev_open = fip_dev_open
110};
111
112
113static const io_dev_funcs_t fip_dev_funcs = {
114	.type = device_type_fip,
115	.open = fip_file_open,
116	.seek = NULL,
117	.size = fip_file_len,
118	.read = fip_file_read,
119	.write = NULL,
120	.close = fip_file_close,
121	.dev_init = fip_dev_init,
122	.dev_close = fip_dev_close,
123};
124
125/* Locate a file state in the pool, specified by address */
126static int find_first_fip_state(const uintptr_t dev_spec,
127				  unsigned int *index_out)
128{
129	int result = -ENOENT;
130	unsigned int index;
131
132	for (index = 0; index < (unsigned int)MAX_FIP_DEVICES; ++index) {
133		/* dev_spec is used as identifier since it's unique */
134		if (state_pool[index].dev_spec == dev_spec) {
135			result = 0;
136			*index_out = index;
137			break;
138		}

발췌 범위와 읽기 기준

원문 50-138줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 static int fip_file_open(io_dev_info_t *dev_info은 L74에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

FIP parser가 믿는 값은 storage에서 읽은 비신뢰 metadata다. terminator, serial number, offset, size와 backend length 검사를 먼저 확인한다.

함께 읽어야 하는 원본 코드

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

01. 선택한 ToC entry 범위에서 payload를 읽는 함수

drivers/io/io_fip.c 67-169줄이다.

filedrivers/io/io_fip.canchor · L77static int fip_file_read(io_entity_t *entity
67static io_dev_info_t dev_info_pool[MAX_FIP_DEVICES];
68
69/* Track number of allocated fip devices */
70static unsigned int fip_dev_count;
71
72/* Firmware Image Package driver functions */
73static int fip_dev_open(const uintptr_t dev_spec, io_dev_info_t **dev_info);
74static int fip_file_open(io_dev_info_t *dev_info, const uintptr_t spec,
75			  io_entity_t *entity);
76static int fip_file_len(io_entity_t *entity, size_t *length);
77static int fip_file_read(io_entity_t *entity, uintptr_t buffer, size_t length,
78			  size_t *length_read);
79static int fip_file_close(io_entity_t *entity);
80static int fip_dev_init(io_dev_info_t *dev_info, const uintptr_t init_params);
81static int fip_dev_close(io_dev_info_t *dev_info);
82
83
84/* Return 0 for equal uuids. */
85static inline int compare_uuids(const uuid_t *uuid1, const uuid_t *uuid2)
86{
87	return memcmp(uuid1, uuid2, sizeof(uuid_t));
88}
89
90
91static inline int is_valid_header(fip_toc_header_t *header)
92{
93	if ((header->name == TOC_HEADER_NAME) && (header->serial_number != 0)) {
94		return 1;
95	} else {
96		return 0;
97	}
98}
99
100
101/* Identify the device type as a virtual driver */
102static io_type_t device_type_fip(void)
103{
104	return IO_TYPE_FIRMWARE_IMAGE_PACKAGE;
105}
106
107
108static const io_dev_connector_t fip_dev_connector = {
109	.dev_open = fip_dev_open
110};
111
112
113static const io_dev_funcs_t fip_dev_funcs = {
114	.type = device_type_fip,
115	.open = fip_file_open,
116	.seek = NULL,
117	.size = fip_file_len,
118	.read = fip_file_read,
119	.write = NULL,
120	.close = fip_file_close,
121	.dev_init = fip_dev_init,
122	.dev_close = fip_dev_close,
123};
124
125/* Locate a file state in the pool, specified by address */
126static int find_first_fip_state(const uintptr_t dev_spec,
127				  unsigned int *index_out)
128{
129	int result = -ENOENT;
130	unsigned int index;
131
132	for (index = 0; index < (unsigned int)MAX_FIP_DEVICES; ++index) {
133		/* dev_spec is used as identifier since it's unique */
134		if (state_pool[index].dev_spec == dev_spec) {
135			result = 0;
136			*index_out = index;
137			break;
138		}
139	}
140	return result;
141}
142
143
144/* Allocate a device info from the pool and return a pointer to it */
145static int allocate_dev_info(io_dev_info_t **dev_info)
146{
147	int result = -ENOMEM;
148
149	assert(dev_info != NULL);
150
151	if (fip_dev_count < (unsigned int)MAX_FIP_DEVICES) {
152		unsigned int index = 0;
153
154		result = find_first_fip_state(0, &index);
155		assert(result == 0);
156		/* initialize dev_info */
157		dev_info_pool[index].funcs = &fip_dev_funcs;
158		dev_info_pool[index].info =
159				(uintptr_t)&state_pool[index];
160		*dev_info = &dev_info_pool[index];
161		++fip_dev_count;
162	}
163
164	return result;
165}
166
167/* Release a device info to the pool */
168static int free_dev_info(io_dev_info_t *dev_info)
169{

02. FIP header와 ToC를 읽어 container state를 초기화

drivers/io/io_fip.c 70-168줄이다.

filedrivers/io/io_fip.canchor · L80static int fip_dev_init(io_dev_info_t *dev_info
70static unsigned int fip_dev_count;
71
72/* Firmware Image Package driver functions */
73static int fip_dev_open(const uintptr_t dev_spec, io_dev_info_t **dev_info);
74static int fip_file_open(io_dev_info_t *dev_info, const uintptr_t spec,
75			  io_entity_t *entity);
76static int fip_file_len(io_entity_t *entity, size_t *length);
77static int fip_file_read(io_entity_t *entity, uintptr_t buffer, size_t length,
78			  size_t *length_read);
79static int fip_file_close(io_entity_t *entity);
80static int fip_dev_init(io_dev_info_t *dev_info, const uintptr_t init_params);
81static int fip_dev_close(io_dev_info_t *dev_info);
82
83
84/* Return 0 for equal uuids. */
85static inline int compare_uuids(const uuid_t *uuid1, const uuid_t *uuid2)
86{
87	return memcmp(uuid1, uuid2, sizeof(uuid_t));
88}
89
90
91static inline int is_valid_header(fip_toc_header_t *header)
92{
93	if ((header->name == TOC_HEADER_NAME) && (header->serial_number != 0)) {
94		return 1;
95	} else {
96		return 0;
97	}
98}
99
100
101/* Identify the device type as a virtual driver */
102static io_type_t device_type_fip(void)
103{
104	return IO_TYPE_FIRMWARE_IMAGE_PACKAGE;
105}
106
107
108static const io_dev_connector_t fip_dev_connector = {
109	.dev_open = fip_dev_open
110};
111
112
113static const io_dev_funcs_t fip_dev_funcs = {
114	.type = device_type_fip,
115	.open = fip_file_open,
116	.seek = NULL,
117	.size = fip_file_len,
118	.read = fip_file_read,
119	.write = NULL,
120	.close = fip_file_close,
121	.dev_init = fip_dev_init,
122	.dev_close = fip_dev_close,
123};
124
125/* Locate a file state in the pool, specified by address */
126static int find_first_fip_state(const uintptr_t dev_spec,
127				  unsigned int *index_out)
128{
129	int result = -ENOENT;
130	unsigned int index;
131
132	for (index = 0; index < (unsigned int)MAX_FIP_DEVICES; ++index) {
133		/* dev_spec is used as identifier since it's unique */
134		if (state_pool[index].dev_spec == dev_spec) {
135			result = 0;
136			*index_out = index;
137			break;
138		}
139	}
140	return result;
141}
142
143
144/* Allocate a device info from the pool and return a pointer to it */
145static int allocate_dev_info(io_dev_info_t **dev_info)
146{
147	int result = -ENOMEM;
148
149	assert(dev_info != NULL);
150
151	if (fip_dev_count < (unsigned int)MAX_FIP_DEVICES) {
152		unsigned int index = 0;
153
154		result = find_first_fip_state(0, &index);
155		assert(result == 0);
156		/* initialize dev_info */
157		dev_info_pool[index].funcs = &fip_dev_funcs;
158		dev_info_pool[index].info =
159				(uintptr_t)&state_pool[index];
160		*dev_info = &dev_info_pool[index];
161		++fip_dev_count;
162	}
163
164	return result;
165}
166
167/* Release a device info to the pool */
168static int free_dev_info(io_dev_info_t *dev_info)

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

FIP parser가 믿는 값은 storage에서 읽은 비신뢰 metadata다. terminator, serial number, offset, size와 backend length 검사를 먼저 확인한다.

02

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

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

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

03

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

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

04

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

FIP header read → ToC scan → UUID match 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.

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

05

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

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

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

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

01

backend device open에서 entity seek/read까지 제어권이 이동하는 조건

FIP header와 ToC를 읽고 요청 UUID에 해당하는 payload offset과 길이를 io_entity로 노출하는 경로를 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. backend device open → FIP header read → ToC scan → UUID match → entity seek/read 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 BL2 storage I/O context에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.

FIP parser가 믿는 값은 storage에서 읽은 비신뢰 metadata다. terminator, serial number, offset, size와 backend length 검사를 먼저 확인한다. 따라서 첫 지점에서 fip_state_t / io_entity_t의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 반환된 entity의 모든 read는 선택한 ToC entry의 payload 범위를 넘지 않아야 하며 다른 FIP instance의 state와 섞이면 안 된다.

02

io_dev_info_t와 io_entity_t의 생성 시점과 수명

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

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

03

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

대표적인 실패 조건은 terminator 누락: ToC overrun; offset overflow: 임의 storage read; shared state 오염: 다른 FIP payload 선택이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.

재현에는 FIP ToC offset을 변조해 open 실패 확인; 동시에 두 FIP device를 열어 state 분리 확인; 짧은 backend에서 read 반환값 기록를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.

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

FIP I/O driver는 UUID를 파일 이름으로 바꾸는 얇은 adapter가 아니다. backend device 위에 FIP container view를 만들고, ToC entry가 허용한 payload 구간 안에서만 seek/read가 일어나도록 io_entity의 위치와 size를 관리한다.

분석의 핵심은 container offset, backend offset, entity relative offset을 구분하는 것이다. 특히 offset + length 계산은 overflow 이전의 값으로 bounds를 검사해야 하며, terminator를 찾았다는 사실만으로 앞선 entry의 범위가 유효하다고 볼 수 없다.

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

FIP device가 읽을 block/flash/file backend여야 한다.

02FIP image spec

container 시작 offset과 최대 범위가 storage 안에 있어야 한다.

03requested UUID

정확히 하나의 non-terminator ToC entry와 일치해야 한다.

04entity position

0부터 entry.size 사이의 상대 offset으로 유지한다.

05read length

remaining size보다 크면 truncate 정책 또는 오류가 명확해야 한다.

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

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

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

#입력 상태생산자정상 조건확인 이유
01backend handleplatform I/O policyFIP device가 읽을 block/flash/file backend여야 한다.모든 ToC와 payload read의 실제 owner다.
02FIP image specplatform policycontainer 시작 offset과 최대 범위가 storage 안에 있어야 한다.partition 안에 FIP가 놓인 경우 절대 주소를 결정한다.
03requested UUIDimage ID policy정확히 하나의 non-terminator ToC entry와 일치해야 한다.잘못된 image를 여는 것을 막는다.
04entity positionfip_file_open/seek0부터 entry.size 사이의 상대 offset으로 유지한다.payload 밖 backend read를 차단한다.
05read lengthcallerremaining size보다 크면 truncate 정책 또는 오류가 명확해야 한다.short read를 성공으로 오해하지 않게 한다.

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

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

#객체 또는 필드생산자소비자수명과 불변 조건
01fip_dev_info_t/backend_dev_handleio_dev_initFIP open/readFIP device가 닫힐 때까지 backend 참조를 유지한다.
02fip_state_tfip device initopen entity현재 FIP container의 base와 ToC 상태를 소유하며 다른 instance와 섞이면 안 된다.
03fip_toc_headerstorageinit parserheader validation 순간의 buffer 수명과 별개로 필요한 field를 state에 보존한다.
04fip_toc_entrystorage ToCUUID lookupentry를 복사하는지 storage buffer를 참조하는지 확인하고 entity 종료까지 유효해야 한다.
05io_entity_t/infoio_openseek/read/close한 open request의 current position과 selected payload를 소유한다.
06backend block bufferstorage driverio_readcallback 반환 뒤에도 pointer를 보존하지 않고 필요한 byte를 즉시 소비해야 한다.

함수 내부 실행 순서

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

  1. 01

    platform policy가 FIP container가 있는 backend와 image spec을 반환한다.

  2. 02

    FIP device가 backend를 열고 container base에서 header 고정 길이만 읽는다.

  3. 03

    magic과 지원 header 조건을 확인한 뒤 ToC entry를 하나씩 읽는다.

  4. 04

    각 entry에서 terminator 여부와 offset+size overflow, container 최대 범위를 검사한다.

  5. 05

    요청 UUID와 일치하는 entry를 찾고 payload base와 size를 entity private state에 기록한다.

  6. 06

    seek는 entity 상대 위치를 계산하며 음수·끝 초과·integer wrap을 거부한다.

  7. 07

    read는 payload base + current position을 backend 절대 위치로 바꾸고 remaining byte 안에서 수행한다.

  8. 08

    실제 읽은 길이만큼 position을 전진시키고 short read와 EOF를 caller 계약에 맞게 반환한다.

  9. 09

    close에서 entity state와 backend reference를 정리하되 다른 open entity의 state는 건드리지 않는다.

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

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

#설정바뀌는 동작확인 방법
01FIP_OFFSET/FIP_MAX_SIZE 계열 platform 값storage 내 container 위치와 상한을 바꾼다.partition table과 image spec의 byte 단위를 비교한다.
02io_block/io_mtd/io_memmap backendalignment, erase/read granularity와 short-read 성격이 달라진다.backend별 seek/read callback을 추적한다.
03TRUSTED_BOARD_BOOTFIP에서 certificate image도 연속해서 읽는다.UUID lookup 실패가 auth 실패로 보이지 않게 분리한다.
04multiple FIP source policyprimary/backup package fallback이 가능하다.device state와 entity가 fallback 사이에서 재사용되는지 확인한다.

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

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

#관찰 증상중단 위치기록할 값판정
01UUID match 로그 뒤 payload hash 불일치fip_file_open과 첫 readentry offset/size, backend absolute offsetcontainer-relative offset에 partition base를 빠뜨렸는지 확인한다.
02큰 payload 끝에서만 read 실패마지막 read 계산position, requested, remaining, offset+sizeexclusive end 또는 integer overflow 오류를 찾는다.
03backup FIP 전환 뒤 다른 image가 열림device init/openfip_state 주소, backend handle, ToC serialglobal state 재사용으로 instance가 섞였는지 판정한다.
04손상 ToC에서 hangToC scan loopentry index, terminator, read return lengthterminator 누락과 short read 처리 여부를 확인한다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01terminator 누락ToC overrunFIP header read
02offset overflow임의 storage readToC scan
03shared state 오염다른 FIP payload 선택UUID match

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
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 'static int fip_file_open'대상 함수가 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
    FIP ToC offset을 변조해 open 실패 확인

    FIP header read 진입 전후에 io_dev_info_t의 주소·크기·반환값과 timestamp를 함께 남긴다.

  2. 02
    동시에 두 FIP device를 열어 state 분리 확인

    ToC scan 진입 전후에 fip_toc_header의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    짧은 backend에서 read 반환값 기록

    UUID match 진입 전후에 fip_toc_entry의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글