Microsoft MVP성태의 닷넷 이야기
Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례 [링크 복사], [링크+제목 복사],
조회: 147
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

eBPF - __attribute__((preserve_access_index)) 활용 사례

지난 글에서,

eBPF (bpf2go) - __attribute__((preserve_access_index)) 사용법
; https://www.sysnet.pe.kr/2/0/14016

preserve_access_index 속성에 대해 알아봤는데요, 단지 적절한 활용 사례를 찾을 수는 없었습니다. 그런데, 아래의 글에서 그 의미를 찾을 수 있군요. ^^

BPF CO-RE reference guide / Handling incompatible field and type changes
; https://nakryiko.com/posts/bpf-core-reference-guide/#handling-incompatible-field-and-type-changes

위의 글에서는 task_struct를 예로 들고 있지만, 제 경우에는 struct iov_iter 구조체로 설명해 보겠습니다. 해당 구조체는 커널 5.15 버전에서는 이렇게 정의돼 있는데요,

// 커널 5.15 버전의 vmlinux.h 헤더 파일에서 발췌

struct iov_iter {
        u8 iter_type;
        bool nofault;
        bool data_source;
        size_t iov_offset;
        size_t count;
        union {
                const struct iovec *iov;
                const struct kvec *kvec;
                const struct bio_vec *bvec;
                struct xarray *xarray;
                struct pipe_inode_info *pipe;
        };
        union {
                long unsigned int nr_segs;
                struct {
                        unsigned int head;
                        unsigned int start_head;
                };
                loff_t xarray_start;
        };
};

위의 구조체에 있는 iov 필드를 접근하는 코드는 다음과 같이 작성할 수 있습니다.

const struct iovec *iov = (const struct iovec *)BPF_CORE_READ(iter, iov);

문제는, (변경이 발생한 정확한 버전은 알 수 없지만) 커널 6.14 버전에서는 다음과 같이 구조체가 변경되었다는 점입니다.

// 커널 6.14 버전의 vmlinux.h 헤더 파일에서 발췌

struct iov_iter {
        u8 iter_type;
        bool nofault;
        bool data_source;
        size_t iov_offset;
        union {
                struct iovec __ubuf_iovec;
                struct {
                        union {
                                const struct iovec *__iov;
                                const struct kvec *kvec;
                                const struct bio_vec *bvec;
                                const struct folio_queue *folioq;
                                struct xarray *xarray;
                                void *ubuf;
                        };
                        size_t count;
                };
        };
        union {
                long unsigned int nr_segs;
                u8 folioq_slot;
                loff_t xarray_start;
        };
};

그래서 이전 코드로 컴파일한 eBPF 바이너리를 커널 6.14 버전에서 (실행이 아닌) 로드하면 다음과 같은 오류가 발생합니다.

bad CO-RE relocation: invalid func unknown#195896080 (85 line(s) omitted)

바로 이 문제를 해결할 수 있는 방안이 preserve_access_index 속성입니다.




문제 해결을 위해 가장 먼저 해야 할 것이, 해당 필드가 없는 환경에서도 eBPF 프로그램을 로딩할 수 있게 만드는 것입니다. 이 문제의 원인은 결국 iov 필드를 접근하는 코드가 있다는 것인데요,

// 이렇게만 코딩하면 로딩 시 "bad CO-RE relocation" 오류 발생

iov = (const struct iovec *)BPF_CORE_READ(iter, iov);

이것을 다음과 같이 bpf_core_field_exists를 함께 사용하면,

const struct iovec *iov = NULL;
if (bpf_core_field_exists(iter->iov)) {
    iov = (const struct iovec *)BPF_CORE_READ(iter, iov);
} else {
    // ... __iov 필드로 접근
}

이제 로딩 시 문제가 없게 됩니다. 여기서 중요한 것은, bpf_core_field_exists 함수의 사용이 실행 시 발생하는 것이 아니고, eBPF 로더가 검증하는 순간에 도움을 주는 용도로 사용된다는 점입니다. 그래서 위의 코드는 검증 단계에서 bpf_core_field_exists 판정이 false라면 그 블록 내의 코드를 아예 버리게 되고, 결국 처음부터 저 코드가 없었던 것처럼 JIT 컴파일이 이뤄진 후 커널에 로딩돼 실행되는 식입니다.

그렇다면, 이제 다음과 같이 작성하면 되는 걸까요?

if (bpf_core_field_exists(iter->iov)) {
    iov = (const struct iovec *)BPF_CORE_READ(iter, iov);
} else {
    iov = (const struct iovec *)BPF_CORE_READ(iter, __iov);
}

아쉽게도 저렇게 작성하면, 이제는 컴파일 단계에서부터 오류가 발생하는데, 환경에 따라 달라지게 됩니다. 즉, 커널 5.15 버전의 환경에서 빌드한다면 __iov 필드를 iov_iter 구조체에서 찾을 수 없다는 컴파일 오류가 발생할 것이고,

