QUESTION
입력 경로와 정적 command 등록은 어디서 만나고 무엇이 남는가?
console_start()는 read_debug_line으로 interactive 입력을 받는다. console_run_script()와 console_run_script_locked()는 fetch_next_line을 사용한다. 두 경로는 command_loop()에서 합류하지만 prompt는 interactive 경로에만 켜진다. 고정 console.c L570–780.
한 줄을 읽은 뒤 tokenize_command가 임시 argc/argv를 만들고 convert_args가 값을 채운다. match_command(..., CMD_AVAIL_NORMAL)은 링크 시 놓인 command block을 검색한다. callback의 반환값은 con->lastresult에 저장되며 PASS/FAIL 출력은 환경 기능과 reportresult 설정이 있을 때만 수행된다. 정적 검색 · 공통 루프.
STRUCTURE
두 입력 경로와 링크된 command block
command_loop()에서 한다read_debug_linecon->debug_buffer에 입력한다. showprompt=true로 루프를 호출한다.
fetch_next_linescript 문자열을 lineread.buffer로 가져온다. showprompt=false이며 locked API는 mutex 재획득을 생략한다.
argv · outbuf루프 진입 때 할당해 여러 command에 재사용하고 반환 때 해제한다. 다음 command가 내용을 덮어쓸 수 있다.
__start_commands → __stop_commandsconsole_cmd_block과 console_cmd는 링크된 등록 정보다. tokenizer가 만드는 list가 아니다.
입력·루프 근거 · 등록 macro와 descriptor 근거. console_t 자체는 console_create()에서 먼저 만들어진다.
CALL PATH
경로별 입력과 공통 처리
get_line callback만 달리해 공통 루프로 들어간다console_start(con)
console_set_current(con).command_loop(con, read_debug_line, …, true, false).- prompt를 보인 뒤
con->debug_buffer에서 한 줄을 받는다.
console_run_script_etc
lineread.buffer를 할당하고 script 위치를 초기화한다.command_loop(con, fetch_next_line, …, false, locked).- buffer를 해제한 뒤
con->lastresult를 반환한다.
args/outbuf를 먼저 할당한 뒤 get_line → tokenize_command → convert_args → match_command(..., CMD_AVAIL_NORMAL) → callback → con->lastresult. ; 뒤에는 같은 입력의 continuebuffer를 먼저 소비한다. console.c L570–677.STATE LEDGER
호출 단계와 살아 있는 상태
01–02는 서로 다른 진입 설정이다. 공통 루프는 03에서 args/outbuf를 먼저 할당하고, 04에서 비로소 입력을 읽는다. command block은 parse 중 생성되지 않는다.
| # | 문맥 | 입력과 작업 | 다음에 남는 값 | 고정 근거 |
|---|---|---|---|---|
| 01 | interactive 설정 | read_debug_line callback, showprompt=true 선택 | 앞서 만들어진 con->debug_buffer | L689–714 |
| 02 | script 설정 | lineread.buffer 할당, fetch_next_line callback 선택 | showprompt=false, locked 전달 | L750–763 |
| 03 | 공통 루프 | args와 outbuf를 할당 | 반복마다 재사용할 저장소 | L576–589 |
| 04 | 입력 | prompt 조건 확인 후 get_line 또는 continuebuffer | 한 줄의 buffer | L593–607 |
| 05 | parse | tokenize_command; ;이면 나머지 위치 보관 | argc/argv와 continuebuffer | L377–529 |
| 06 | convert·lookup | convert_args → 정적 block에서 normal mask 검색 | 일치하는 console_cmd 또는 없음 | L244–260 · L532–629 |
| 07 | callback | 필요하면 lock 획득 후 callback 호출 | con->lastresult | L631–638 |
| 08 | 출력·정리 | 조건부 result 출력, 다음 반복 또는 종료 | 루프 종료 시 args/outbuf 해제 | L639–685 |
없는 명령의 안내와 syntax 오류 메시지도 showprompt가 참인 경로에만 출력된다. console.c L604–631.
VISUAL WALKTHROUGH
한 command의 처리와 저장소 수명
실제 주소 대신 고정 소스가 보장하는 입력 공급자, 임시 저장소, 정적 등록 정보의 관계를 표시한다.
args/outbuf루프 진입 시 할당하고 여러 command에 재사용한다.
새 줄을 읽거나 ; 뒤의 continuebuffer를 사용한다.
argc/argvoutbuf 안의 token 문자열을 가리키는 임시 인자를 만든다.
convert_args문자열에서 숫자·boolean 필드를 채운다.
정적 block 범위를 CMD_AVAIL_NORMAL로 검색한다.
con->lastresulthandler 반환값을 기록한다. locked=false이면 lock을 획득·해제한다.
PASS/FAIL은 WITH_LIB_ENV와 reportresult가 참일 때만 출력한다. 다음 prompt는 interactive의 새 줄 읽기 전에 나온다.
console_cmd_block / console_cmdSTATIC_COMMAND_* macro가 정적 command 배열과 commands section의 block을 만든다. 이름·help·callback·availability mask를 보유하며 parser가 생성하거나 해제하지 않는다.
args / outbufcommand_loop가 할당·재사용·해제한다. script의 lineread.buffer는 wrapper 수명이다. 실행 문맥은 interactive console 또는 script 호출자에 따른다.
UPSTREAM SOURCE
원본 코드
아래 코드는 LK upstream 1eb9917의 lib/console/console.c에서 726-814줄을 그대로 가져온 것이다.
726
727 // we're done
728 if (lineread->string[lineread->pos] == 0)
729 return -1;
730
731 size_t bufpos = 0;
732 while (lineread->string[lineread->pos] != 0) {
733 if (lineread->string[lineread->pos] == '\n') {
734 lineread->pos++;
735 break;
736 }
737 if (bufpos == (lineread->buflen - 1))
738 break;
739 lineread->buffer[bufpos] = lineread->string[lineread->pos];
740 lineread->pos++;
741 bufpos++;
742 }
743 lineread->buffer[bufpos] = 0;
744
745 *buffer = lineread->buffer;
746
747 return bufpos;
748}
749
750static int console_run_script_etc(console_t *con, const char *string, bool locked) {
751 struct line_read_struct lineread;
752
753 lineread.string = string;
754 lineread.pos = 0;
755 lineread.buffer = malloc(LINE_LEN);
756 lineread.buflen = LINE_LEN;
757
758 command_loop(con, &fetch_next_line, (void *)&lineread, false, locked);
759
760 free(lineread.buffer);
761
762 return con->lastresult;
763}
764
765int console_run_script(console_t *con, const char *string) {
766 if (!con) {
767 con = console_get_current();
768 }
769 return console_run_script_etc(con, string, false);
770}
771
772int console_run_script_locked(console_t *con, const char *string) {
773 if (!con) {
774 con = console_get_current();
775 }
776 return console_run_script_etc(con, string, true);
777}
778
779console_cmd_func console_get_command_handler(const char *commandstr) {
780 const console_cmd *command = match_command(commandstr, CMD_AVAIL_NORMAL);
781
782 if (command)
783 return command->cmd_callback;
784 else
785 return NULL;
786}
787
788static int cmd_help_impl(uint8_t availability_mask) {
789 printf("command list by block:\n");
790
791 for (const console_cmd_block *block = &__start_commands; block != &__stop_commands; block++) {
792 const console_cmd *curr_cmd = block->list;
793 printf(" [%s]\n", block->name);
794 for (size_t i = 0; i < block->count; i++) {
795 if ((availability_mask & curr_cmd[i].availability_mask) == 0) {
796 // Skip commands that aren't available in the current shell.
797 continue;
798 }
799 if (curr_cmd[i].help_str)
800 printf("\t%-16s: %s\n", curr_cmd[i].cmd_str, curr_cmd[i].help_str);
801 }
802 }
803
804 return 0;
805}
806
807static int cmd_help(int argc, const console_cmd_args *argv) {
808 return cmd_help_impl(CMD_AVAIL_NORMAL);
809}
810
811static int cmd_help_panic(int argc, const console_cmd_args *argv) {
812 return cmd_help_impl(CMD_AVAIL_PANIC);
813}
814
READING CONTRACT
발췌 범위와 공통 루프
첫 원문은 console.c L726–814 중 script wrapper와 command lookup 후반이다. 기준 구문 static int console_run_script_etc는 L750에 있다. command_loop 전체와 interactive 진입은 이 발췌보다 앞에 있으므로 L570–714를 함께 읽어야 한다.
두 번째 원문은 tokenizer L367–455의 앞부분만 보여준다. ; 처리와 convert_args는 이어지는 L455–569에 있다. 원본 코드 블록은 그대로 유지했다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
아래 발췌는 tokenizer의 앞부분이다. 전체 command_loop와 등록 macro는 고정 commit의 링크된 원문을 함께 읽는다.
01. 입력 한 줄을 argc와 argv로 분해하는 tokenizer
lib/console/console.c 367-455줄이다.
367 // add to history
368 add_history(con, buffer);
369#endif
370
371 // return a pointer to our buffer
372 *outbuffer = buffer;
373
374 return pos;
375}
376
377static int tokenize_command(const char *inbuffer, const char **continuebuffer, char *buffer, size_t buflen, console_cmd_args *args, int arg_count) {
378 int inpos;
379 int outpos;
380 int arg;
381 enum {
382 INITIAL = 0,
383 NEXT_FIELD,
384 SPACE,
385 IN_SPACE,
386 TOKEN,
387 IN_TOKEN,
388 QUOTED_TOKEN,
389 IN_QUOTED_TOKEN,
390 VAR,
391 IN_VAR,
392 COMMAND_SEP,
393 } state;
394 char varname[128];
395 int varnamepos;
396
397 inpos = 0;
398 outpos = 0;
399 arg = 0;
400 varnamepos = 0;
401 state = INITIAL;
402 *continuebuffer = NULL;
403
404 for (;;) {
405 char c = inbuffer[inpos];
406
407// dprintf(SPEW, "c 0x%hhx state %d arg %d inpos %d pos %d\n", c, state, arg, inpos, outpos);
408
409 switch (state) {
410 case INITIAL:
411 case NEXT_FIELD:
412 if (c == '\0')
413 goto done;
414 if (isspace(c))
415 state = SPACE;
416 else if (c == ';')
417 state = COMMAND_SEP;
418 else
419 state = TOKEN;
420 break;
421 case SPACE:
422 state = IN_SPACE;
423 break;
424 case IN_SPACE:
425 if (c == '\0')
426 goto done;
427 if (c == ';') {
428 state = COMMAND_SEP;
429 } else if (!isspace(c)) {
430 state = TOKEN;
431 } else {
432 inpos++; // consume the space
433 }
434 break;
435 case TOKEN:
436 // start of a token
437 DEBUG_ASSERT(c != '\0');
438 if (c == '"') {
439 // start of a quoted token
440 state = QUOTED_TOKEN;
441 } else if (c == '$') {
442 // start of a variable
443 state = VAR;
444 } else {
445 // regular, unquoted token
446 state = IN_TOKEN;
447 args[arg].str = &buffer[outpos];
448 }
449 break;
450 case IN_TOKEN:
451 if (c == '\0') {
452 arg++;
453 goto done;
454 }
455 if (isspace(c) || c == ';') {
DETAILS
고정 구현에서 확인할 경계
interactive와 script는 호출 문맥이 다르다
console_start는 현재 console TLS를 설정하고 read_debug_line으로 루프를 돈다. script API는 호출한 thread에서 fetch_next_line을 넘겨 같은 루프를 실행한다. 따라서 모든 invocation을 전용 console thread로 그리지 않는다. console.c L698–777 · API 주석.
정적 command block은 parse 결과가 아니다
STATIC_COMMAND_* macro는 commands section에 block을 둔다. match_command가 linker 경계 사이를 순회하며 availability mask와 이름을 검사한다. 빌드 조건은 macro 자체와 해당 모듈 포함 여부를 함께 봐야 한다. cmd.h L20–51 · console.c L80–112 · L244–260.
callback 결과와 화면 출력은 별개다
일치하는 handler 반환값만 con->lastresult에 저장된다. PASS/FAIL은 WITH_LIB_ENV와 reportresult에 좌우된다. 입력 오류·없는 명령의 화면 안내는 showprompt일 때만 출력된다. console.c L604–659.
locked script는 내부 재호출을 위한 경로다
일반 루프는 callback 전후 mutex를 획득·해제한다. console_run_script_locked는 locked=true를 넘겨 루프의 재획득을 생략한다. 헤더는 이를 command 내부의 특수 사례로 설명한다. console.c L631–677 · L765–777 · API 주석.
IMPLEMENTATION NOTES
입력 경계와 조건부 동작
lookup 실패는 callback 결과가 아니다
일치하는 command가 없으면 callback을 호출하지 않고 다음 반복으로 간다. command not found 문구는 interactive에서만 찍으므로 script 반환값을 해당 오류 메시지로 추정하지 않는다. console.c L623–631.
abort_script와 lock을 나눠 본다
callback 이후 con->abort_script를 확인해 반복을 끝낼 수 있다. script wrapper의 locked 인자는 루프에서 mutex를 다시 잡을지 결정한다. 어느 경로든 정적 command block을 해제하는 단계는 없다. console.c L631–685 · L765–777.
OBJECT LIFETIME
정적 등록 정보와 호출 중 임시 상태
| 대상 | 만들어지는 곳 | 사용·종료 범위 | 근거 |
|---|---|---|---|
console_t / debug_buffer | console_create의 calloc / malloc(LINE_LEN) | interactive 입력은 이 console의 buffer를 사용 | L689–709 |
console_cmd_block / console_cmd | STATIC_COMMAND_* macro, 링크 시 section | 정적 등록 정보; availability mask로 검색 | cmd.h L20–51 · L244–260 |
args / outbuf | command_loop 진입 시 heap 할당 | 반복 중 재사용, 루프 종료 시 해제 | L576–589 · L675–685 |
script lineread.buffer | console_run_script_etc의 malloc(LINE_LEN) | script wrapper의 루프 호출 뒤 해제 | L750–763 |
con->lastresult | 일치한 command callback의 반환 | console 객체에 보관; script API가 반환 | L631–638 · L760–763 |
FAILURE PATH
입력과 검색의 분기
| # | 조건 | 고정 소스의 동작 | 확인할 위치 |
|---|---|---|---|
| 01 | interactive 입력이 길다 | line too long 출력, 길이 0인 줄로 돌아가 루프가 계속 | L352–375 · L599–603 |
| 02 | script 입력이 buffer보다 길다 | 현재 위치에서 끊고 다음 fetch에서 남은 문자열을 읽을 수 있음 | L724–748 |
| 03 | 빈 입력 또는 token 없음 | callback 없이 다음 반복으로 진행 | L599–620 |
| 04 | 일치하는 normal command 없음 | callback 없음; 안내 문구는 showprompt가 참일 때만 출력 | L623–631 |
| 05 | args 또는 outbuf 할당 실패 | 할당분 해제 후 ERR_NO_MEMORY 반환 | L576–589 · L679–690 |
script wrapper는 command_loop의 status 대신 con->lastresult를 반환한다. 따라서 wrapper 반환만으로 루프 내부의 모든 실패를 식별한다고 단정하지 않는다. console.c L750–763.
EVIDENCE
고정 소스와 실제 실행을 대조할 지점
command_loop()의 args·outbuf 실패 처리와 입력 buffer의 할당은 별개다. console_run_script() 계열의 lineread.buffer = malloc(LINE_LEN), console_create()의 debug_buffer 할당에는 각각의 NULL 검사가 없다. 따라서 모든 console 메모리 부족이 ERR_NO_MEMORY로 안전하게 반환된다고 일반화할 수 없다. 입력 buffer와 script wrapper 구현.
아래 항목은 실행 결과가 아닌 검증 설계다. 이 글의 근거는 고정 버전 소스 대조이며, LK 실기기·에뮬레이터 실행은 검증 범위에 포함되지 않는다.
| # | 목적 | 볼 값 | 판정 기준 |
|---|---|---|---|
| 01 | 등록 정보 | 빌드 map의 commands section과 __start_commands/__stop_commands | 대상 command block과 availability가 포함되는지 확인 |
| 02 | 입력 공급자 | get_line callback 주소와 showprompt 값 | interactive와 script를 구별 |
| 03 | parse 경계 | 입력 길이, argc, continuebuffer, 첫 argv.str | tokenizer가 임시 argv를 만들고 ;를 이어 처리하는지 확인 |
| 04 | lookup·결과 | match 결과, availability mask, callback 반환, lastresult | 없는 command와 handler 결과를 구별 |
| 05 | 조건부 출력·lock | WITH_LIB_ENV, reportresult, locked | PASS/FAIL과 mutex 경로가 실제 조건에 맞는지 확인 |
LAB
interactive와 script를 나란히 확인하는 방법
- 01같은 command를 두 공급자로 실행한다
interactive 입력과
console_run_script에 같은 문자열을 주고get_line, prompt, callback 반환을 기록한다. - 02
;와 quote를 넣는다continuebuffer,argc,argv.str을 계측해 새 줄 읽기 없이 다음 command로 이어지는지 확인한다. - 03없는 명령과 길이 경계를 비교한다
interactive와 script에서 안내 출력·
lastresult·입력 분할을 따로 기록한다. - 04command 내부 script 경로를 확인한다
console_run_script_locked와 일반 API의locked값을 대조한다. lock을 실제로 보유한 호출 문맥에서만 특수 경로를 시험한다.
PRIMARY REFERENCES