Barebox · source analysis

envfs load와 default environment

영속 envfs image를 검증해 디렉터리로 펼치고 default environment와 합치는 과정을 읽습니다.

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

Series
11 / 19
Baseline
v2026.06.1
Commit
314c679eea2d
Source
common/environment.c:422-510 (발췌 범위)

envfs load와 default environment 단계에서 실제로 바뀌는 상태는 무엇인가?

U-Boot의 key-value blob과 달리 Barebox 환경은 파일과 script 중심이다. 저장 image의 integrity, extraction path와 default overlay 순서를 확인한다.

검증되지 않은 entry가 environment root 밖으로 추출되거나 기존 runtime state를 부분적으로 덮어쓰지 않아야 한다. 이 문장을 기준으로 코드를 위에서 아래로 읽으면, 함수 이름을 외우는 대신 어느 시점에 어떤 상태를 신뢰할 수 있는지 판단할 수 있다.

객체와 주소가 놓이는 구조

그림 1. envfs load와 default environment에서 입력, 내부 상태, 출력의 경계
입력과 전제내부 상태외부로 공개되는 결과
01envfs image
02superblock/inodes
03runtime directory
04global variables

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

실행 흐름

그림 2. 정상 경로의 주요 호출과 상태 전달
environment cdev/file
envfs superblock
CRC/decompress
extract files
shell variables/scripts

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

단계별 입력과 출력

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

#단계진입 시 신뢰할 상태성공 뒤 남아야 할 상태다음 소비자
01environment cdev/file부트 CPU의 동기 실행 문맥envfs imageenvfs superblock
02envfs superblockenvironment cdev/file 완료 상태superblock/inodesCRC/decompress
03CRC/decompressenvfs superblock 완료 상태runtime directoryextract files
04extract filesCRC/decompress 완료 상태global variablesshell variables/scripts
05shell variables/scriptsextract files 완료 상태global variables이 단계의 처리 결과를 사용하는 코드

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

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

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

그림 3. envfs image를 runtime directory로 펼치는 과정

호출 이름만 나열하지 않고, 각 단계가 다음 단계에 넘기는 상태를 기준으로 실행 순서를 표시한다.

01environment file/cdev
02superblock read
03size·CRC 검증
04decompress
05inode/path 검증
06temporary extraction
07runtime environment 전환
그림 4. default environment와 persistent envfs

두 열의 객체는 이름이 비슷해도 생성 시점, 사용 가능한 API와 해제 책임이 다르다.

Default

01binary에 포함

02복구 기준

03read-only 원본

04build version 의존

05CRC 실패 시 사용

Persistent

01storage image

02사용자 수정

03saveenv 결과

04전원 차단 위험

05default 위에 적용

원본 코드

아래 코드는 Barebox v2026.06.1의 common/environment.c에서 422-510줄을 그대로 가져온 것이다. 설명을 위해 실제 코드를 가짜 의사 코드로 바꾸지 않았다.

