QUESTION
SMC runtime service 등록과 dispatch 단계에서 실제로 바뀌는 상태는 무엇인가?
SMC function ID의 owner number, call type, 32/64-bit convention을 분리해서 본다. descriptor 초기화 실패가 runtime table에 어떤 빈칸을 남기는지도 확인한다.
한 SMC ID는 정확히 하나의 유효 descriptor로 dispatch되고 handler는 caller security state와 register width 계약을 위반하지 않아야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.
STRUCTURE
객체와 주소가 놓이는 구조
rt_svc_desc_t / SMC function ID를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.
CALL PATH
실행 흐름
화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.
STATE LEDGER
단계별 입력과 출력
각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.
| # | 단계 | 진입 시 신뢰할 상태 | 성공 뒤 남아야 할 상태 | 다음 소비자 |
|---|---|---|---|---|
| 01 | SMC exception | EL3 synchronous exception context | rt_svc_desc_t | decode owner/type |
| 02 | decode owner/type | SMC exception 완료 상태 | runtime_svc_descs_indices | descriptor index |
| 03 | descriptor index | decode owner/type 완료 상태 | SMCCC registers | service handler |
| 04 | service handler | descriptor index 완료 상태 | context handle | SMC return |
| 05 | SMC return | service handler 완료 상태 | context handle | 이 단계의 처리 결과를 사용하는 코드 |
분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.
VISUAL WALKTHROUGH
주소와 객체의 이동을 그림으로 읽기
아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.
각 칸은 제어권이 다음 단계로 넘어가기 전에 확정되어야 하는 상태를 나타낸다.
왼쪽에서 만든 상태를 오른쪽 단계가 처음 사용하는 관계를 표시한다.
bit 31→fast/yielding→call typebit 30→SMC32/SMC64→register widthOEN→service index→rt_svc_descfunction number→subcommand→handler branchUPSTREAM SOURCE
원본 코드
아래 코드는 Trusted Firmware-A LTS 2.14.3의 common/runtime_svc.c에서 8-96줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.
8#include <errno.h>
9#include <string.h>
10
11#include <common/debug.h>
12#include <common/runtime_svc.h>
13
14/*******************************************************************************
15 * The 'rt_svc_descs' array holds the runtime service descriptors exported by
16 * services by placing them in the 'rt_svc_descs' linker section.
17 * The 'rt_svc_descs_indices' array holds the index of a descriptor in the
18 * 'rt_svc_descs' array. When an SMC arrives, the OEN[29:24] bits and the call
19 * type[31] bit in the function id are combined to get an index into the
20 * 'rt_svc_descs_indices' array. This gives the index of the descriptor in the
21 * 'rt_svc_descs' array which contains the SMC handler.
22 ******************************************************************************/
23uint8_t rt_svc_descs_indices[MAX_RT_SVCS];
24
25#define RT_SVC_DECS_NUM ((RT_SVC_DESCS_END - RT_SVC_DESCS_START)\
26 / sizeof(rt_svc_desc_t))
27
28/*******************************************************************************
29 * Function to invoke the registered `handle` corresponding to the smc_fid in
30 * AArch32 mode.
31 ******************************************************************************/
32uintptr_t handle_runtime_svc(uint32_t smc_fid,
33 void *cookie,
34 void *handle,
35 unsigned int flags)
36{
37 u_register_t x1, x2, x3, x4;
38 unsigned int index;
39 unsigned int idx;
40 const rt_svc_desc_t *rt_svc_descs;
41
42 assert(handle != NULL);
43 idx = get_unique_oen_from_smc_fid(smc_fid);
44 assert(idx < MAX_RT_SVCS);
45
46 index = rt_svc_descs_indices[idx];
47 if (index >= RT_SVC_DECS_NUM)
48 SMC_RET1(handle, SMC_UNK);
49
50 rt_svc_descs = (rt_svc_desc_t *) RT_SVC_DESCS_START;
51
52 get_smc_params_from_ctx(handle, x1, x2, x3, x4);
53
54 return rt_svc_descs[index].handle(smc_fid, x1, x2, x3, x4, cookie,
55 handle, flags);
56}
57
58/*******************************************************************************
59 * Simple routine to sanity check a runtime service descriptor before using it
60 ******************************************************************************/
61static int32_t validate_rt_svc_desc(const rt_svc_desc_t *desc)
62{
63 if (desc == NULL) {
64 return -EINVAL;
65 }
66 if (desc->start_oen > desc->end_oen) {
67 return -EINVAL;
68 }
69 if (desc->end_oen >= OEN_LIMIT) {
70 return -EINVAL;
71 }
72 if ((desc->call_type != SMC_TYPE_FAST) &&
73 (desc->call_type != SMC_TYPE_YIELD)) {
74 return -EINVAL;
75 }
76 /* A runtime service having no init or handle function doesn't make sense */
77 if ((desc->init == NULL) && (desc->handle == NULL)) {
78 return -EINVAL;
79 }
80 return 0;
81}
82
83/*******************************************************************************
84 * This function calls the initialisation routine in the descriptor exported by
85 * a runtime service. Once a descriptor has been validated, its start & end
86 * owning entity numbers and the call type are combined to form a unique oen.
87 * The unique oen is used as an index into the 'rt_svc_descs_indices' array.
88 * The index of the runtime service descriptor is stored at this index.
89 ******************************************************************************/
90void __init runtime_svc_init(void)
91{
92 int rc = 0;
93 uint8_t index, start_idx, end_idx;
94 rt_svc_desc_t *rt_svc_descs;
95
96 /* Assert the number of descriptors detected are less than maximum indices */
READING CONTRACT
발췌 범위와 읽기 기준
원문 8-96줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 uintptr_t handle_runtime_svc(uint32_t smc_fid은 L32에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
SMC function ID의 owner number, call type, 32/64-bit convention을 분리해서 본다. descriptor 초기화 실패가 runtime table에 어떤 빈칸을 남기는지도 확인한다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. runtime service descriptor table 구성
common/runtime_svc.c 80-155줄이다.
80 return 0;
81}
82
83/*******************************************************************************
84 * This function calls the initialisation routine in the descriptor exported by
85 * a runtime service. Once a descriptor has been validated, its start & end
86 * owning entity numbers and the call type are combined to form a unique oen.
87 * The unique oen is used as an index into the 'rt_svc_descs_indices' array.
88 * The index of the runtime service descriptor is stored at this index.
89 ******************************************************************************/
90void __init runtime_svc_init(void)
91{
92 int rc = 0;
93 uint8_t index, start_idx, end_idx;
94 rt_svc_desc_t *rt_svc_descs;
95
96 /* Assert the number of descriptors detected are less than maximum indices */
97 assert((RT_SVC_DESCS_END >= RT_SVC_DESCS_START) &&
98 (RT_SVC_DECS_NUM < MAX_RT_SVCS));
99
100 /* If no runtime services are implemented then simply bail out */
101 if (RT_SVC_DECS_NUM == 0U) {
102 return;
103 }
104 /* Initialise internal variables to invalid state */
105 (void)memset(rt_svc_descs_indices, -1, sizeof(rt_svc_descs_indices));
106
107 rt_svc_descs = (rt_svc_desc_t *) RT_SVC_DESCS_START;
108 for (index = 0U; index < RT_SVC_DECS_NUM; index++) {
109 rt_svc_desc_t *service = &rt_svc_descs[index];
110
111 /*
112 * An invalid descriptor is an error condition since it is
113 * difficult to predict the system behaviour in the absence
114 * of this service.
115 */
116 rc = validate_rt_svc_desc(service);
117 if (rc != 0) {
118 ERROR("Invalid runtime service descriptor %p\n",
119 (void *) service);
120 panic();
121 }
122
123 /*
124 * The runtime service may have separate rt_svc_desc_t
125 * for its fast smc and yielding smc. Since the service itself
126 * need to be initialized only once, only one of them will have
127 * an initialisation routine defined. Call the initialisation
128 * routine for this runtime service, if it is defined.
129 */
130 if (service->init != NULL) {
131 rc = service->init();
132 if (rc != 0) {
133 ERROR("Error initializing runtime service %s\n",
134 service->name);
135 continue;
136 }
137 }
138
139 /*
140 * Fill the indices corresponding to the start and end
141 * owning entity numbers with the index of the
142 * descriptor which will handle the SMCs for this owning
143 * entity range.
144 */
145 start_idx = (uint8_t)get_unique_oen(service->start_oen,
146 service->call_type);
147 end_idx = (uint8_t)get_unique_oen(service->end_oen,
148 service->call_type);
149 assert(start_idx <= end_idx);
150 assert(end_idx < MAX_RT_SVCS);
151 for (; start_idx <= end_idx; start_idx++) {
152 rt_svc_descs_indices[start_idx] = index;
153 }
154 }
155}
02. OEN 범위와 handler를 보존하는 runtime service descriptor
include/common/runtime_svc.h 51-113줄이다.
51 * for future use
52 */
53typedef uintptr_t (*rt_svc_handle_t)(uint32_t smc_fid,
54 u_register_t x1,
55 u_register_t x2,
56 u_register_t x3,
57 u_register_t x4,
58 void *cookie,
59 void *handle,
60 u_register_t flags);
61typedef struct rt_svc_desc {
62 uint8_t start_oen;
63 uint8_t end_oen;
64 uint8_t call_type;
65 const char *name;
66 rt_svc_init_t init;
67 rt_svc_handle_t handle;
68} rt_svc_desc_t;
69
70/*
71 * Convenience macros to declare a service descriptor
72 */
73#define DECLARE_RT_SVC(_name, _start, _end, _type, _setup, _smch) \
74 static const rt_svc_desc_t __svc_desc_ ## _name \
75 __section(".rt_svc_descs") __used = { \
76 .start_oen = (_start), \
77 .end_oen = (_end), \
78 .call_type = (_type), \
79 .name = #_name, \
80 .init = (_setup), \
81 .handle = (_smch) \
82 }
83
84/*
85 * Compile time assertions related to the 'rt_svc_desc' structure to:
86 * 1. ensure that the assembler and the compiler view of the size
87 * of the structure are the same.
88 * 2. ensure that the assembler and the compiler see the initialisation
89 * routine at the same offset.
90 * 3. ensure that the assembler and the compiler see the handler
91 * routine at the same offset.
92 */
93CASSERT((sizeof(rt_svc_desc_t) == SIZEOF_RT_SVC_DESC),
94 assert_sizeof_rt_svc_desc_mismatch);
95CASSERT(RT_SVC_DESC_INIT == __builtin_offsetof(rt_svc_desc_t, init),
96 assert_rt_svc_desc_init_offset_mismatch);
97CASSERT(RT_SVC_DESC_HANDLE == __builtin_offsetof(rt_svc_desc_t, handle),
98 assert_rt_svc_desc_handle_offset_mismatch);
99
100
101/*
102 * This function combines the call type and the owning entity number
103 * corresponding to a runtime service to generate a unique owning entity number.
104 * This unique oen is used to access an entry in the 'rt_svc_descs_indices'
105 * array. The entry contains the index of the service descriptor in the
106 * 'rt_svc_descs' array.
107 */
108static inline uint32_t get_unique_oen(uint32_t oen, uint32_t call_type)
109{
110 return ((call_type & FUNCID_TYPE_MASK) << FUNCID_OEN_WIDTH) |
111 (oen & FUNCID_OEN_MASK);
112}
113
DETAILS
내부 동작을 더 깊게 읽기
진입 조건을 먼저 고정한다
SMC exception에서 들어온 실행은 EL3 synchronous exception context에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.
SMC function ID의 owner number, call type, 32/64-bit convention을 분리해서 본다. descriptor 초기화 실패가 runtime table에 어떤 빈칸을 남기는지도 확인한다.
중심 객체의 생성과 공개를 나눈다
이 글의 중심 객체는 rt_svc_desc_t / SMC function ID다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.
빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.
주소, 크기와 정렬을 계산한다
부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.
성공 flag와 실제 완료 시점을 맞춘다
decode owner/type → descriptor index → service handler 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.
다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.
제어권을 넘기기 전에 확인할 조건을 정리한다
정상 경로는 SMC return에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.
호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.
IMPLEMENTATION NOTES
구현을 읽을 때 놓치기 쉬운 부분
SMC exception에서 SMC return까지 제어권이 이동하는 조건
OEN 범위와 fast/yielding call type으로 runtime service descriptor를 찾고 handler에 x1-x4와 handle을 전달하는 코드를 읽습니다. 이 경로는 함수 호출 목록만 외워서는 연결되지 않는다. SMC exception → decode owner/type → descriptor index → service handler → SMC return 순서에서 각 단계가 읽는 입력, 새로 확정하는 상태, 다음 단계에 넘기는 값을 구분해야 한다. 특히 EL3 synchronous exception context에서는 이전 단계가 남긴 register와 memory attribute가 C 코드의 전제 조건이 된다.
SMC function ID의 owner number, call type, 32/64-bit convention을 분리해서 본다. descriptor 초기화 실패가 runtime table에 어떤 빈칸을 남기는지도 확인한다. 따라서 첫 지점에서 rt_svc_desc_t / SMC function ID의 주소와 owner를 기록하고, 마지막 지점에서 같은 값이 그대로 유지되는지 아니면 새 객체로 교체되는지를 확인한다. 중간 함수가 성공을 반환해도 한 SMC ID는 정확히 하나의 유효 descriptor로 dispatch되고 handler는 caller security state와 register width 계약을 위반하지 않아야 한다.
rt_svc_desc_t와 context handle의 생성 시점과 수명
이 글에서 함께 나타나는 객체는 rt_svc_desc_t, runtime_svc_descs_indices, SMCCC registers, context handle이다. 이름이 비슷해도 저장 위치와 수명은 다르다. build-time descriptor인지, boot 단계의 임시 객체인지, world switch 뒤에도 남는 runtime 객체인지 나눠야 pointer를 따라가다 다른 단계의 구조체를 같은 것으로 오해하지 않는다.
rt_svc_desc_t / SMC function ID을 기준으로 allocation 또는 정적 배치 위치, list/table에 공개되는 시점, 참조가 끊기는 시점을 적는다. 그 다음 source와 destination 범위, per-CPU 여부, secure/non-secure 접근 권한을 map과 runtime log로 대조한다. 이 절차를 거치면 단순한 호출 순서가 아니라 실제 소유권 이동이 보인다.
성공 로그만으로 놓치기 쉬운 오류
대표적인 실패 조건은 OEN range overlap: 잘못된 handler; 32/64-bit 인자 혼동: pointer truncation; init 실패 무시: NULL service 호출이다. 이 문제들은 대개 fault가 발생한 함수보다 앞에서 만들어진 잘못된 주소, size, security state 또는 refcount 때문에 생긴다. 마지막 출력만 보지 말고 각 경계 직전의 상태를 한 줄씩 남겨 최초 불일치 지점을 찾는다.
재현에는 등록 descriptor와 index table 출력; unknown SMC ID 반환값 확인; 32-bit caller에서 64-bit pointer 전달 거부 확인를 사용한다. 정상 경로와 실패 경로에서 같은 필드를 같은 위치에 출력하고, 실패가 검증 단계에서 차단되는지 아니면 다음 context까지 전파되는지 비교한다. firmware와 secure world에서는 실패 뒤의 cleanup 또는 reset 경로도 정상 경로만큼 중요하다.
DEEP ANALYSIS
레지스터에서 오류 판정까지 상세 분석
TF-A runtime service dispatch는 거대한 switch 문이 아니라 linker section에 등록된 rt_svc_desc_t와 compact index table을 사용한다. SMC function ID에서 call type, 32/64-bit convention, Owning Entity Number를 분리한 뒤 해당 descriptor handler를 호출한다.
SMCCC register ABI와 TF-A 내부 context handle을 구분해야 한다. x0은 function ID이면서 return code가 될 수 있고 x1-x4는 argument지만 handler가 pointer로 해석하기 전에 caller security state, width, shared-memory 정책을 검증해야 한다.
bit31 call type, bit30 width, bits29:24 OEN, function number를 포함한다.
32-bit caller의 상위 bit와 pointer 접근 권한을 규칙대로 처리한다.
caller security state와 execution width 정보를 보존한다.
현재 CPU의 gp_regs와 복귀 시 복원할 실행 상태를 가리킨다.
해당 OEN/call-type 조합에 유효한 descriptor 또는 invalid marker다.
각 계약은 앞 단계가 생산하고 현재 단계가 검증한 뒤 다음 소비자에게 넘기는 상태다. 한 항목이라도 확인되지 않으면 뒤 단계의 fault를 그 지점의 문제로 단정하지 않는다.
진입 레지스터와 메모리 계약
함수 첫 줄에 도달했을 때 이미 참이라고 가정하는 값과, 그 값이 틀렸을 때 영향을 받는 범위를 함께 적었다.
| # | 입력 상태 | 생산자 | 정상 조건 | 확인 이유 |
|---|---|---|---|---|
| 01 | x0 / smc_fid | SMC caller | bit31 call type, bit30 width, bits29:24 OEN, function number를 포함한다. | descriptor index와 handler 내부 command 선택을 결정한다. |
| 02 | x1-x4 | caller ABI | 32-bit caller의 상위 bit와 pointer 접근 권한을 규칙대로 처리한다. | service-specific 입력이며 EL3가 무조건 신뢰하면 안 된다. |
| 03 | flags | EL3 exception framework | caller security state와 execution width 정보를 보존한다. | secure-only/non-secure-only service 접근 제어에 쓰인다. |
| 04 | handle | exception frame | 현재 CPU의 gp_regs와 복귀 시 복원할 실행 상태를 가리킨다. | SMC_RET 매크로가 값을 기록하는 대상이다. |
| 05 | descriptor index | runtime_svc_init | 해당 OEN/call-type 조합에 유효한 descriptor 또는 invalid marker다. | runtime lookup을 일정 시간에 끝내게 한다. |
핵심 구조체 필드의 생산자, 소비자와 수명
구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.
| # | 객체 또는 필드 | 생산자 | 소비자 | 수명과 불변 조건 |
|---|---|---|---|---|
| 01 | rt_svc_desc_t.start_oen/end_oen | DECLARE_RT_SVC macro | runtime_svc_init | build image 수명 동안 불변이며 range overlap이 없어야 한다. |
| 02 | rt_svc_desc_t.call_type | service declaration | index builder/dispatch | fast와 yielding call table을 분리한다. |
| 03 | rt_svc_desc_t.init | service module | runtime_svc_init | BL33 진입 전 한 번 호출되고 성공한 service만 공개돼야 한다. |
| 04 | rt_svc_desc_t.handle | service module | handle_runtime_svc | EL3 resident code에 있어야 하며 init section을 가리키면 안 된다. |
| 05 | runtime_svc_descs_indices | runtime_svc_init | SMC hot path | OEN/call-type key를 descriptor index로 변환하는 resident read-only table이다. |
| 06 | SMC context frame | EL3 vector | handler/SMC return | 한 호출 동안 유효하며 suspend되는 yielding service는 별도 state가 필요하다. |
함수 내부 실행 순서
소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.
- 01
EL3 synchronous vector가 SMC exception을 분류하고 x0-x7과 return state를 context frame에 저장한다.
- 02
handle_runtime_svc가 x0에서 SMC type, calling convention, OEN을 추출한다.
- 03
OEN과 call type으로 index table을 조회하고 invalid marker면 SMCCC unknown을 반환한다.
- 04
descriptor range와 handler pointer가 유효한지 assert 또는 defensive check를 수행한다.
- 05
caller flags와 x1-x4, context handle을 선택된 service handler에 전달한다.
- 06
handler가 function number와 security state를 다시 검증하고 service-specific object를 찾는다.
- 07
반환 code와 추가 register를 context frame에 기록하며 pointer-width와 sign extension을 맞춘다.
- 08
target context를 준비하고 EL3 exit path가 x0-x3를 복원한다.
- 09
ERET 뒤 caller가 SMCCC return code를 해석하며 unknown, denied, invalid parameter를 구분한다.
빌드 설정이 바꾸는 실제 코드 경로
동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.
| # | 설정 | 바뀌는 동작 | 확인 방법 |
|---|---|---|---|
| 01 | service DECLARE_RT_SVC | OEN range, fast/yielding type, init, handler를 등록한다. | map의 rt_svc_descs section과 descriptor 수를 확인한다. |
| 02 | SMCCC_MAJOR/MINOR support | accepted function ID와 feature query 결과가 달라진다. | SMCCC_VERSION/ARCH_FEATURES 응답을 target에서 확인한다. |
| 03 | SPD/SPMD/PSCI service inclusion | 등록되는 OEN 범위가 build마다 달라진다. | descriptor table을 dump해 실제 handler 소유권을 기록한다. |
| 04 | SVE/SME hint handling | function ID hint bit와 context policy가 추가될 수 있다. | masking 뒤 원래 function number가 유지되는지 확인한다. |
증상에서 최초 불일치 지점까지 추적하기
마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.
| # | 관찰 증상 | 중단 위치 | 기록할 값 | 판정 |
|---|---|---|---|---|
| 01 | 모든 SMC가 UNKNOWN | handle_runtime_svc index lookup | smc_fid decode, index value, descriptor count | service가 build에 없거나 init 실패로 등록되지 않았는지 확인한다. |
| 02 | 32-bit client에서만 pointer 오류 | handler entry | call convention bit, x1/x2 상위 bit | reg_pair 조합 또는 pointer truncation 문제를 찾는다. |
| 03 | 다른 service handler가 호출됨 | runtime_svc_init table build | OEN range와 call_type overlap | descriptor 선언 범위 중복을 판정한다. |
| 04 | SMC 후 원래 world가 아닌 곳으로 복귀 | handler return과 cm_prepare_el3_exit | flags, handle, active context | dispatch 결과보다 context handle 오용을 먼저 본다. |
OBJECT LIFETIME
객체와 수명
| 대상 | 만들어지는 시점 | 유효 범위 | 확인할 조건 |
|---|---|---|---|
rt_svc_desc_t / SMC function ID | decode owner/type | SMC return 또는 오류 정리 완료까지 | 진입 전제와 상태 계약 |
| 입력 buffer / metadata | SMC exception | parse와 검증이 끝날 때까지 | 길이, 정렬, 소유권, 변조 가능성 |
| 등록된 list / descriptor | descriptor index | 하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지 | 중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리 |
| hardware 또는 persistent state | 실제 write/probe가 완료된 뒤 | reset 또는 명시적 해제·갱신까지 | 쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원 |
최종 부트로더 이미지 | link/image 생성 시점 | 다음 stage가 새 image로 교체할 때까지 | 적재 주소, 진입점, 섹션, 헤더의 일치 여부 |
FAILURE PATH
실패 지점과 증상
| # | 조건 | 관찰되는 증상 | 먼저 볼 단계 |
|---|---|---|---|
| 01 | OEN range overlap | 잘못된 handler | decode owner/type |
| 02 | 32/64-bit 인자 혼동 | pointer truncation | descriptor index |
| 03 | init 실패 무시 | NULL service 호출 | service handler |
로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.
EVIDENCE
소스 밖에서 확인할 증거
소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.
| # | 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|---|
| 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 'uintptr_t handle_runtime_svc' | 대상 함수가 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
직접 확인할 실험
- 01등록 descriptor와 index table 출력
decode owner/type진입 전후에 rt_svc_desc_t의 주소·크기·반환값과 timestamp를 함께 남긴다. - 02unknown SMC ID 반환값 확인
descriptor index진입 전후에 runtime_svc_descs_indices의 주소·크기·반환값과 timestamp를 함께 남긴다. - 0332-bit caller에서 64-bit pointer 전달 거부 확인
service handler진입 전후에 SMCCC registers의 주소·크기·반환값과 timestamp를 함께 남긴다.
PRIMARY REFERENCES