Microsoft MVP성태의 닷넷 이야기
Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례 [링크 복사], [링크+제목 복사],
조회: 282
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  [98]  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11582정성태7/5/201827977.NET Framework: 784. C# - 제네릭 인자를 가진 타입을 생성하는 방법 [1]파일 다운로드1
11581정성태7/4/201825396Math: 34. GeoGebra 기하 (11) - 3대 작도 불능 문제의 하나인 임의 각의 3등분파일 다운로드1
11580정성태7/4/201822628Math: 33. GeoGebra 기하 (10) - 직각의 3등분파일 다운로드1
11579정성태7/4/201820337Math: 32. GeoGebra 기하 (9) - 임의의 선분을 한 변으로 갖는 정삼각형파일 다운로드1
11578정성태7/3/201820508Math: 31. GeoGebra 기하 (8) - 호(Arc)의 이등분파일 다운로드1
11577정성태7/3/201820678Math: 30. GeoGebra 기하 (7) - 각의 이등분파일 다운로드1
11576정성태7/3/201824031Math: 29. GeoGebra 기하 (6) - 대수의 4칙 연산파일 다운로드1
11575정성태7/2/201824870Math: 28. GeoGebra 기하 (5) - 선분을 n 등분하는 방법파일 다운로드1
11574정성태7/2/201823484Math: 27. GeoGebra 기하 (4) - 선분을 n 배 늘이는 방법파일 다운로드1
11573정성태7/2/201821125Math: 26. GeoGebra 기하 (3) - 평행선
11572정성태7/1/201820654.NET Framework: 783. C# 컴파일러가 허용하지 않는 (유효한) 코드를 컴파일해 테스트하는 방법
11571정성태7/1/201821777.NET Framework: 782. C# - JIRA에 등록된 Project의 Version 항목 추가하는 방법파일 다운로드1
11570정성태7/1/201823194Math: 25. GeoGebra 기하 (2) - 임의의 선분과 특정 점을 지나는 수직선파일 다운로드1
11569정성태7/1/201821206Math: 24. GeoGebra 기하 (1) - 수직 이등분선파일 다운로드1
11568정성태7/1/201833737Math: 23. GeoGebra 기하 - 컴퍼스와 자를 이용한 작도 프로그램 [1]
11567정성태6/28/201823964.NET Framework: 781. C# - OpenCvSharp 사용 시 포인터를 이용한 속도 향상파일 다운로드1
11566정성태6/28/201829147.NET Framework: 780. C# - JIRA REST API 사용 정리 (1) Basic 인증 [4]파일 다운로드1
11565정성태6/28/201827213.NET Framework: 779. C# 7.3에서 enum을 boxing 없이 int로 변환하기 - 세 번째 이야기파일 다운로드1
11564정성태6/27/201825483.NET Framework: 778. (Unity가 사용하는) 모노 런타임의 __makeref 오류
11563정성태6/27/201821985개발 환경 구성: 386. .NET Framework Native compiler 프리뷰 버전 사용법 [2]
11562정성태6/26/201821768개발 환경 구성: 385. 레지스트리에 등록된 원격지 스크립트 COM 객체 실행 방법
11561정성태6/26/201835270.NET Framework: 777. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! [8]파일 다운로드1
11560정성태6/25/201826322.NET Framework: 776. C# 7.3 - 초기화 식에서 변수 사용 가능(expression variables in initializers)파일 다운로드1
11559정성태6/25/201834299개발 환경 구성: 384. 영문 설정의 Windows 10 명령행 창(cmd.exe)의 한글 지원 [6]
11558정성태6/24/201827685.NET Framework: 775. C# 7.3 - unmanaged(blittable) 제네릭 제약파일 다운로드1
11557정성태6/22/201824932.NET Framework: 774. C# - blittable 타입이란?파일 다운로드1
... 91  92  93  94  95  96  97  [98]  99  100  101  102  103  104  105  ...