commit314c679eea2d0ca847c64d1b646a1cf91225c0ecanchor · L446int envfs_load(const char *filename
422	defenv_path = default_environment_path_get();
423	if (defenv_path && !strcmp(filename, defenv_path))
424	    nv_var_set_clean();
425#endif
426out:
427	close(envfd);
428out1:
429	free(buf);
430#ifdef __BAREBOX__
431	unlink_recursive(TMPDIR, NULL);
432#endif
433	return ret;
434}
435EXPORT_SYMBOL(envfs_save);
436
437/**
438 * Restore the last environment into the current one
439 * @param[in] filename from where to restore
440 * @param[in] dir where to store the last content
441 * @return 0 on success, anything else in case of failure
442 *
443 * Note: This function will also be used on the host! See note in the header
444 * of this file.
445 */
446int envfs_load(const char *filename, const char *dir, unsigned flags)
447{
448	struct envfs_super super;
449	void *buf = NULL, *rbuf;
450	int envfd;
451	int ret = 0;
452	size_t size, rsize;
453	__maybe_unused const char *defenv_path;
454
455#ifdef __BAREBOX__
456	if (!IS_ALLOWED(SCONFIG_ENVIRONMENT_LOAD))
457		return -EPERM;
458#endif
459
460	if (!filename)
461		filename = default_environment_path_get();
462	if (!filename)
463		return -ENOENT;
464
465	if (!dir)
466		dir = "/env";
467
468	envfd = open(filename, O_RDONLY);
469	if (envfd < 0) {
470		printf("environment load %s: %m\n", filename);
471		if (errno == ENOENT)
472			printf("Maybe you have to create the partition.\n");
473		return -1;
474	}
475
476	/* read superblock */
477	ret = read(envfd, &super, sizeof(struct envfs_super));
478	if ( ret < sizeof(struct envfs_super)) {
479		perror("read");
480		ret = -errno;
481		goto out;
482	}
483
484	ret = envfs_check_super(&super, &size);
485	if (ret)
486		goto out;
487
488	if (super.flags & ENVFS_FLAGS_FORCE_BUILT_IN) {
489		printf("found force-builtin environment, using defaultenv\n");
490		ret = defaultenv_load(dir, 0);
491		if (ret)
492			printf("failed to load default environment: %s\n",
493					strerror(-ret));
494		goto out;
495	}
496
497	buf = xmalloc(size);
498
499	rbuf = buf;
500	rsize = size;
501
502	while (rsize) {
503		ssize_t now;
504
505		now = read(envfd, rbuf, rsize);
506		if (now < 0) {
507			perror("read");
508			ret = -errno;
509			goto out;
510		}

발췌 범위와 읽기 기준

원문 422-510줄에는 앞뒤 문맥이 포함됩니다. 기준 구문 int envfs_load(const char *filename은 L446에 있습니다. 발췌 첫 줄을 함수 정의의 시작으로 해석하지 않습니다.

U-Boot의 key-value blob과 달리 Barebox 환경은 파일과 script 중심이다. 저장 image의 integrity, extraction path와 default overlay 순서를 확인한다.

함께 읽어야 하는 원본 코드

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

01. runtime environment를 envfs image로 직렬화

common/environment.c 295-397줄이다.

filecommon/environment.canchor · L305int envfs_save
295/**
296 * Make the current environment persistent
297 * @param[in] filename where to store
298 * @param[in] dirname what to store (all files in this dir)
299 * @param[in] flags superblock flags (refer ENVFS_FLAGS_* macros)
300 * @return 0 on success, anything else in case of failure
301 *
302 * Note: This function will also be used on the host! See note in the header
303 * of this file.
304 */
305int envfs_save(const char *filename, const char *dirname, unsigned flags)
306{
307	struct envfs_super *super;
308	int envfd, size, ret;
309	struct action_data data = {};
310	void *buf = NULL, *wbuf;
311	struct envfs_entry *env;
312	__maybe_unused const char *defenv_path;
313
314	if (!filename)
315		return -ENOENT;
316
317	if (!dirname)
318		dirname = "/env";
319
320	data.writep = NULL;
321	data.base = dirname;
322
323#ifdef __BAREBOX__
324	defaultenv_load(TMPDIR, 0);
325#endif
326
327	if (flags & ENVFS_FLAGS_FORCE_BUILT_IN) {
328		size = 0; /* force no content */
329	} else {
330		/* first pass: calculate size */
331		recursive_action(dirname, ACTION_RECURSE | ACTION_SORT, file_action,
332				NULL, &data, 0);
333		recursive_action("/.defaultenv", ACTION_RECURSE | ACTION_SORT,
334				file_remove_action, NULL, &data, 0);
335		size = 0;
336
337		for (env = data.env; env; env = env->next) {
338			size += PAD4(env->size);
339			size += sizeof(struct envfs_inode);
340			size += PAD4(strlen(env->name) + 1);
341			size += sizeof(struct envfs_inode_end);
342		}
343	}
344
345	buf = xzalloc(size + sizeof(struct envfs_super));
346	data.writep = buf + sizeof(struct envfs_super);
347
348	super = buf;
349	super->magic = ENVFS_32(ENVFS_MAGIC);
350	super->major = ENVFS_MAJOR;
351	super->minor = ENVFS_MINOR;
352	super->size = ENVFS_32(size);
353	super->flags = ENVFS_32(flags);
354
355	if (!(flags & ENVFS_FLAGS_FORCE_BUILT_IN)) {
356		/* second pass: copy files to buffer */
357		env = data.env;
358		while (env) {
359			struct envfs_entry *next = env->next;
360
361			envfs_save_inode(&data, env);
362
363			free(env->buf);
364			free(env->name);
365			free(env);
366			env = next;
367		}
368	}
369
370	super->crc = ENVFS_32(crc32(0, buf + sizeof(struct envfs_super), size));
371	super->sb_crc = ENVFS_32(crc32(0, buf, sizeof(struct envfs_super) - 4));
372
373	envfd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
374	if (envfd < 0) {
375		printf("could not open %s: %m\n", filename);
376		ret = -errno;
377		goto out1;
378	}
379
380	ret = protect(envfd, ~0, 0, 0);
381
382	/* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */
383	if (ret && errno != ENOSYS && errno != EOPNOTSUPP) {
384		printf("could not unprotect %s: %m\n", filename);
385		goto out;
386	}
387
388	ret = erase(envfd, ERASE_SIZE_ALL, 0, ERASE_TO_WRITE);
389
390	/* ENOSYS and EOPNOTSUPP aren't errors here, many devices don't need it */
391	if (ret && errno != ENOSYS && errno != EOPNOTSUPP) {
392		printf("could not erase %s: %m\n", filename);
393		goto out;
394	}
395
396	size += sizeof(struct envfs_super);
397

내부 동작을 더 깊게 읽기

01

진입 조건을 먼저 고정한다

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

U-Boot의 key-value blob과 달리 Barebox 환경은 파일과 script 중심이다. 저장 image의 integrity, extraction path와 default overlay 순서를 확인한다.

02

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

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

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

03

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

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

04

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

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

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

05

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

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

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

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

01

envfs는 key-value blob이 아니라 파일 tree image다

superblock과 inode entry를 검증하고 압축 또는 CRC를 확인한 뒤 runtime environment directory로 파일과 script를 펼친다. path, mode와 file length를 신뢰하기 전에 image 전체 범위 안인지 계산한다.

..와 절대 path가 environment root 밖으로 나가지 못하게 canonicalization을 확인한다.

02

default environment와 persistent overlay 순서를 본다

built-in default 파일을 먼저 구성하고 valid envfs를 덮는지, persistent load 실패 시 default로 완전히 되돌리는지 확인한다. 부분 extraction 뒤 CRC나 entry 오류가 나면 이미 쓴 파일을 정리해야 한다.

같은 파일의 source와 최종 내용을 표시해 우선순위를 검증한다.

03

saveenv의 atomicity는 backend에 달려 있다

새 image를 memory에서 완성·검증한 뒤 storage에 기록해야 하며 단일 erase block을 덮는 backend는 전원 차단에 취약하다. redundant copy, rename 가능한 filesystem 또는 state backend와 보장 수준을 구분한다.

write 중 reset 뒤 어느 copy가 선택되는지 반복 시험한다.

객체와 수명

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

실패 지점과 증상

#조건관찰되는 증상먼저 볼 단계
01CRC 오류persistent env 무시envfs superblock
02path traversal 처리 오류임의 파일 overwriteCRC/decompress
03전원 차단새 envfs image 손상extract files

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

소스 밖에서 확인할 증거

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

#목적명령 또는 계측판정 기준
01빌드 구성make <board>_defconfig && make V=1Kconfig, linker section과 최종 barebox image 생성 명령을 보관한다.
02symbol과 section${CROSS_COMPILE}nm -n barebox | grep 'int envfs_load'initcall, command, driver descriptor가 image에 남았는지 확인한다.
03주소와 resourceiomemimage, malloc, stack, device resource와 reserved 영역의 겹침을 확인한다.
04device 상태devinfo; drvinfo; of_dumpDT node 생성, device 등록, driver probe를 서로 구분한다.
05boot 정책boot -d -v; state -dentry 탐색 결과와 persistent state가 실제 선택에 미친 영향을 확인한다.

직접 확인할 실험

  1. 01
    saveenv/loadenv 전후 envfs header 비교

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

  2. 02
    CRC byte 변조 후 default fallback 확인

    CRC/decompress 진입 전후에 superblock/inodes의 주소·크기·반환값과 timestamp를 함께 남긴다.

  3. 03
    환경 파일 하나의 mode와 내용 보존 확인

    extract files 진입 전후에 runtime directory의 주소·크기·반환값과 timestamp를 함께 남긴다.

원문과 다음 글