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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  73  74  [75]  ...
NoWriterDateCnt.TitleFile(s)
12159정성태2/26/202017931오류 유형: 596. Visual Studio - The project needs to include ATL support
12158정성태2/25/202022597디버깅 기술: 165. C# - Marshal.GetIUnknownForObject/GetIDispatchForObject 사용 시 메모리 누수(Memory Leak) 발생파일 다운로드1
12157정성태2/25/202021562디버깅 기술: 164. C# - Marshal.GetNativeVariantForObject 사용 시 메모리 누수(Memory Leak) 발생 및 해결 방법파일 다운로드1
12156정성태2/25/202019983오류 유형: 595. LINK : warning LNK4098: defaultlib 'nafxcw.lib' conflicts with use of other libs; use /NODEFAULTLIB:library
12155정성태2/25/202020926오류 유형: 594. Warning NU1701 - This package may not be fully compatible with your project
12154정성태2/25/202019446오류 유형: 593. warning LNK4070: /OUT:... directive in .EXP differs from output filename
12153정성태2/23/202024842.NET Framework: 898. Trampoline을 이용한 후킹의 한계파일 다운로드1
12152정성태2/23/202021669.NET Framework: 897. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 세 번째 이야기(Trampoline 후킹)파일 다운로드1
12151정성태2/22/202024412.NET Framework: 896. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 - 두 번째 이야기 (원본 함수 호출)파일 다운로드1
12150정성태2/21/202024471.NET Framework: 895. C# - Win32 API를 Trampoline 기법을 이용해 C# 메서드로 가로채는 방법 [1]파일 다운로드1
12149정성태2/20/202021339.NET Framework: 894. eBEST C# XingAPI 래퍼 - 연속 조회 처리 방법 [1]
12148정성태2/19/202026023디버깅 기술: 163. x64 환경에서 구현하는 다양한 Trampoline 기법 [1]
12147정성태2/19/202021208디버깅 기술: 162. x86/x64의 기계어 코드 최대 길이
12146정성태2/18/202022395.NET Framework: 893. eBEST C# XingAPI 래퍼 - 로그인 처리파일 다운로드1
12145정성태2/18/202024124.NET Framework: 892. eBEST C# XingAPI 래퍼 - Sqlite 지원 추가파일 다운로드1
12144정성태2/13/202024296.NET Framework: 891. 실행 시에 메서드 가로채기 - CLR Injection: Runtime Method Replacer 개선 - 두 번째 이야기파일 다운로드1
12143정성태2/13/202018772.NET Framework: 890. 상황별 GetFunctionPointer 반환값 정리 - x64파일 다운로드1
12142정성태2/12/202022854.NET Framework: 889. C# 코드로 접근하는 MethodDesc, MethodTable파일 다운로드1
12141정성태2/10/202021831.NET Framework: 888. C# - ASP.NET Core 웹 응용 프로그램의 출력 가로채기 [2]파일 다운로드1
12140정성태2/10/202023006.NET Framework: 887. C# - ASP.NET 웹 응용 프로그램의 출력 가로채기파일 다운로드1
12139정성태2/9/202022655.NET Framework: 886. C# - Console 응용 프로그램에서 UI 스레드 구현 방법
12138정성태2/9/202028961.NET Framework: 885. C# - 닷넷 응용 프로그램에서 SQLite 사용 [6]파일 다운로드1
12137정성태2/9/202020777오류 유형: 592. [AhnLab] 경고 - 디버거 실행을 탐지했습니다.
12136정성태2/6/202022351Windows: 168. Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
12135정성태2/6/202028034개발 환경 구성: 468. Nuget 패키지의 로컬 보관 폴더를 옮기는 방법 [2]
12134정성태2/5/202025381.NET Framework: 884. eBEST XingAPI의 C# 래퍼 버전 - XingAPINet Nuget 패키지 [5]파일 다운로드1
... 61  62  63  64  65  66  67  68  69  70  71  72  73  74  [75]  ...