get_type_offset/
get-type-offset.rs

1/*
2  Copyright (c) 2024-present, Alessandro Gario
3  All rights reserved.
4
5  This source code is licensed in accordance with the terms specified in
6  the LICENSE file found in the root directory of this source tree.
7*/
8
9use std::{env, fs::File, os::unix::fs::FileExt, path::Path};
10
11use btfparse::{Readable, Result as BTFResult, TypeInformation};
12
13struct ReadableFile {
14    file: File,
15}
16
17impl ReadableFile {
18    fn new(path: &Path) -> Self {
19        ReadableFile {
20            file: File::open(path).unwrap(),
21        }
22    }
23}
24
25impl Readable for ReadableFile {
26    fn read(&self, offset: u64, buffer: &mut [u8]) -> BTFResult<()> {
27        self.file
28            .read_exact_at(buffer, offset)
29            .map_err(|err| err.into())
30    }
31}
32
33fn main() {
34    let argument_list: Vec<String> = env::args().collect();
35    if argument_list.len() != 4 {
36        println!("Usage:\n\tget-type-offset /path/to/btf/file <type_name> <path>\n");
37        return;
38    }
39
40    let btf_file_path = Path::new(&argument_list[1]);
41    let btf_type_name = &argument_list[2];
42    let type_path = &argument_list[3];
43
44    println!("Opening BTF file: {btf_file_path:?}");
45
46    let vmlinux_btf_file = ReadableFile::new(btf_file_path);
47    let type_information = TypeInformation::new(&vmlinux_btf_file).unwrap();
48    let offset = type_information
49        .offset_of(type_information.id_of(btf_type_name).unwrap(), type_path)
50        .unwrap();
51
52    println!("{btf_type_name} => {type_path}: {offset:?}");
53}