QUESTION
bootm image handler와 실행 단계 단계에서 실제로 바뀌는 상태는 무엇인가?
파일 열기, 형식 판별, 처리 함수 선택, 자원 예약, 정리 과정을 차례로 살펴본다. dry-run과 verbose 옵션이 실제 상태를 변경하는지도 확인한다.
선택한 처리 함수가 사용하는 image_data의 파일, 버퍼, 예약 자원은 제어권을 넘기거나 정리할 때까지 유효해야 한다. 코드를 따라가며 각 자원을 언제 확보하고 해제하는지 확인한다.
STRUCTURE
객체와 주소가 놓이는 구조
bootm_data / image_data / image_handler를 중심에 놓고 왼쪽의 입력이 어떤 검사를 거쳐 오른쪽 결과로 공개되는지 표시했다. 실제 디버깅에서는 각 블록의 주소와 크기를 로그에 대입한다.
CALL PATH
실행 흐름
화살표는 단순 호출 순서만 뜻하지 않는다. 각 단계가 성공을 반환할 때 다음 단계가 읽을 수 있는 상태가 무엇인지 함께 확인한다. 오류 반환이 발생하면 바로 다음 화살표로 진행하지 않고 해당 단계의 정리 경로를 따라간다.
STATE LEDGER
단계별 입력과 출력
각 단계의 입력과 처리 후 바뀌는 상태를 정리한 표다. 사용 중인 소스 버전에서 다른 필드를 변경한다면 그에 맞춰 표도 수정한다.
| # | 단계 | 진입 시 신뢰할 상태 | 성공 뒤 남아야 할 상태 | 다음 소비자 |
|---|---|---|---|---|
| 01 | boot command/entry | 부트 CPU의 동기 실행 문맥 | bootm_data | bootm_data |
| 02 | bootm_data | boot command/entry 완료 상태 | image_data | filetype detect |
| 03 | filetype detect | bootm_data 완료 상태 | handler registry | image handler |
| 04 | image handler | filetype detect 완료 상태 | loaded resources | OS handoff |
| 05 | OS handoff | image handler 완료 상태 | loaded resources | 이 단계의 처리 결과를 사용하는 코드 |
분석 범위의 전제와 비교해, 다음 단계에 잘못된 입력을 넘긴 부분부터 조사한다.
VISUAL WALKTHROUGH
주소와 객체의 이동을 그림으로 읽기
아래 그림은 주소, 객체를 사용하는 기간, 제어권을 넘기는 시점을 중심으로 정리했다. 실제 주소와 크기는 사용 중인 보드의 bdinfo, 맵 파일과 링커 심벌로 확인한다.
크기는 개념 비율이다. 실제 분석에서는 map, symbol과 runtime 출력의 시작·끝 주소를 대입한다.
호출 이름만 나열하지 않고, 각 단계가 다음 단계에 넘기는 상태를 기준으로 실행 순서를 표시한다.
UPSTREAM SOURCE
원본 코드
아래 코드는 Barebox v2026.06.1의 common/bootm.c에서 796-884줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.
796 if (data->initrd_res)
797 of_del_reserve_entry(data->initrd_res->start, data->initrd_res->end);
798 release_sdram_region(data->initrd_res);
799 release_sdram_region(data->oftree_res);
800 release_sdram_region(data->tee_res);
801 loadable_release(&data->oftree);
802 loadable_release(&data->initrd);
803 loadable_release(&data->os);
804 loadable_release(&data->tee);
805 if (data->of_root_node)
806 of_delete_node(data->of_root_node);
807
808 globalvar_remove(LINUX_BOOTARGS_BOOTM_LATE "*");
809 free(data->os_header);
810 free(data->os_file);
811 free(data->oftree_file);
812 free(data->initrd_file);
813 free(data->tee_file);
814 free(data);
815}
816
817/*
818 * bootm_boot - Boot an application image described by bootm_data
819 */
820int bootm_boot(const struct bootm_data *bootm_data)
821{
822 struct image_data *data;
823 int ret;
824
825 data = bootm_boot_prep(bootm_data);
826 if (IS_ERR(data))
827 return PTR_ERR(data);
828
829 ret = bootm_boot_handler(data);
830
831 bootm_boot_cleanup(data);
832 return ret;
833}
834
835bool bootm_efi_check_image(struct image_handler *handler,
836 struct image_data *data,
837 enum filetype detected_filetype)
838{
839 /* This is our default: Use EFI when support is compiled in,
840 * and fallback to normal boot otherwise.
841 */
842 if (data->efi_boot == BOOTM_EFI_AVAILABLE) {
843 if (IS_ENABLED(CONFIG_EFI_LOADER) || efi_is_payload())
844 data->efi_boot = BOOTM_EFI_REQUIRED;
845 else
846 data->efi_boot = BOOTM_EFI_DISABLED;
847 }
848
849 /* If EFI is disabled, we assume EFI-stubbed images are
850 * just normal non-EFI stubbed ones
851 */
852 if (data->efi_boot == BOOTM_EFI_DISABLED)
853 return handler->filetype == filetype_no_efistub(detected_filetype);
854
855 /* If EFI is required, we enforce handlers to match exactly */
856 return detected_filetype == handler->filetype;
857}
858
859int linux_rootwait_secs = 10;
860
861static const char * const bootm_efi_loader_mode_names[] = {
862 [BOOTM_EFI_DISABLED] = "disabled",
863 [BOOTM_EFI_AVAILABLE] = "available",
864 [BOOTM_EFI_REQUIRED] = "required",
865};
866
867static int bootm_init(void)
868{
869 globalvar_add_simple("bootm.image", NULL);
870 globalvar_add_simple("bootm.image.loadaddr", NULL);
871 globalvar_add_simple("bootm.oftree", NULL);
872 globalvar_add_simple("bootm.root_dev", NULL);
873 globalvar_add_simple("bootm.root_param", "root");
874 globalvar_add_simple("bootm.tee", NULL);
875 globalvar_add_simple_bool("bootm.appendroot", &bootm_appendroot);
876 globalvar_add_simple_bool("bootm.earlycon", &bootm_earlycon);
877 globalvar_add_simple_bool("bootm.provide_machine_id", &bootm_provide_machine_id);
878 globalvar_add_simple_bool("bootm.provide_hostname", &bootm_provide_hostname);
879 if (IS_ENABLED(CONFIG_SECURITY_POLICY))
880 globalvar_add_simple_bool("bootm.provide_policy", &bootm_provide_policy);
881 if (IS_ENABLED(CONFIG_BOOTM_INITRD)) {
882 globalvar_add_simple("bootm.initrd", NULL);
883 globalvar_add_simple("bootm.initrd.loadaddr", NULL);
884 }
READING CONTRACT
발췌 범위와 읽기 기준
원문 796-884줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int bootm_boot(const struct bootm_data *bootm_data)은 L820에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.
파일 열기, 형식 판별, 처리 함수 선택, 자원 예약, 정리 과정을 차례로 살펴본다. dry-run과 verbose 옵션이 실제 상태를 변경하는지도 확인한다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. image file을 열고 handler 실행 전 상태를 준비
common/bootm.c 521-635줄이다.
521 /* Detect actual image type from decompressed content */
522 data->kernel_type = file_detect_boot_image_type(header, ret);
523
524 /* Replace the os_header with the decompressed header */
525 free(data->os_header);
526 data->os_header = header;
527
528 return 0;
529}
530
531struct image_data *bootm_boot_prep(const struct bootm_data *bootm_data)
532{
533 struct image_data *data;
534 int ret;
535 const char *image_type_str;
536
537 if (!bootm_data->os_file) {
538 pr_err("no image given\n");
539 return ERR_PTR(-ENOENT);
540 }
541
542 data = xzalloc(sizeof(*data));
543
544 bootm_image_name_and_part(bootm_data->os_file, &data->os_file, &data->os_part);
545 bootm_image_name_and_part(bootm_data->oftree_file, &data->oftree_file, &data->oftree_part);
546 bootm_image_name_and_part(bootm_data->initrd_file, &data->initrd_file, &data->initrd_part);
547 if (bootm_data->tee_file)
548 data->tee_file = xstrdup(bootm_data->tee_file);
549 data->verbose = bootm_data->verbose;
550 data->verify = bootm_data->verify;
551 data->force = bootm_data->force;
552 data->dryrun = bootm_data->dryrun;
553 data->initrd_address = bootm_data->initrd_address;
554 data->os_address = data->os_address_hint = bootm_data->os_address;
555 data->os_entry = data->os_entry_hint = bootm_data->os_entry;
556 data->efi_boot = bootm_data->efi_boot;
557
558 ret = file_read_and_detect_boot_image_type(data->os_file, &data->os_header);
559 if (ret < 0)
560 goto err_out;
561 data->image_type = ret;
562
563 if (!data->force && data->image_type == filetype_unknown) {
564 pr_err("Unknown OS filetype (try -f)\n");
565 ret = -EINVAL;
566 goto err_out;
567 }
568
569 if (bootm_signed_images_are_forced()) {
570 data->verify = BOOTM_VERIFY_SIGNATURE;
571
572 /*
573 * When we only allow booting signed images make sure everything
574 * we boot is in the OS image and not given separately.
575 */
576 data->oftree_file = NULL;
577 data->initrd_file = NULL;
578 data->tee_file = NULL;
579 if (data->image_type != filetype_fit) {
580 pr_err("Signed boot and image is no FIT image, aborting\n");
581 ret = -EINVAL;
582 goto err_out;
583 }
584 }
585
586 image_type_str = file_type_to_short_string(data->image_type);
587
588 /* May be updated by below container-specific handlers */
589 data->kernel_type = data->image_type;
590
591 switch (data->image_type) {
592 case filetype_fit:
593 ret = bootm_open_fit(data, false);
594 break;
595 case filetype_uimage:
596 ret = bootm_open_uimage(data);
597 break;
598 case filetype_gzip:
599 case filetype_bzip2:
600 case filetype_lzo_compressed:
601 case filetype_lz4_compressed:
602 case filetype_xz_compressed:
603 case filetype_zstd_compressed:
604 ret = bootm_open_files(data);
605 if (!ret)
606 ret = bootm_open_os_compressed(data);
607 image_type_str = "compressed boot";
608 break;
609 default:
610 ret = bootm_open_files(data);
611 image_type_str = "boot";
612 break;
613 }
614
615 if (ret) {
616 pr_err("Loading %s image failed with: %pe\n", image_type_str, ERR_PTR(ret));
617 goto err_out;
618 }
619
620 if (IS_ENABLED(CONFIG_BOOTM_UIMAGE)) {
621 ret = bootm_collect_uimage_loadables(data);
622 if (ret)
623 goto err_out;
624 }
625
626 if (bootm_data->appendroot) {
627 const char *root = NULL;
628 const char *rootopts = NULL;
629
630 if (bootm_data->root_dev) {
631 const char *root_dev_name = devpath_to_name(bootm_data->root_dev);
632 struct cdev *root_cdev = cdev_open_by_name(root_dev_name, O_RDONLY);
633
634 ret = cdev_get_linux_root_and_opts(root_cdev, &root, &rootopts);
635
DETAILS
내부 동작을 더 깊게 읽기
진입 조건을 먼저 고정한다
boot command/entry에서 들어온 실행은 부트 CPU의 동기 실행 문맥에 놓여 있다. 이때 interrupt, MMU/cache, stack, heap 중 무엇이 이미 준비되었는지 소스의 호출자까지 올라가 확인한다. 같은 함수라도 SPL, relocation 전후, app thread처럼 호출 문맥이 달라지면 허용되는 API와 지연 시간이 달라진다.
파일 열기, 형식 판별, 처리 함수 선택, 자원 예약, 정리 과정을 차례로 살펴본다. dry-run과 verbose 옵션이 실제 상태를 변경하는지도 확인한다.
중심 객체의 생성과 공개를 나눈다
이 글의 중심 객체는 bootm_data / image_data / image_handler다. 메모리를 확보한 시점, 필드를 채운 시점, 전역 list나 다른 subsystem에 공개한 시점을 구분한다. 공개 뒤 오류가 발생한다면 목록에서 제거하고 child, buffer, reference를 역순으로 정리하는지 확인한다.
빌드 산출물 관점에서는 최종 부트로더 이미지 안에 해당 symbol과 section이 실제로 포함되었는지도 map과 objdump로 검증한다.
주소, 크기와 정렬을 계산한다
부트 코드에서는 주소 계산 오류를 주의해야 한다. 원본과 목적지의 주소 범위, 헤더에 기록된 데이터 크기, 블록·페이지 단위를 표로 정리하고 각 구간의 끝 주소를 계산한다. 끝 주소가 start + size - 1처럼 마지막 바이트를 가리키는지, 구간 바로 다음 주소를 가리키는지는 API 규약에서 확인한다.
성공 flag와 실제 완료 시점을 맞춘다
bootm_data → filetype detect → image handler 구간에서는 부분 초기화 상태가 생길 수 있다. flag, list insertion, callback 등록, storage write 완료 중 무엇이 성공의 기준인지 찾는다. hardware write나 DMA가 포함되면 함수 반환과 장치 완료가 같은 시점인지도 확인한다.
다른 CPU, 인터럽트 처리기, USB 완료 콜백, 셸 명령에서도 이 상태를 읽는다면 메모리 접근 순서와 잠금 범위를 함께 확인한다.
제어권을 넘기기 전에 확인할 조건을 정리한다
정상 경로는 OS handoff에서 끝난다. 이 단계가 함수 반환인지, scheduler 전환인지, 다른 image로의 비복귀 분기인지 구분한다. 비복귀 handoff라면 cache clean/invalidate, interrupt disable, 장치 quiesce, argument register와 FDT 또는 image address가 최종 점검 항목이다.
호출한 함수로 돌아오는 경로라면 오류와 일부 처리만 완료된 상태를 구분하는지 확인한다. 이어서 다음 후보를 시도할지, 복구 절차를 실행할지 살펴본다.
IMPLEMENTATION NOTES
구현을 읽을 때 놓치기 쉬운 부분
bootm_data는 사용자 선택을 실행 계획으로 고정한다
filename, OS file, initrd, FDT, verify와 dry-run option을 수집한 뒤 file type을 감지하고 handler를 고른다. command parsing 중의 임시 문자열과 handler가 오래 보관할 object의 ownership을 구분한다.
명시 handler와 auto-detect 결과가 충돌할 때 우선순위를 확인한다.
resource reservation은 image copy보다 앞서야 한다
kernel, initrd, FDT destination을 iomem resource로 예약해 barebox image, stack, malloc과 overlap을 막는다. 압축 image는 source, temporary와 output range를 모두 예약하거나 순서를 검증한다.
handler 실패 뒤 reservation과 open file을 해제해 다음 boot 시도를 오염시키지 않는다.
dry-run과 verbose가 state를 바꾸지 않는지 확인한다
진단용 scan이 device를 probe하거나 mount할 수는 있지만 persistent state, attempts와 storage를 수정해서는 안 된다. 실제 handoff 직전 callback과 dry-run 경로의 분기점을 찾는다.
연속 실패 boot 뒤 iomem과 heap을 비교해 cleanup을 검증한다.
OBJECT LIFETIME
객체와 수명
| 대상 | 만들어지는 시점 | 유효 범위 | 확인할 조건 |
|---|---|---|---|
bootm_data / image_data / image_handler | bootm_data | OS handoff 또는 오류 정리 완료까지 | 진입 전제와 상태 계약 |
| 입력 buffer / metadata | boot command/entry | parse와 검증이 끝날 때까지 | 길이, 정렬, 소유권, 변조 가능성 |
| 등록된 list / descriptor | filetype detect | 하위 시스템을 종료하거나 다음 이미지에 제어권을 넘길 때까지 | 중복 등록, 해제된 객체를 가리키는 포인터, 오류 후 자원 정리 |
| hardware 또는 persistent state | 실제 write/probe가 완료된 뒤 | reset 또는 명시적 해제·갱신까지 | 쓰기 완료, 시간 초과, 전원 차단, 이전 상태 복원 |
최종 부트로더 이미지 | link/image 생성 시점 | 다음 stage가 새 image로 교체할 때까지 | 적재 주소, 진입점, 섹션, 헤더의 일치 여부 |
FAILURE PATH
실패 지점과 증상
| # | 조건 | 관찰되는 증상 | 먼저 볼 단계 |
|---|---|---|---|
| 01 | filetype 오검출 | 잘못된 handler | bootm_data |
| 02 | resource 예약 실패 무시 | image overlap | filetype detect |
| 03 | 오류 cleanup 누락 | 다음 boot 시 stale reservation | image handler |
로그가 끊긴 함수뿐 아니라 그 함수에 주소, 크기, 플래그를 전달한 앞 단계도 조사한다. 오류 처리 후 등록된 객체나 하드웨어 설정이 그대로 남아 있는지도 확인한다.
EVIDENCE
소스 밖에서 확인할 증거
소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.
| # | 목적 | 명령 또는 계측 | 판정 기준 |
|---|---|---|---|
| 01 | 빌드 구성 | make <board>_defconfig && make V=1 | Kconfig, linker section과 최종 barebox image 생성 명령을 보관한다. |
| 02 | symbol과 section | ${CROSS_COMPILE}nm -n barebox | grep 'int bootm_boot' | initcall, command, driver descriptor가 image에 남았는지 확인한다. |
| 03 | 주소와 resource | iomem | image, malloc, stack, device resource와 reserved 영역의 겹침을 확인한다. |
| 04 | device 상태 | devinfo; drvinfo; of_dump | DT node 생성, device 등록, driver probe를 서로 구분한다. |
| 05 | boot 정책 | boot -d -v; state -d | entry 탐색 결과와 persistent state가 실제 선택에 미친 영향을 확인한다. |
LAB
직접 확인할 실험
- 01bootm -d -v로 handler와 주소 확인
bootm_data진입 전후에 bootm_data의 주소·크기·반환값과 timestamp를 함께 남긴다. - 02잘못된 magic image의 거부 위치 추적
filetype detect진입 전후에 image_data의 주소·크기·반환값과 timestamp를 함께 남긴다. - 03연속 실패 boot 후 iomem/heap 상태 비교
image handler진입 전후에 handler registry의 주소·크기·반환값과 timestamp를 함께 남긴다.
PRIMARY REFERENCES