QUESTION
boot 명령의 image를 어느 시점에 신뢰하고 제어권을 넘기는가?
이 글의 lkboot는 classic Android aboot와 별개다. server는 TCP(WITH_LIB_MINIP 조건) 또는 DCC에서 MSG_CMD를 받고, boot:<len>:를 do_boot()로 보낸다. do_flash_boot()는 유한한 autoboot 설정에서 server가 반환한 뒤 system partition을 시도하는 다른 경로다. 타임아웃뿐 아니라 listen 초기 오류로 server가 반환해도 이 조건을 통과할 수 있다.
do_boot()는 받은 길이로 uncached contiguous buffer를 할당하고 lkb_read()로 읽는다. bootimage_open()은 첫 page와 file section의 범위·SHA-256 검사를 시도하고 성공하면 structured image 경로로 간다. 실패하면 hash를 검사하지 않는 raw buffer를 그대로 entry로 삼는다. 따라서 이 코드는 모든 boot image를 검증한 뒤 실행한다는 계약이 아니다.
명령·handoff 구현과 structured parser를 아래 그림·표의 근거로 함께 읽는다.
STRUCTURE
명령 세션, image buffer, 실행 포인터
boot 명령이 만든 상태와 제어권 경계lkb_t session·lenbuflk_args[4]ptr → boot thread → arch_chain_loadptr는 성공한 structured image의 TYPE_LK section 또는 raw buf다. structured image에 TYPE_LK가 없으면 미초기화 위험이 남는다.
구조 블록은 주소 순서가 아니다. 이 경로에는 보편적인 destination 재배치나 device quiesce 단계가 보이지 않는다.
CALL PATH
boot 명령의 호출 순서
MSG_CMD·길이 파싱do_boot() alloc·lkb_read()bootimage_open() 또는 raw bufdo_boot()는 thread를 재개하고 0을 반환한다. protocol의 lkb_okay()는 그 반환을 보고 전송된다. 실제 arch_chain_load()는 별도 thread의 thread_sleep(250) 뒤에 실행된다. 응답을 다음 image 진입 완료로 읽으면 안 된다.
STATE LEDGER
확인된 상태와 아직 보장되지 않은 상태
표는 고정 source의 실제 분기를 기술한다. 좁은 화면에서는 좌우로 밀어 각 조건을 확인할 수 있다.
| # | 함수와 조건 | 그 시점에 알 수 있는 것 | 다음 결과 |
|---|---|---|---|
| 01 | lkboot_process_command() | MSG_CMD, header 길이 ≤ 127, cmd:len:arg 파싱 | lkb_handle_command()가 boot 분기 선택 |
| 02 | vmm_alloc_contiguous(len) → lkb_read(len) | uncached buffer 확보와 요청한 byte 수 수신; read 오류 시 io error | 성공 시 boot args 구성; read 실패의 buffer free는 TODO |
| 03 | bootargs_start() → args cache clean → bootargs_generate_lk_arg_values() | 고정 코드의 Zynq 경로에서 SRAM args page와 4개 LK 인자 생성 | lk_args[4]를 cl_args에 복사; 이후 args 수정 가능 |
| 04 | bootimage_open(buf,len) 성공 | first page 형식·SHA와 image 안 file section 범위·SHA 확인 | TYPE_LK 발견 시 cache clean 뒤 bootargs_add_bootimage_pointer(); 추가 clean 없음. 부재 시 ptr 미초기화 위험 |
| 05 | bootimage_open() 실패 | raw fallback; SHA 검증 성공 상태가 아님 | ptr = buf로 직접 실행 대상으로 사용 |
| 06 | boot thread 재개 → 250 ms sleep | do_boot() 반환 뒤 protocol OKAY 가능 | thread에서 arch_chain_load(ptr,lk_args[0..3]) |
structured image의 파일 범위 검사는 destination·entry 권한 검사와 다르다. 또한 parser의 entry_count 순회에는 table 크기에 대한 별도 상한 검사가 없고, image size 검사는 입력 길이를 넘는지만 확인한다. 개별 file의 끝 주소 검사와 모든 metadata 접근의 안전성을 같은 보장으로 읽지 않는다. hash 실패까지 raw fallback으로 넘어갈 수 있으므로 제품 보안 정책은 이 코드 밖에서 따로 마련·검증해야 한다.
VISUAL WALKTHROUGH
단일 직선이 아닌 두 image 경로
화살표는 do_boot()에서 실행되는 순서이고, 두 분기는 bootimage_open()의 반환값으로 갈린다. RAM의 상대 주소나 cache/device 종료를 가정하지 않는다.
do_boot()에서 실제로 일어나는 일lkb_read() 성공 뒤 args를 만들고 image를 판별한다.
lkb_read(buf,len)bootimage_open() 성공/실패 분기ptr 지정·boot thread 재개arch_chain_load()같은 buf를 쓰지만 entry를 고르는 규칙과 검사 범위가 다르다.
bootimage_open() 성공
형식첫 entry의 4096-byte file 조건, version·image size 검사
검증첫 page와 file section 범위·SHA-256 확인
entryTYPE_LK를 찾으면 buf + offset
틈TYPE_LK 부재를 처리하지 않아 ptr 미초기화 위험
bootimage_open() 실패 → raw
형식실패 이유와 무관하게 raw branch로 이동
검증raw image 자체에 SHA·entry 검사가 없음
entryptr = buf로 시작 주소 선택
분리flash autoboot는 do_flash_boot()의 별도 경로
UPSTREAM SOURCE
원본 코드
아래 코드는 LK upstream 1eb9917의 app/lkboot/lkboot.c에서 263-337줄을 그대로 가져온 것이다.
263 printf("lkboot: handled command, staying in server loop\n");
264 }
265
266 /* see if we need to drop out and try to direct boot */
267 if (timeout != INFINITE_TIME && (current_time() - t >= timeout)) {
268 break;
269 }
270 }
271
272#if WITH_LIB_MINIP
273 tcp_close(listen_socket);
274#endif
275
276 printf("lkboot: server timed out\n");
277
278 return ERR_TIMED_OUT;
279}
280
281/* platform code can override this to conditionally abort autobooting from flash */
282bool platform_abort_autoboot(void);
283__WEAK bool platform_abort_autoboot(void) {
284 return false;
285}
286
287static void lkboot_task(const struct app_descriptor *app, void *args) {
288 /* read a few sysparams to decide if we're going to autoboot */
289 uint8_t autoboot = 1;
290 sysparam_read("lkboot.autoboot", &autoboot, sizeof(autoboot));
291
292 /* let platform code have a shot at disabling the autoboot behavior */
293 if (platform_abort_autoboot())
294 autoboot = 0;
295
296#if !LKBOOT_AUTOBOOT
297 autoboot = 0;
298#endif
299
300 /* if we're going to autoobot, read the timeout value */
301 lk_time_t autoboot_timeout;
302 if (!autoboot) {
303 autoboot_timeout = INFINITE_TIME;
304 } else {
305 autoboot_timeout = LKBOOT_AUTOBOOT_TIMEOUT;
306 sysparam_read("lkboot.autoboot_timeout", &autoboot_timeout, sizeof(autoboot_timeout));
307 }
308
309 TRACEF("autoboot %u autoboot_timeout %u\n", autoboot, (uint)autoboot_timeout);
310
311#if LKBOOT_WITH_SERVER
312 lkboot_server(autoboot_timeout);
313#else
314 if (autoboot_timeout != INFINITE_TIME) {
315 TRACEF("waiting for %u milliseconds before autobooting\n", (uint)autoboot_timeout);
316 thread_sleep(autoboot_timeout);
317 }
318#endif
319
320 if (autoboot_timeout != INFINITE_TIME) {
321 TRACEF("trying to boot from flash...\n");
322 status_t err = do_flash_boot();
323 TRACEF("do_flash_boot returns %d\n", err);
324 }
325
326#if LKBOOT_WITH_SERVER
327 TRACEF("restarting server\n");
328 lkboot_server(INFINITE_TIME);
329#endif
330
331 TRACEF("nothing to do, exiting\n");
332}
333
334APP_START(lkboot)
335.entry = lkboot_task,
336.flags = 0,
337APP_END
READING CONTRACT
발췌 범위와 읽기 기준
원문 263–337줄에는 server 반환 뒤 유한한 autoboot 설정이면 별도 flash boot를 시도하는 lkboot_task()가 있다. 기준 구문은 L287이며, 발췌 첫 줄을 함수 시작으로 읽지 않는다. network/DCC 명령의 do_boot()는 이 발췌에 없고 아래 고정 commands.c를 함께 봐야 한다.
lkboot_server()는 TCP(WITH_LIB_MINIP 조건)와 DCC를 검사한다. 명령 성공 여부와 무관하게 TCP 연결 또는 DCC session을 시도하면 handled_command가 true가 되어 server timeout을 무기한으로 바꾼다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
이 발췌는 protocol parsing과 TCP 수신 경계다. do_boot()의 buffer·bootimage 분기 및 bootimage_open()의 SHA 검사는 commands.c와 bootimage.c의 같은 commit에서 확인한다.
01. transport packet을 lkboot command로 해석하는 함수
app/lkboot/lkboot.c 169-251줄이다.
169 len -= lkb->avail;
170 lkb->avail = 0;
171 }
172 return 0;
173
174fail:
175 lkb->state = STATE_ERROR;
176 return -1;
177}
178
179status_t lkboot_process_command(lkb_t *lkb) {
180 msg_hdr_t hdr;
181 char cmd[128];
182 char *arg;
183 int err;
184 const char *result;
185 unsigned len;
186
187 if (lkb->read(lkb->cookie, &hdr, sizeof(hdr))) goto fail;
188 if (hdr.opcode != MSG_CMD) goto fail;
189 if (hdr.length > 127) goto fail;
190 if (lkb->read(lkb->cookie, cmd, hdr.length)) goto fail;
191 cmd[hdr.length] = 0;
192
193 TRACEF("recv '%s'\n", cmd);
194
195 if (!(arg = strchr(cmd, ':'))) goto fail;
196 *arg++ = 0;
197 len = atoul(arg);
198 if (!(arg = strchr(arg, ':'))) goto fail;
199 arg++;
200
201 err = lkb_handle_command(lkb, cmd, arg, len, &result);
202 if (err >= 0) {
203 lkb_okay(lkb);
204 } else {
205 lkb_fail(lkb, result);
206 }
207
208 TRACEF("command handled with success\n");
209 return NO_ERROR;
210
211fail:
212 TRACEF("command failed\n");
213 return ERR_IO;
214}
215
216static status_t lkboot_server(lk_time_t timeout) {
217 lkboot_dcc_init();
218
219#if WITH_LIB_MINIP
220 /* open the server's socket */
221 tcp_socket_t *listen_socket = NULL;
222 if (tcp_open_listen(&listen_socket, 1023) < 0) {
223 printf("lkboot: error opening listen socket\n");
224 return ERR_NO_MEMORY;
225 }
226#endif
227
228 /* run the main lkserver loop */
229 printf("lkboot: starting server\n");
230 lk_time_t t = current_time(); /* remember when we started */
231 for (;;) {
232 bool handled_command = false;
233
234 lkb_t *lkb;
235
236#if WITH_LIB_MINIP
237 /* wait for a new connection */
238 lk_time_t sock_timeout = 100;
239 tcp_socket_t *s;
240 if (tcp_accept_timeout(listen_socket, &s, sock_timeout) >= 0) {
241 DEBUG_ASSERT(s);
242
243 /* handle the command and close it */
244 lkb = lkboot_tcp_opened(s);
245 lkboot_process_command(lkb);
246 free(lkb);
247 tcp_close(s);
248 handled_command = true;
249 }
250#endif
251
DETAILS
함수 반환과 image 진입을 분리해서 읽기
수신 transport와 flash autoboot는 다르다
lkboot_server()는 TCP 또는 DCC session의 command를 처리한다. lkboot_task()는 server의 반환값을 검사하지 않고 원래 autoboot_timeout != INFINITE_TIME이면 do_flash_boot()를 시도한다. 정상 타임아웃 외에 TCP listen 초기 오류도 이 경로로 이어질 수 있다. server를 빼고 빌드하면 유한 timeout만큼 sleep한 뒤 같은 조건을 검사한다. 명령 성공 여부와 무관하게 TCP 연결 또는 DCC session을 시도하면 handled_command가 true가 되고 server timeout을 INFINITE_TIME으로 바꾼다.
읽기 실패 뒤 buffer 수명도 확인한다
do_boot()는 len으로 vmm_alloc_contiguous()를 호출하고 lkb_read()로 채운다. read가 실패하면 io error로 반환하지만 코드에 // XXX free buffer here가 남아 있어 이 경로에서 해제 완료를 주장할 수 없다.
args page의 cache 작업 순서를 확인한다
고정 코드의 PLATFORM_ZYNQ 분기는 SRAM의 마지막 page를 boot args로 잡고, command line을 채워 arch_clean_cache_range(args, PAGE_SIZE)를 호출한다. structured image 성공 시 그 뒤에 bootargs_add_bootimage_pointer()가 같은 args를 수정하지만 do_boot()에는 두 번째 clean이 없다. 다른 platform은 이 코드에 #error need better way가 있어 동일한 runtime 경로가 아니다.
structured 성공과 raw fallback을 구별한다
bootimage_open()은 첫 page의 구조·SHA, image size 및 file-section 범위·SHA를 살핀다. 성공 시 TYPE_LK section pointer를 구하고 bootimage pointer를 args에 더한다. 실패 시 ptr = buf로 raw entry를 정하므로 SHA 실패도 거부가 아니라 raw 시도로 이어질 수 있다.
OKAY와 제어권 이전은 같은 사건이 아니다
thread_resume(thread_create(...))에서 생성 결과의 NULL 검사를 하지 않는다. 이 호출을 지나 do_boot()가 0을 반환하면 protocol이 lkb_okay()를 호출하지만 그 송신 반환값도 확인하지 않는다. 따라서 생성 성공·응답 도착·image 진입은 각각 따로 검증해야 한다. 별도 boot thread가 250 ms 잠든 뒤 arch_chain_load()를 호출한다. 이 source 구간에 보편적인 image cache clean, device shutdown, destination copy는 없다.
IMPLEMENTATION NOTES
분기에서 놓치기 쉬운 실패 조건
TYPE_LK가 없어도 성공 branch에 남는다
bootimage_open()이 성공한 뒤 bootimage_get_file_section(TYPE_LK)이 실패하면 ptr를 설정하는 if body를 건너뛴다. 이후 cl_args.func = (void *)ptr를 실행하므로 미초기화 pointer 위험을 성공 처리로 가리지 않아야 한다.
SHA-256은 출처 인증이 아니다
parser가 image 내부 digest와 payload를 비교해도 서명·신뢰 anchor를 검증하는 코드가 아니다. 특히 parser 실패 뒤 raw branch를 실행하므로 모든 boot image의 무결성 보장이라고 적을 수 없다.
flash 경로를 command 경로에 합치지 않는다
do_flash_boot()는 유효 partition table의 system entry와 device memory map을 얻어 structured image를 열고 TYPE_LK를 찾는다. raw fallback은 없고 arch_chain_load()를 직접 부른다. TYPE_LK가 없으면 ptr는 section 주소로 바뀌지 않고 device memory-map 시작 주소에 남는다.
OBJECT LIFETIME
이 경로에서 실제 등장하는 객체
| 대상 | 생성·선택 | 소비자 | 검토할 수명·조건 |
|---|---|---|---|
lkb_t session | TCP/DCC connection | lkboot_process_command(), lkb_read() | server가 처리 후 session을 free; boot thread는 session pointer 대신 args를 받음 |
buf / buf_phys | vmm_alloc_contiguous(len) | parser 또는 raw entry | read 실패 경로 free TODO; thread 실행까지 buffer가 필요 |
args / lk_args[4] | Zynq SRAM page와 bootargs_generate_lk_arg_values() | arch_chain_load() | 초기 args cache clean 후 structured path의 bootimage pointer 추가; 두 번째 clean 없음 |
bootimage_t·TYPE_LK pointer | bootimage_open() 성공 시 | cl_args.func | section 부재 시 ptr 미초기화 위험; section pointer는 buf 내부 |
chainload_args | static cl_args에 entry·인자 저장 | 별도 boot thread | 250 ms 뒤 arch_chain_load(); 반복 boot command의 공유 static 저장소에도 주의 |
FAILURE PATH
실패 조건과 소스에 남은 위험
| # | 조건 | 고정 코드의 동작 | 먼저 볼 곳 |
|---|---|---|---|
| 01 | contiguous buffer 할당 실패 | not enough memory 반환 | do_boot() allocation |
| 02 | lkb_read() 실패 | io error 반환; buffer 해제 TODO | do_boot() read branch |
| 03 | structured format·SHA 검증 실패 | bootimage_open() 실패 → raw ptr = buf | parser 반환과 fallback |
| 04 | structured image에 TYPE_LK 없음 | ptr 설정 없이 thread args에 사용 가능 | section 탐색과 cl_args.func |
이 표는 코드의 관찰 결과다. 실제 제품에서 raw 실행 허용 여부나 부팅 image 인증은 별도 정책·구현에서 판단해야 한다.
EVIDENCE
그림을 다시 확인할 고정 소스 지점
다음 줄은 같은 commit의 호출과 분기를 직접 묶는다. 빌드·보드 재현 전에도 각 주장에 대응하는 조건을 확인할 수 있다.
| # | 질문 | 고정 소스 | 확인할 조건 |
|---|---|---|---|
| 01 | 명령과 응답 시점 | lkboot.c:179–213 | MSG_CMD 파싱, handler 반환 뒤 OKAY/FAIL |
| 02 | alloc·read·args | commands.c:79–121 | uncached buffer, read 오류 TODO, 초기 args cache clean |
| 03 | structured vs raw | commands.c:123–157 | TYPE_LK 성공 조건, raw ptr=buf, boot thread |
| 04 | 검증의 실제 범위 | bootimage.c:23–153 | first page·file section range/SHA 및 실패 반환 |
| 05 | 별도 flash autoboot | commands.c:159–252 | partition memory map·structured section·직접 chain load |
LAB
조건을 분리해 재현할 실험
- 01parser 입력 표본 대조
검증 가능한 시험 환경에서 정상 structured image, digest가 깨진 image, raw image를 각각 넣어
bootimage_open()반환과ptr선택을 구분해 기록한다. digest 실패가 raw fallback으로 이어지는지 확인한다. - 02
TYPE_LK누락 검토고정 소스에서 section 검색 실패 시
ptr에 쓰는 대입문이 없는지 확인한다. 장치에서 미초기화 entry를 실제 실행시키지 않고 코드·분석 도구로만 확인한다. - 03응답과 handoff 시간 분리
복구 가능한 시험 보드에서
lkb_okay(), boot thread의 250 ms sleep,arch_chain_load()계측 시각을 비교한다. OKAY를 실행 완료 신호로 기록하지 않는다.
PRIMARY REFERENCES