LK · source analysis

APP_START descriptor와 app thread

정적 app descriptor와 apps_init()의 두 순회, 조건부 app thread 생성을 읽습니다.

Series
12 / 20
Baseline
upstream 1eb9917
Commit
1eb99171efae
Source
app/app.c:1-86 (발췌 범위)

descriptor가 언제 callback 또는 thread로 이어지는가?

APP_START(name)는 함수를 실행하지 않는다. 고정 app.h는 이름, init, entry, flags, stack size를 가진 const struct app_descriptor를 __SECTION("apps")에 선언한다.

apps_init()는 __start_apps부터 __stop_apps까지 먼저 모든 비어 있지 않은 init을 호출한다. 첫 순회가 끝난 뒤에야 entry가 있고 APP_FLAG_NO_AUTOSTART가 없는 descriptor만 자동으로 시작한다. init-only app에는 app thread가 생기지 않는다.

정적 descriptor와 조건부 thread

그림 1. APP_START가 배치한 정적 객체와 두 callback
정적 선언두 순회의 선택실행 결과
01__SECTION("apps") descriptor
02name · init · entry · flags · stack_size
03init 있으면 첫 순회에서 호출
04자동 시작 조건 만족 시 thread

링커 경계 기호는 app/app.c의 __start_apps·__stop_apps다. section 이름은 매크로의 문자열 "apps"이며 .apps라는 literal 표기로 바꾸지 않는다.

첫 순회와 두 번째 순회

그림 2. apps_init()의 두 독립 순회
정적 apps 범위
첫 순회: 모든 non-null init
첫 순회 완료
둘째 순회: entry·flag 검사
해당 app만 start_app(app,true)

init은 호출된 apps_init()의 문맥에서 직접 실행된다. 두 번째 순회의 thread_resume() 이후 각 entry가 언제 실행되는지는 scheduler에 달려 있으므로 entry 완료 순서를 이 화살표에서 보장하지 않는다.

descriptor별 조건과 다음 소비자

init과 entry는 별도 필드다. APP_FLAG_NO_AUTOSTART는 자동 시작만 막으며, 이름으로 명시적 시작을 요청하는 경로까지 없애지 않는다.

#단계·조건실행 동작결과다음 소비자
01APP_START·APP_ENDconst app_descriptor 정적 선언apps section에 metadata링커 범위 심벌
02첫 순회, app->init 있음app->init(app) 직접 호출모든 init callback 완료 후 다음 순회apps_init()
03둘째 순회, entry 없음자동 시작 생략init-only descriptor에는 thread 없음후속 descriptor
04APP_FLAG_NO_AUTOSTART자동 시작 생략명시적 시작 경로는 별개요청 시 app_start_by_name()
05entry 있고 flag 허용start_app(app,true)thread 생성·detach·resumeapp_thread_entry()

apps_init()는 void이며 각 init callback도 void다. 표의 순회를 일괄 성공·rollback transaction으로 해석할 근거는 이 코드에 없다.

init-only와 thread entry의 갈림길

정적 descriptor가 모두 thread를 갖는 것은 아니다. 자동 시작은 entry와 flag에 의해 결정되며, 종료·재시작 정책은 각 app 구현에서 확인해야 한다.

그림 3. 자동 시작 조건을 통과한 app만 thread로

첫 순회에서 init callback을 모두 처리한 뒤, 두 번째 순회에서 각 descriptor의 entry·flag를 평가한다.

01APP_START 정적 descriptor
02__start_apps–__stop_apps
03첫 순회: non-null init
04둘째 순회: entry && !NO_AUTOSTART
05thread_create·detach·resume
06app_thread_entry → entry(app,NULL)
그림 4. descriptor와 실제 app thread의 조건부 관계

정적 metadata는 모든 포함 app에 있지만, 자동 시작 경로의 runtime thread는 entry·flag 조건을 통과했을 때만 만들어진다.

정적 descriptor

01__SECTION("apps")

02name · init · entry

03flags · stack_size

