Microsoft MVP성태의 닷넷 이야기
Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례 [링크 복사], [링크+제목 복사],
조회: 144
글쓴 사람
정성태 (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)
11884정성태5/5/201925752.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201931086.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201927802.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201927787오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201923751오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
11879정성태4/24/201933393.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others파일 다운로드2
11878정성태4/22/201927497.NET Framework: 824. (번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff파일 다운로드1
11877정성태4/22/201927999.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas파일 다운로드1
11876정성태4/21/201924699.NET Framework: 822. (번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others파일 다운로드1
11875정성태4/21/201927645오류 유형: 530. Visual Studo에서 .NET Core 프로젝트를 열 때 "One or more errors occurred." 오류 발생
11874정성태4/20/201927759.NET Framework: 821. (번역글) .NET Internals Cookbook Part 6 - Object internals파일 다운로드1
11873정성태4/19/201926522.NET Framework: 820. (번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers파일 다운로드1
11872정성태4/17/201927772.NET Framework: 819. (번역글) .NET Internals Cookbook Part 4 - Type members파일 다운로드1
11871정성태4/16/201924040.NET Framework: 818. (번역글) .NET Internals Cookbook Part 3 - Initialization tricks [3]파일 다운로드1
11870정성태4/16/201924119.NET Framework: 817. Process.Start로 실행한 콘솔 프로그램의 출력 결과를 얻는 방법파일 다운로드1
11869정성태4/15/201931585.NET Framework: 816. (번역글) .NET Internals Cookbook Part 2 - GC-related things [2]파일 다운로드2
11868정성태4/15/201925422.NET Framework: 815. CER(Constrained Execution Region)이란?파일 다운로드1
11867정성태4/15/201924482.NET Framework: 814. Critical Finalizer와 SafeHandle의 사용 의미파일 다운로드1
11866정성태4/9/201926833Windows: 159. 네트워크 공유 폴더(net use)에 대한 인증 정보는 언제까지 유효할까요?
11865정성태4/9/201923786오류 유형: 529. 제어판 - C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools is not accessible.
11864정성태4/9/201922360오류 유형: 528. '...' could be '0': this does not adhere to the specification for the function '...'
11863정성태4/9/201922329디버깅 기술: 127. windbg - .NET x64 EXE의 EntryPoint
11862정성태4/7/201923901개발 환경 구성: 437. .NET EXE의 ASLR 기능을 끄는 방법
11861정성태4/6/201922996디버깅 기술: 126. windbg - .NET x86 CLR2/CLR4 EXE의 EntryPoint
11860정성태4/5/201928722오류 유형: 527. Visual C++ 컴파일 오류 - error C2220: warning treated as error - no 'object' file generated
11859정성태4/4/201925276디버깅 기술: 125. WinDbg로 EXE의 EntryPoint에서 BP 거는 방법
... 76  77  78  79  80  81  82  83  84  85  [86]  87  88  89  90  ...