Microsoft MVP성태의 닷넷 이야기
Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례 [링크 복사], [링크+제목 복사],
조회: 292
글쓴 사람
정성태 (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)
11455정성태2/17/201822621오류 유형: 451. ASP.NET Core - An error occurred during the compilation of a resource required to process this request.
11454정성태2/12/201831989기타: 71. 만료된 Office 제품 키를 변경하는 방법
11453정성태1/31/201823380오류 유형: 450. Azure Cloud Services(classic) 배포 시 "Certificate with thumbprint ... doesn't exist." 오류 발생
11452정성태1/31/201828939기타: 70. 재현 가능한 최소한의 예제 프로젝트란? [3]파일 다운로드1
11451정성태1/24/201822471디버깅 기술: 111. windbg - x86 메모리 덤프 분석 시 닷넷 메서드의 호출 인자 값 확인
11450정성태1/24/201839901Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법 [1]
11449정성태1/23/201825856오류 유형: 449. 단위 테스트 - Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.VideoRecorderEngine' or one of its dependencies. [1]
11448정성태1/20/201823913오류 유형: 448. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS0619 관련 오류 발생
11447정성태1/20/201825268.NET Framework: 730. dotnet user-secrets 명령어 [2]파일 다운로드1
11446정성태1/20/201825107.NET Framework: 729. windbg로 살펴보는 GC heap의 Segment 구조 [2]파일 다운로드1
11445정성태1/20/201823200.NET Framework: 728. windbg - 눈으로 확인하는 Workstation GC / Server GC
11444정성태1/19/201822932VS.NET IDE: 125. Visual Studio에서 Selenium WebDriver를 이용한 웹 브라우저 단위 테스트 구성파일 다운로드1
11443정성태1/18/201825514VC++: 124. libuv 모듈 살펴 보기
11442정성태1/18/201821329개발 환경 구성: 353. ASP.NET Core 프로젝트의 "Enable unmanaged code debugging" 옵션 켜는 방법
11441정성태1/18/201819332오류 유형: 447. ASP.NET Core 배포 오류 - Ensure that restore has run and that you have included '...' in the TargetFrameworks for your project.
11440정성태1/17/201822788.NET Framework: 727. ASP.NET의 HttpContext.Current 구현에 대응하는 ASP.NET Core의 IHttpContextAccessor/HttpContextAccessor 사용법파일 다운로드1
11439정성태1/17/201829366기타: 69. C# - CPU 100% 부하 주는 프로그램파일 다운로드1
11438정성태1/17/201822237오류 유형: 446. Error CS0234 The type or namespace name 'ITuple' does not exist in the namespace
11437정성태1/17/201822111VS.NET IDE: 124. Platform Toolset 설정에 따른 Visual C++의 헤더 파일 기본 디렉터리
11436정성태1/16/201824671개발 환경 구성: 352. ASP.NET Core (EXE) 프로세스가 IIS에서 호스팅되는 방법 - ASP.NET Core Module(AspNetCoreModule) [4]
11435정성태1/16/201826370개발 환경 구성: 351. OWIN 웹 서버(EXE)를 IIS에서 호스팅하는 방법 - HttpPlatformHandler (Reverse Proxy)파일 다운로드2
11434정성태1/15/201827744개발 환경 구성: 350. 사용자 정의 웹 서버(EXE)를 IIS에서 호스팅하는 방법 - HttpPlatformHandler (Reverse Proxy)파일 다운로드2
11433정성태1/15/201825397개발 환경 구성: 349. dotnet ef 명령어 사용을 위한 준비
11432정성태1/11/201833078.NET Framework: 726. WPF + Direct2D + SharpDX 출력 C# 예제파일 다운로드2
11431정성태1/11/201828664.NET Framework: 725. C# - 동기 방식이면서 비동기 메서드(awaitable)처럼 구현한 사례 [9]
11430정성태1/10/201831949.NET Framework: 724. WPF + Direct2D 출력 C# 예제 [2]파일 다운로드1
... 91  92  93  94  95  96  97  98  99  100  101  102  [103]  104  105  ...