04__start_apps 범위 순회

05init-only여도 범위에 존재

자동 시작 runtime thread

01entry 있고 autostart 허용

02thread_create(...,DEFAULT_PRIORITY,...)

03custom flag면 stack_size 사용

04자동 시작은 detach·resume

05entry는 (app, NULL) 호출

원본 코드

아래 코드는 LK upstream 1eb9917의 app/app.c에서 1-86줄을 그대로 가져온 것이다.

commit1eb99171efae98867d4be4a5bd6479ea03f43ac9anchor · L22void apps_init(void)
1/*
2 * Copyright (c) 2009 Travis Geiselbrecht
3 *
4 * Use of this source code is governed by a MIT-style
5 * license that can be found in the LICENSE file or at
6 * https://opensource.org/licenses/MIT
7 */
8#include "app.h"
9
10#include <stdio.h>
11#include <string.h>
12#include <lk/err.h>
13#include <lk/console_cmd.h>
14#include <kernel/thread.h>
15
16extern const struct app_descriptor __start_apps __WEAK;
17extern const struct app_descriptor __stop_apps __WEAK;
18
19static void start_app(const struct app_descriptor *app, bool detach);
20
21/* one time setup */
22void apps_init(void) {
23    const struct app_descriptor *app;
24
25    /* call all the init routines */
26    for (app = &__start_apps; app != &__stop_apps; app++) {
27        if (app->init)
28            app->init(app);
29    }
30
31    /* start any that want to start on boot */
32    for (app = &__start_apps; app != &__stop_apps; app++) {
33        if (app->entry && (app->flags & APP_FLAG_NO_AUTOSTART) == 0) {
34            start_app(app, true);
35        }
36    }
37}
38
39static int app_thread_entry(void *arg) {
40    const struct app_descriptor *app = (const struct app_descriptor *)arg;
41
42    app->entry(app, NULL);
43
44    return 0;
45}
46
47static void start_app(const struct app_descriptor *app, bool detach) {
48    /* dont start an app that has no entry point */
49    if (app->entry == NULL) {
50        return;
51    }
52
53    uint32_t stack_size = (app->flags & APP_FLAG_CUSTOM_STACK_SIZE) ? app->stack_size : DEFAULT_STACK_SIZE;
54
55    printf("starting app %s\n", app->name);
56    thread_t *t = thread_create(app->name, &app_thread_entry, (void *)app, DEFAULT_PRIORITY, stack_size);
57    if (detach) {
58        thread_detach(t);
59        thread_resume(t);
60    } else {
61        thread_resume(t);
62        thread_join(t, NULL, INFINITE_TIME);
63    }
64}
65
66status_t app_start_by_name(const char *name, bool detached) {
67    const struct app_descriptor *app;
68
69    /* find the app and call it */
70    for (app = &__start_apps; app != &__stop_apps; app++) {
71        if (!strcmp(app->name, name)) {
72            start_app(app, detached);
73            return NO_ERROR;
74        }
75    }
76
77    return ERR_NOT_FOUND;
78}
79
80static void list_apps(void) {
81    const struct app_descriptor *app;
82
83    for (app = &__start_apps; app != &__stop_apps; app++) {
84        printf("%s\n", app->name);
85    }
86}

발췌 범위와 읽기 기준

보존 발췌 app/app.c:1–86에서 apps_init()은 L22, 첫 init 순회는 L26–29, 두 번째 autostart 순회는 L32–37이다. start_app()의 thread 경로는 같은 발췌 L47–64에서 확인한다.

APP_START의 정확한 선언, APP_FLAG_NO_AUTOSTART와 APP_FLAG_CUSTOM_STACK_SIZE 정의는 발췌 밖의 고정 app/include/app.h:27–45에 있다. 원문 첫 줄을 함수 시작으로 읽지 않는다.

함께 읽어야 하는 원본 코드

아래 보존 발췌 app/app.c:39–95는 app_thread_entry(), start_app()와 이름으로 시작하는 경로를 보여 준다. descriptor의 선언과 두 flag는 같은 commit의 app.h에서 대조한다.