error: no member named '__iov' in 'struct iov_iter'
   91 |         iov = (const struct iovec *)BPF_CORE_READ(iter, __iov);
      |                                     ~~~~~~~~~~~~~~~~~~~~^~~~~~

반대로 커널 6.14 버전의 환경에서 빌드한다면 iov 필드를 찾을 수 없다는 컴파일 오류가 발생할 것입니다.

당연하겠죠? ^^ 자, 그럼 컴파일 환경이 5.15라고 가정해 보겠습니다. 그렇다면 여기서 해결해야 할 것은 컴파일 시점에 "__iov" 필드를 사용해도 문제가 없을 다른 방법을 찾아야 하는 건데요, 바로 이럴 때 preserve_access_index 속성을 사용한 구조체를 다음과 같이 정의해 사용하면 됩니다.

struct iov_iter___new {
    const struct iovec *__iov;
} __attribute__((preserve_access_index));

이렇게 정의한 구조체로 __iov 필드에 접근하도록 다음과 같이 보완하면,

const struct iovec *iov = NULL;
if (bpf_core_field_exists(iter->iov)) {
    // 기존 iov 필드로 접근 (커널 5.15 버전)
    iov = (const struct iovec *)BPF_CORE_READ(iter, iov);
} else {
    // preserve_access_index 속성을 적용한 구조체로 __iov 필드에 접근 (커널 6.14 버전)
    struct iov_iter___new *new_iter = (struct iov_iter___new *)iter;
    iov = (const struct iovec *)BPF_CORE_READ(new_iter, __iov);
}

컴파일도 잘 되고, 런타임 시에 커널 5.15 버전과 6.14 버전 모두에서 정상적으로 동작합니다. ^^ 아마도 preserve_access_index 속성이 없었다면 저런 식의 코드 작성은 불가능했을 겁니다.

참고로, struct iov_iter의 구조체라면 다른 우회 방법도 있습니다. iov 필드가 union으로 정의돼 있으므로 다른 필드를 통해 접근하는 건데요, 예를 들어 kvec 필드를 통해 이렇게도 구할 수 있습니다.

const struct kvec *kvec = (const struct kvec *)BPF_CORE_READ(iter, kvec);
const struct iovec *iov2 = (const struct iovec *)kvec;

실제로 위에서 구한 iov2 포인터와 이전 코드의 iov 포인터는 동일한 값을 가집니다.




한 가지 유의할 점은 preserve_access_index 속성이 적용된 구조체가 기존의 다른 구조체를 대신하는 용도로 사용될 때, 반드시 그 이름에 "___" 밑줄 3개를 접미사로 추가해야 한다는 점입니다. 가령 "iov_iter___my" 또는 "iov_iter___"라고 짓는 것은 문제없지만 (밑줄 2개가 들어간) "iov_iter__new"로 이름을 지으면 안 됩니다.

그런 의미에서 지난 글에 정의한 my_task_struct 예제를 다음과 같이 수정하면 문제없이 컴파일 및 로드가 됩니다.

struct task_struct___my {
    unsigned int flags;
    const struct cred *cred;
} __attribute__((preserve_access_index));

SEC("tracepoint/syscalls/sys_enter_execve")
int sys_enter_execve(struct pt_regs *ctx) {
    struct task_struct___my *current_task = (struct task_struct___my *)bpf_get_current_task();
    unsigned int task_flags = BPF_CORE_READ(current_task, flags); // 정상 동작

    bpf_printk("task_flags == %d\n", task_flags);

    return 0;
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/3/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12034정성태10/12/201922285개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201927342개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201922425.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/201921609오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201928558.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201928015제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201924773.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201917589오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201925496.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201923662제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201925677.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201926360.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201928896개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201946439도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201928889VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201922333Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201921614오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201925579오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
12016정성태9/5/201923946오류 유형: 565. git fetch - warning: 'C:\ProgramData/Git/config' has a dubious owner: '(unknown)'.
12015정성태9/3/201931582개발 환경 구성: 457. 윈도우 응용 프로그램의 Socket 연결 시 time-out 시간 제어
12014정성태9/3/201924424개발 환경 구성: 456. 명령행에서 AWS, Azure 등의 원격 저장소에 파일 관리하는 방법 - cyberduck/duck 소개
12013정성태8/28/201928072개발 환경 구성: 455. 윈도우에서 (테스트) 인증서 파일 만드는 방법 [3]
12012정성태8/28/201932848.NET Framework: 859. C# - HttpListener를 이용한 HTTPS 통신 방법
12011정성태8/27/201932185사물인터넷: 57. C# - Rapsberry Pi Zero W와 PC 간 Bluetooth 통신 예제 코드파일 다운로드1
12010정성태8/27/201924086VS.NET IDE: 138. VSIX - DTE.ItemOperations.NewFile 메서드에서 템플릿 이름을 다국어로 설정하는 방법
12009정성태8/26/201925642.NET Framework: 858. C#/Windows - Clipboard(Ctrl+C, Ctrl+V)가 동작하지 않는다면?파일 다운로드1
... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...