01. app descriptor를 thread로 바꾸는 start_app

app/app.c 39-95줄이다.

fileapp/app.canchor · L47static void start_app(const struct app_descriptor *app, bool detach) {
39static int app_thread_entry(void *arg) {
40    const struct app_descriptor *app = (const struct app_descriptor *)arg;
41
42    app->entry(app, NULL);
43
44    return 0;
45}
46
47static void start_app(const struct app_descriptor *app, bool detach) {
48    /* dont start an app that has no entry point */
49    if (app->entry == NULL) {
50        return;
51    }
52
53    uint32_t stack_size = (app->flags & APP_FLAG_CUSTOM_STACK_SIZE) ? app->stack_size : DEFAULT_STACK_SIZE;
54
55    printf("starting app %s\n", app->name);
56    thread_t *t = thread_create(app->name, &app_thread_entry, (void *)app, DEFAULT_PRIORITY, stack_size);
57    if (detach) {
58        thread_detach(t);
59        thread_resume(t);
60    } else {
61        thread_resume(t);
62        thread_join(t, NULL, INFINITE_TIME);
63    }
64}
65
66status_t app_start_by_name(const char *name, bool detached) {
67    const struct app_descriptor *app;
68
69    /* find the app and call it */
70    for (app = &__start_apps; app != &__stop_apps; app++) {
71        if (!strcmp(app->name, name)) {
72            start_app(app, detached);
73            return NO_ERROR;
74        }
75    }
76
77    return ERR_NOT_FOUND;
78}
79
80static void list_apps(void) {
81    const struct app_descriptor *app;
82
83    for (app = &__start_apps; app != &__stop_apps; app++) {
84        printf("%s\n", app->name);
85    }
86}
87
88static int cmd_app(int argc, const console_cmd_args *argv) {
89    if (argc == 1) {
90usage:
91        printf("%s subcommands:\n", argv[0].str);
92        printf("%s list         : list apps compiled into the system\n", argv[0].str);
93        printf("%s start <name> : run app\n", argv[0].str);
94        return ERR_INVALID_ARGS;
95    } else if (!strcmp(argv[1].str, "list")) {

선언부터 entry 호출까지

01

매크로는 정적 descriptor를 만든다

APP_START(appname)는 _app_##appname const 객체를 포인터 크기에 맞춰 정렬해 __SECTION("apps")에 둔다. APP_END가 initializer를 닫는다. app/app.c는 이 객체 범위를 __start_apps·__stop_apps로 순회한다.

02

init callback은 첫 순회에서 직접 실행

apps_init()의 첫 for loop는 각 app->init이 있으면 app->init(app)을 호출한다. flag로 init 전용 thread를 만드는 분기는 없다. 첫 순회 전체가 끝난 뒤 두 번째 for loop가 시작된다.

03

자동 시작은 entry와 flag가 함께 결정

둘째 순회는 app->entry && (app->flags & APP_FLAG_NO_AUTOSTART) == 0인 경우에만 start_app(app,true)을 호출한다. init-only descriptor는 첫 순회에 참여해도 thread는 생기지 않는다.

04

thread의 stack과 호출 인자

start_app()은 custom-stack flag에 따라 descriptor의 stack_size 또는 DEFAULT_STACK_SIZE를 고른다. thread_create()에는 DEFAULT_PRIORITY와 descriptor pointer를 넘긴다. thread 함수는 app->entry(app,NULL)을 호출한다.

05

명시적 시작은 별개

app_start_by_name()은 이름을 찾아 start_app(app,detached)을 호출한다. NO_AUTOSTART는 이 함수의 조건이 아니다. 다만 일치하는 init-only app은 start_app()의 null-entry guard에서 끝나며, 이름 일치만으로 thread 생성 성공을 증명하지 않는다.

코드가 보장하는 순서와 보장하지 않는 것

01

두 순회 사이에 init barrier가 있다

고정 함수 본문에서는 모든 non-null init callback 호출이 끝난 뒤에야 autostart 순회를 시작한다. 그러나 각 app thread는 두 번째 순회 도중 resume된다. 여러 entry의 실제 실행·완료 순서를 이 코드만으로 단정하지 않는다.

02

detach 여부는 호출 경로가 정한다

자동 시작은 start_app(app,true)라서 thread_detach() 뒤 thread_resume()한다. 명시적 호출은 detached 인자에 따라 같은 경로 또는 thread_resume() 뒤 thread_join(...,INFINITE_TIME) 경로를 택한다.

03

이 함수에 보편적 stop/restart는 없다

app_thread_entry()는 entry callback 뒤 0을 반환한다. app/app.c의 이 경로에는 전체 app을 대상으로 하는 shutdown hook, rollback loop나 자동 restart 정책이 보이지 않는다. 개별 app의 자체 수명 관리는 그 app의 코드를 별도로 살펴야 한다.

정적 객체와 조건부 runtime 객체

대상생성·정의사용 지점범위
app_descriptorAPP_START의 const 정의두 순회·이름 검색링크된 image의 정적 객체
init callbackdescriptor 필드첫 순회에서 non-null이면 직접 호출thread 생성과 별개
entry callbackdescriptor 필드자동 시작 조건 또는 명시적 시작null이면 start_app()에서 반환
thread_t·stackthread_create()조건을 통과한 app entry자동 경로는 detached; 명시 경로는 인자별
APP_FLAG_CUSTOM_STACK_SIZEdescriptor flagsstart_app()의 stack 선택없으면 DEFAULT_STACK_SIZE

조건 누락과 검증 한계

#조건고정 코드의 경로해석 범위
01init == NULL첫 순회에서 callback 생략descriptor 자체는 다음 순회에 남음
02entry == NULL자동 시작 생략; start_app()도 즉시 반환init-only app은 thread 없음
03NO_AUTOSTART둘째 순회에서 자동 시작 생략이름으로 명시적 시작은 가능
04이름 검색 불일치app_start_by_name()이 ERR_NOT_FOUND일치 시 NO_ERROR가 thread 생성 증명은 아님
05thread_create()의 실패 가능성여기에는 반환 포인터 검사 없이 detach/resume·join 진행안전한 실패 복구를 단정하지 않음

이 소스는 각 init callback을 void로 호출하며 실패 코드를 수집하지 않는다. 따라서 모든 app 초기화의 일괄 성공/실패 판정을 그림에 넣지 않는다.

그림과 표를 대조할 고정 원문

이 페이지에 보존된 두 번호별 app/app.c 발췌와 같은 commit의 app.h를 함께 읽는다.

#주제고정 원문확인할 식·호출
01descriptor·flag 정의app.h:27–45__SECTION("apps"), 두 flag, 5개 필드
02경계·두 순회app.c:16–37__start_apps, 모든 init 선행, entry·flag 조건
03thread entry·stackapp.c:39–64entry(app,NULL), stack 선택, detach·join 분기
04명시적 시작app.c:66–78이름 검색, start_app(), ERR_NOT_FOUND

세 종류의 descriptor를 구분해 확인

  1. 01
    정적 범위 읽기

    시험 빌드의 map 또는 symbol table에서 _app_*, __start_apps, __stop_apps의 포함 여부를 대조한다. 특정 보드의 결과를 고정 소스의 보편적 결과로 일반화하지 않는다.

  2. 02
    init-only app 추적

    init만 있는 descriptor를 첫 순회에서 관찰하고 둘째 순회에서 thread 생성이 생략되는지 확인한다. callback 순서와 thread 실행 순서를 분리해 기록한다.

  3. 03
    autostart flag 비교

    entry가 있는 app에서 APP_FLAG_NO_AUTOSTART 유무를 비교한다. 자동 경로의 detach와 명시적 app_start_by_name()의 detached 선택도 별도로 확인한다.

원문과 다음 글