btf.rs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. use alloc::{
  2. borrow::{Cow, ToOwned as _},
  3. format,
  4. string::String,
  5. vec,
  6. vec::Vec,
  7. };
  8. use core::{ffi::CStr, mem, ptr};
  9. use bytes::BufMut;
  10. use log::debug;
  11. use object::{Endianness, SectionIndex};
  12. use crate::{
  13. btf::{
  14. info::{FuncSecInfo, LineSecInfo},
  15. relocation::Relocation,
  16. Array, BtfEnum, BtfKind, BtfMember, BtfType, Const, Enum, FuncInfo, FuncLinkage, Int,
  17. IntEncoding, LineInfo, Struct, Typedef, Union, VarLinkage,
  18. },
  19. generated::{btf_ext_header, btf_header},
  20. util::{bytes_of, HashMap},
  21. Object,
  22. };
  23. pub(crate) const MAX_RESOLVE_DEPTH: usize = 32;
  24. pub(crate) const MAX_SPEC_LEN: usize = 64;
  25. /// The error type returned when `BTF` operations fail.
  26. #[derive(thiserror::Error, Debug)]
  27. pub enum BtfError {
  28. #[cfg(feature = "std")]
  29. /// Error parsing file
  30. #[error("error parsing {path}")]
  31. FileError {
  32. /// file path
  33. path: std::path::PathBuf,
  34. /// source of the error
  35. #[source]
  36. error: std::io::Error,
  37. },
  38. /// Error parsing BTF header
  39. #[error("error parsing BTF header")]
  40. InvalidHeader,
  41. /// invalid BTF type info segment
  42. #[error("invalid BTF type info segment")]
  43. InvalidTypeInfo,
  44. /// invalid BTF relocation info segment
  45. #[error("invalid BTF relocation info segment")]
  46. InvalidRelocationInfo,
  47. /// invalid BTF type kind
  48. #[error("invalid BTF type kind `{kind}`")]
  49. InvalidTypeKind {
  50. /// type kind
  51. kind: u32,
  52. },
  53. /// invalid BTF relocation kind
  54. #[error("invalid BTF relocation kind `{kind}`")]
  55. InvalidRelocationKind {
  56. /// type kind
  57. kind: u32,
  58. },
  59. /// invalid BTF string offset
  60. #[error("invalid BTF string offset: {offset}")]
  61. InvalidStringOffset {
  62. /// offset
  63. offset: usize,
  64. },
  65. /// invalid BTF info
  66. #[error("invalid BTF info, offset: {offset} len: {len} section_len: {section_len}")]
  67. InvalidInfo {
  68. /// offset
  69. offset: usize,
  70. /// length
  71. len: usize,
  72. /// section length
  73. section_len: usize,
  74. },
  75. /// invalid BTF line infos
  76. #[error("invalid BTF line info, offset: {offset} len: {len} section_len: {section_len}")]
  77. InvalidLineInfo {
  78. /// offset
  79. offset: usize,
  80. /// length
  81. len: usize,
  82. /// section length
  83. section_len: usize,
  84. },
  85. /// unknown BTF type id
  86. #[error("Unknown BTF type id `{type_id}`")]
  87. UnknownBtfType {
  88. /// type id
  89. type_id: u32,
  90. },
  91. /// unexpected btf type id
  92. #[error("Unexpected BTF type id `{type_id}`")]
  93. UnexpectedBtfType {
  94. /// type id
  95. type_id: u32,
  96. },
  97. /// unknown BTF type
  98. #[error("Unknown BTF type `{type_name}`")]
  99. UnknownBtfTypeName {
  100. /// type name
  101. type_name: String,
  102. },
  103. /// maximum depth reached resolving BTF type
  104. #[error("maximum depth reached resolving BTF type")]
  105. MaximumTypeDepthReached {
  106. /// type id
  107. type_id: u32,
  108. },
  109. #[cfg(feature = "std")]
  110. /// Loading the btf failed
  111. #[error("the BPF_BTF_LOAD syscall failed. Verifier output: {verifier_log}")]
  112. LoadError {
  113. /// The [`std::io::Error`] returned by the `BPF_BTF_LOAD` syscall.
  114. #[source]
  115. io_error: std::io::Error,
  116. /// The error log produced by the kernel verifier.
  117. verifier_log: crate::VerifierLog,
  118. },
  119. /// offset not found for symbol
  120. #[error("Offset not found for symbol `{symbol_name}`")]
  121. SymbolOffsetNotFound {
  122. /// name of the symbol
  123. symbol_name: String,
  124. },
  125. /// btf type that is not VAR found in DATASEC
  126. #[error("BTF type that is not VAR was found in DATASEC")]
  127. InvalidDatasec,
  128. /// unable to determine the size of section
  129. #[error("Unable to determine the size of section `{section_name}`")]
  130. UnknownSectionSize {
  131. /// name of the section
  132. section_name: String,
  133. },
  134. /// unable to get symbol name
  135. #[error("Unable to get symbol name")]
  136. InvalidSymbolName,
  137. }
  138. /// Available BTF features
  139. #[derive(Default, Debug)]
  140. pub struct BtfFeatures {
  141. btf_func: bool,
  142. btf_func_global: bool,
  143. btf_datasec: bool,
  144. btf_float: bool,
  145. btf_decl_tag: bool,
  146. btf_type_tag: bool,
  147. btf_enum64: bool,
  148. }
  149. impl BtfFeatures {
  150. #[doc(hidden)]
  151. pub fn new(
  152. btf_func: bool,
  153. btf_func_global: bool,
  154. btf_datasec: bool,
  155. btf_float: bool,
  156. btf_decl_tag: bool,
  157. btf_type_tag: bool,
  158. btf_enum64: bool,
  159. ) -> Self {
  160. BtfFeatures {
  161. btf_func,
  162. btf_func_global,
  163. btf_datasec,
  164. btf_float,
  165. btf_decl_tag,
  166. btf_type_tag,
  167. btf_enum64,
  168. }
  169. }
  170. /// Returns true if the BTF_TYPE_FUNC is supported.
  171. pub fn btf_func(&self) -> bool {
  172. self.btf_func
  173. }
  174. /// Returns true if the BTF_TYPE_FUNC_GLOBAL is supported.
  175. pub fn btf_func_global(&self) -> bool {
  176. self.btf_func_global
  177. }
  178. /// Returns true if the BTF_TYPE_DATASEC is supported.
  179. pub fn btf_datasec(&self) -> bool {
  180. self.btf_datasec
  181. }
  182. /// Returns true if the BTF_FLOAT is supported.
  183. pub fn btf_float(&self) -> bool {
  184. self.btf_float
  185. }
  186. /// Returns true if the BTF_DECL_TAG is supported.
  187. pub fn btf_decl_tag(&self) -> bool {
  188. self.btf_decl_tag
  189. }
  190. /// Returns true if the BTF_TYPE_TAG is supported.
  191. pub fn btf_type_tag(&self) -> bool {
  192. self.btf_type_tag
  193. }
  194. /// Returns true if the BTF_KIND_FUNC_PROTO is supported.
  195. pub fn btf_kind_func_proto(&self) -> bool {
  196. self.btf_func && self.btf_decl_tag
  197. }
  198. /// Returns true if the BTF_KIND_ENUM64 is supported.
  199. pub fn btf_enum64(&self) -> bool {
  200. self.btf_enum64
  201. }
  202. }
  203. /// BPF Type Format metadata.
  204. ///
  205. /// BTF is a kind of debug metadata that allows eBPF programs compiled against one kernel version
  206. /// to be loaded into different kernel versions.
  207. ///
  208. /// Aya automatically loads BTF metadata if you use `Ebpf::load_file`. You
  209. /// only need to explicitly use this type if you want to load BTF from a non-standard
  210. /// location or if you are using `Ebpf::load`.
  211. #[derive(Clone, Debug)]
  212. pub struct Btf {
  213. header: btf_header,
  214. strings: Vec<u8>,
  215. types: BtfTypes,
  216. _endianness: Endianness,
  217. }
  218. impl Btf {
  219. /// Creates a new empty instance with its header initialized
  220. pub fn new() -> Btf {
  221. Btf {
  222. header: btf_header {
  223. magic: 0xeb9f,
  224. version: 0x01,
  225. flags: 0x00,
  226. hdr_len: 0x18,
  227. type_off: 0x00,
  228. type_len: 0x00,
  229. str_off: 0x00,
  230. str_len: 0x00,
  231. },
  232. strings: vec![0],
  233. types: BtfTypes::default(),
  234. _endianness: Endianness::default(),
  235. }
  236. }
  237. pub(crate) fn is_empty(&self) -> bool {
  238. // the first one is awlays BtfType::Unknown
  239. self.types.types.len() < 2
  240. }
  241. pub(crate) fn types(&self) -> impl Iterator<Item = &BtfType> {
  242. self.types.types.iter()
  243. }
  244. /// Adds a string to BTF metadata, returning an offset
  245. pub fn add_string(&mut self, name: &str) -> u32 {
  246. let str = name.bytes().chain(core::iter::once(0));
  247. let name_offset = self.strings.len();
  248. self.strings.extend(str);
  249. self.header.str_len = self.strings.len() as u32;
  250. name_offset as u32
  251. }
  252. /// Adds a type to BTF metadata, returning a type id
  253. pub fn add_type(&mut self, btf_type: BtfType) -> u32 {
  254. let size = btf_type.type_info_size() as u32;
  255. let type_id = self.types.len();
  256. self.types.push(btf_type);
  257. self.header.type_len += size;
  258. self.header.str_off += size;
  259. type_id as u32
  260. }
  261. /// Loads BTF metadata from `/sys/kernel/btf/vmlinux`.
  262. #[cfg(feature = "std")]
  263. pub fn from_sys_fs() -> Result<Btf, BtfError> {
  264. Btf::parse_file("/sys/kernel/btf/vmlinux", Endianness::default())
  265. }
  266. /// Loads BTF metadata from the given `path`.
  267. #[cfg(feature = "std")]
  268. pub fn parse_file<P: AsRef<std::path::Path>>(
  269. path: P,
  270. endianness: Endianness,
  271. ) -> Result<Btf, BtfError> {
  272. use std::{borrow::ToOwned, fs};
  273. let path = path.as_ref();
  274. Btf::parse(
  275. &fs::read(path).map_err(|error| BtfError::FileError {
  276. path: path.to_owned(),
  277. error,
  278. })?,
  279. endianness,
  280. )
  281. }
  282. /// Parses BTF from binary data of the given endianness
  283. pub fn parse(data: &[u8], endianness: Endianness) -> Result<Btf, BtfError> {
  284. if data.len() < mem::size_of::<btf_header>() {
  285. return Err(BtfError::InvalidHeader);
  286. }
  287. // safety: btf_header is POD so read_unaligned is safe
  288. let header = unsafe { read_btf_header(data) };
  289. let str_off = header.hdr_len as usize + header.str_off as usize;
  290. let str_len = header.str_len as usize;
  291. if str_off + str_len > data.len() {
  292. return Err(BtfError::InvalidHeader);
  293. }
  294. let strings = data[str_off..str_off + str_len].to_vec();
  295. let types = Btf::read_type_info(&header, data, endianness)?;
  296. Ok(Btf {
  297. header,
  298. strings,
  299. types,
  300. _endianness: endianness,
  301. })
  302. }
  303. fn read_type_info(
  304. header: &btf_header,
  305. data: &[u8],
  306. endianness: Endianness,
  307. ) -> Result<BtfTypes, BtfError> {
  308. let hdr_len = header.hdr_len as usize;
  309. let type_off = header.type_off as usize;
  310. let type_len = header.type_len as usize;
  311. let base = hdr_len + type_off;
  312. if base + type_len > data.len() {
  313. return Err(BtfError::InvalidTypeInfo);
  314. }
  315. let mut data = &data[base..base + type_len];
  316. let mut types = BtfTypes::default();
  317. while !data.is_empty() {
  318. // Safety:
  319. // read() reads POD values from ELF, which is sound, but the values can still contain
  320. // internally inconsistent values (like out of bound offsets and such).
  321. let ty = unsafe { BtfType::read(data, endianness)? };
  322. data = &data[ty.type_info_size()..];
  323. types.push(ty);
  324. }
  325. Ok(types)
  326. }
  327. pub(crate) fn string_at(&self, offset: u32) -> Result<Cow<'_, str>, BtfError> {
  328. let btf_header {
  329. hdr_len,
  330. mut str_off,
  331. str_len,
  332. ..
  333. } = self.header;
  334. str_off += hdr_len;
  335. if offset >= str_off + str_len {
  336. return Err(BtfError::InvalidStringOffset {
  337. offset: offset as usize,
  338. });
  339. }
  340. let offset = offset as usize;
  341. let nul = self.strings[offset..]
  342. .iter()
  343. .position(|c| *c == 0u8)
  344. .ok_or(BtfError::InvalidStringOffset { offset })?;
  345. let s = CStr::from_bytes_with_nul(&self.strings[offset..=offset + nul])
  346. .map_err(|_| BtfError::InvalidStringOffset { offset })?;
  347. Ok(s.to_string_lossy())
  348. }
  349. pub(crate) fn type_by_id(&self, type_id: u32) -> Result<&BtfType, BtfError> {
  350. self.types.type_by_id(type_id)
  351. }
  352. pub(crate) fn resolve_type(&self, root_type_id: u32) -> Result<u32, BtfError> {
  353. self.types.resolve_type(root_type_id)
  354. }
  355. pub(crate) fn type_name(&self, ty: &BtfType) -> Result<Cow<'_, str>, BtfError> {
  356. self.string_at(ty.name_offset())
  357. }
  358. pub(crate) fn err_type_name(&self, ty: &BtfType) -> Option<String> {
  359. self.string_at(ty.name_offset()).ok().map(String::from)
  360. }
  361. /// Returns a type id matching the type name and [BtfKind]
  362. pub fn id_by_type_name_kind(&self, name: &str, kind: BtfKind) -> Result<u32, BtfError> {
  363. for (type_id, ty) in self.types().enumerate() {
  364. if ty.kind() != kind {
  365. continue;
  366. }
  367. if self.type_name(ty)? == name {
  368. return Ok(type_id as u32);
  369. }
  370. continue;
  371. }
  372. Err(BtfError::UnknownBtfTypeName {
  373. type_name: name.to_owned(),
  374. })
  375. }
  376. pub(crate) fn type_size(&self, root_type_id: u32) -> Result<usize, BtfError> {
  377. let mut type_id = root_type_id;
  378. let mut n_elems = 1;
  379. for () in core::iter::repeat_n((), MAX_RESOLVE_DEPTH) {
  380. let ty = self.types.type_by_id(type_id)?;
  381. let size = match ty {
  382. BtfType::Array(Array { array, .. }) => {
  383. n_elems = array.len;
  384. type_id = array.element_type;
  385. continue;
  386. }
  387. other => {
  388. if let Some(size) = other.size() {
  389. size
  390. } else if let Some(next) = other.btf_type() {
  391. type_id = next;
  392. continue;
  393. } else {
  394. return Err(BtfError::UnexpectedBtfType { type_id });
  395. }
  396. }
  397. };
  398. return Ok((size * n_elems) as usize);
  399. }
  400. Err(BtfError::MaximumTypeDepthReached {
  401. type_id: root_type_id,
  402. })
  403. }
  404. /// Encodes the metadata as BTF format
  405. pub fn to_bytes(&self) -> Vec<u8> {
  406. // Safety: btf_header is POD
  407. let mut buf = unsafe { bytes_of::<btf_header>(&self.header).to_vec() };
  408. // Skip the first type since it's always BtfType::Unknown for type_by_id to work
  409. buf.extend(self.types.to_bytes());
  410. buf.put(self.strings.as_slice());
  411. buf
  412. }
  413. // This follows the same logic as libbpf's bpf_object__sanitize_btf() function.
  414. // https://github.com/libbpf/libbpf/blob/05f94ddbb837f5f4b3161e341eed21be307eaa04/src/libbpf.c#L2701
  415. //
  416. // Fixup: The loader needs to adjust values in the BTF before it's loaded into the kernel.
  417. // Sanitize: Replace an unsupported BTF type with a placeholder type.
  418. //
  419. // In addition to the libbpf logic, it performs some fixups to the BTF generated by bpf-linker
  420. // for Aya programs. These fixups are gradually moving into bpf-linker itself.
  421. pub(crate) fn fixup_and_sanitize(
  422. &mut self,
  423. section_infos: &HashMap<String, (SectionIndex, u64)>,
  424. symbol_offsets: &HashMap<String, u64>,
  425. features: &BtfFeatures,
  426. ) -> Result<(), BtfError> {
  427. // ENUM64 placeholder type needs to be added before we take ownership of
  428. // self.types to ensure that the offsets in the BtfHeader are correct.
  429. let placeholder_name = self.add_string("enum64_placeholder");
  430. let enum64_placeholder_id = (!features.btf_enum64
  431. && self.types().any(|t| t.kind() == BtfKind::Enum64))
  432. .then(|| {
  433. self.add_type(BtfType::Int(Int::new(
  434. placeholder_name,
  435. 1,
  436. IntEncoding::None,
  437. 0,
  438. )))
  439. });
  440. let mut types = mem::take(&mut self.types);
  441. for i in 0..types.types.len() {
  442. let t = &mut types.types[i];
  443. let kind = t.kind();
  444. match t {
  445. // Fixup PTR for Rust.
  446. //
  447. // LLVM emits names for Rust pointer types, which the kernel doesn't like.
  448. // While I figure out if this needs fixing in the Kernel or LLVM, we'll
  449. // do a fixup here.
  450. BtfType::Ptr(ptr) => {
  451. ptr.name_offset = 0;
  452. }
  453. // Sanitize VAR if they are not supported.
  454. BtfType::Var(v) if !features.btf_datasec => {
  455. *t = BtfType::Int(Int::new(v.name_offset, 1, IntEncoding::None, 0));
  456. }
  457. // Sanitize DATASEC if they are not supported.
  458. BtfType::DataSec(d) if !features.btf_datasec => {
  459. debug!("{}: not supported. replacing with STRUCT", kind);
  460. // STRUCT aren't allowed to have "." in their name, fixup this if needed.
  461. let mut name_offset = d.name_offset;
  462. let name = self.string_at(name_offset)?;
  463. // Handle any "." characters in struct names.
  464. // Example: ".maps"
  465. let fixed_name = name.replace('.', "_");
  466. if fixed_name != name {
  467. name_offset = self.add_string(&fixed_name);
  468. }
  469. let entries = core::mem::take(&mut d.entries);
  470. let members = entries
  471. .iter()
  472. .map(|e| {
  473. let mt = types.type_by_id(e.btf_type).unwrap();
  474. BtfMember {
  475. name_offset: mt.name_offset(),
  476. btf_type: e.btf_type,
  477. offset: e.offset * 8,
  478. }
  479. })
  480. .collect();
  481. // Must reborrow here because we borrow `types` immutably above.
  482. let t = &mut types.types[i];
  483. *t = BtfType::Struct(Struct::new(name_offset, members, entries.len() as u32));
  484. }
  485. // Fixup DATASEC.
  486. //
  487. // DATASEC sizes aren't always set by LLVM so we need to fix them
  488. // here before loading the btf to the kernel.
  489. BtfType::DataSec(d) if features.btf_datasec => {
  490. // Start DataSec Fixups
  491. let name = self.string_at(d.name_offset)?;
  492. let name = name.into_owned();
  493. // Handle any "/" characters in section names.
  494. // Example: "maps/hashmap"
  495. let fixed_name = name.replace('/', ".");
  496. if fixed_name != name {
  497. d.name_offset = self.add_string(&fixed_name);
  498. }
  499. // There are some cases when the compiler does indeed populate the size.
  500. if d.size > 0 {
  501. debug!("{} {}: size fixup not required", kind, name);
  502. } else {
  503. // We need to get the size of the section from the ELF file.
  504. // Fortunately, we cached these when parsing it initially
  505. // and we can this up by name in section_infos.
  506. let size = match section_infos.get(&name) {
  507. Some((_, size)) => size,
  508. None => {
  509. return Err(BtfError::UnknownSectionSize { section_name: name });
  510. }
  511. };
  512. debug!("{} {}: fixup size to {}", kind, name, size);
  513. d.size = *size as u32;
  514. // The Vec<btf_var_secinfo> contains BTF_KIND_VAR sections
  515. // that need to have their offsets adjusted. To do this,
  516. // we need to get the offset from the ELF file.
  517. // This was also cached during initial parsing and
  518. // we can query by name in symbol_offsets.
  519. let mut entries = mem::take(&mut d.entries);
  520. let mut fixed_section = d.clone();
  521. for e in entries.iter_mut() {
  522. if let BtfType::Var(var) = types.type_by_id(e.btf_type)? {
  523. let var_name = self.string_at(var.name_offset)?;
  524. if var.linkage == VarLinkage::Static {
  525. debug!(
  526. "{} {}: VAR {}: fixup not required",
  527. kind, name, var_name
  528. );
  529. continue;
  530. }
  531. let offset = match symbol_offsets.get(var_name.as_ref()) {
  532. Some(offset) => offset,
  533. None => {
  534. return Err(BtfError::SymbolOffsetNotFound {
  535. symbol_name: var_name.into_owned(),
  536. });
  537. }
  538. };
  539. e.offset = *offset as u32;
  540. debug!(
  541. "{} {}: VAR {}: fixup offset {}",
  542. kind, name, var_name, offset
  543. );
  544. } else {
  545. return Err(BtfError::InvalidDatasec);
  546. }
  547. }
  548. fixed_section.entries = entries;
  549. // Must reborrow here because we borrow `types` immutably above.
  550. let t = &mut types.types[i];
  551. *t = BtfType::DataSec(fixed_section);
  552. }
  553. }
  554. // Fixup FUNC_PROTO.
  555. BtfType::FuncProto(ty) if features.btf_func => {
  556. for (i, param) in ty.params.iter_mut().enumerate() {
  557. if param.name_offset == 0 && param.btf_type != 0 {
  558. param.name_offset = self.add_string(&format!("param{i}"));
  559. }
  560. }
  561. }
  562. // Sanitize FUNC_PROTO.
  563. BtfType::FuncProto(ty) if !features.btf_func => {
  564. debug!("{}: not supported. replacing with ENUM", kind);
  565. let members: Vec<BtfEnum> = ty
  566. .params
  567. .iter()
  568. .map(|p| BtfEnum {
  569. name_offset: p.name_offset,
  570. value: p.btf_type,
  571. })
  572. .collect();
  573. let enum_type = BtfType::Enum(Enum::new(ty.name_offset, false, members));
  574. *t = enum_type;
  575. }
  576. // Sanitize FUNC.
  577. BtfType::Func(ty) => {
  578. let name = self.string_at(ty.name_offset)?;
  579. // Sanitize FUNC.
  580. if !features.btf_func {
  581. debug!("{}: not supported. replacing with TYPEDEF", kind);
  582. *t = BtfType::Typedef(Typedef::new(ty.name_offset, ty.btf_type));
  583. } else if !features.btf_func_global
  584. || name == "memset"
  585. || name == "memcpy"
  586. || name == "memmove"
  587. || name == "memcmp"
  588. {
  589. // Sanitize BTF_FUNC_GLOBAL when not supported and ensure that
  590. // memory builtins are marked as static. Globals are type checked
  591. // and verified separately from their callers, while instead we
  592. // want tracking info (eg bound checks) to be propagated to the
  593. // memory builtins.
  594. if ty.linkage() == FuncLinkage::Global {
  595. if !features.btf_func_global {
  596. debug!(
  597. "{}: BTF_FUNC_GLOBAL not supported. replacing with BTF_FUNC_STATIC",
  598. kind
  599. );
  600. } else {
  601. debug!("changing FUNC {name} linkage to BTF_FUNC_STATIC");
  602. }
  603. ty.set_linkage(FuncLinkage::Static);
  604. }
  605. }
  606. }
  607. // Sanitize FLOAT.
  608. BtfType::Float(ty) if !features.btf_float => {
  609. debug!("{}: not supported. replacing with STRUCT", kind);
  610. *t = BtfType::Struct(Struct::new(0, vec![], ty.size));
  611. }
  612. // Sanitize DECL_TAG.
  613. BtfType::DeclTag(ty) if !features.btf_decl_tag => {
  614. debug!("{}: not supported. replacing with INT", kind);
  615. *t = BtfType::Int(Int::new(ty.name_offset, 1, IntEncoding::None, 0));
  616. }
  617. // Sanitize TYPE_TAG.
  618. BtfType::TypeTag(ty) if !features.btf_type_tag => {
  619. debug!("{}: not supported. replacing with CONST", kind);
  620. *t = BtfType::Const(Const::new(ty.btf_type));
  621. }
  622. // Sanitize Signed ENUMs.
  623. BtfType::Enum(ty) if !features.btf_enum64 && ty.is_signed() => {
  624. debug!("{}: signed ENUMs not supported. Marking as unsigned", kind);
  625. ty.set_signed(false);
  626. }
  627. // Sanitize ENUM64.
  628. BtfType::Enum64(ty) if !features.btf_enum64 => {
  629. debug!("{}: not supported. replacing with UNION", kind);
  630. let placeholder_id =
  631. enum64_placeholder_id.expect("enum64_placeholder_id must be set");
  632. let members: Vec<BtfMember> = ty
  633. .variants
  634. .iter()
  635. .map(|v| BtfMember {
  636. name_offset: v.name_offset,
  637. btf_type: placeholder_id,
  638. offset: 0,
  639. })
  640. .collect();
  641. *t = BtfType::Union(Union::new(ty.name_offset, members.len() as u32, members));
  642. }
  643. // The type does not need fixing up or sanitization.
  644. _ => {}
  645. }
  646. }
  647. self.types = types;
  648. Ok(())
  649. }
  650. }
  651. impl Default for Btf {
  652. fn default() -> Self {
  653. Self::new()
  654. }
  655. }
  656. impl Object {
  657. /// Fixes up and sanitizes BTF data.
  658. ///
  659. /// Mostly, it removes unsupported types and works around LLVM behaviours.
  660. pub fn fixup_and_sanitize_btf(
  661. &mut self,
  662. features: &BtfFeatures,
  663. ) -> Result<Option<&Btf>, BtfError> {
  664. if let Some(ref mut obj_btf) = &mut self.btf {
  665. if obj_btf.is_empty() {
  666. return Ok(None);
  667. }
  668. // fixup btf
  669. obj_btf.fixup_and_sanitize(
  670. &self.section_infos,
  671. &self.symbol_offset_by_name,
  672. features,
  673. )?;
  674. Ok(Some(obj_btf))
  675. } else {
  676. Ok(None)
  677. }
  678. }
  679. }
  680. unsafe fn read_btf_header(data: &[u8]) -> btf_header {
  681. // safety: btf_header is POD so read_unaligned is safe
  682. ptr::read_unaligned(data.as_ptr() as *const btf_header)
  683. }
  684. /// Data in the `.BTF.ext` section
  685. #[derive(Debug, Clone)]
  686. pub struct BtfExt {
  687. data: Vec<u8>,
  688. _endianness: Endianness,
  689. relocations: Vec<(u32, Vec<Relocation>)>,
  690. header: btf_ext_header,
  691. func_info_rec_size: usize,
  692. pub(crate) func_info: FuncInfo,
  693. line_info_rec_size: usize,
  694. pub(crate) line_info: LineInfo,
  695. core_relo_rec_size: usize,
  696. }
  697. impl BtfExt {
  698. pub(crate) fn parse(
  699. data: &[u8],
  700. endianness: Endianness,
  701. btf: &Btf,
  702. ) -> Result<BtfExt, BtfError> {
  703. #[repr(C)]
  704. #[derive(Debug, Copy, Clone)]
  705. struct MinimalHeader {
  706. pub magic: u16,
  707. pub version: u8,
  708. pub flags: u8,
  709. pub hdr_len: u32,
  710. }
  711. if data.len() < core::mem::size_of::<MinimalHeader>() {
  712. return Err(BtfError::InvalidHeader);
  713. }
  714. let header = {
  715. // first find the actual size of the header by converting into the minimal valid header
  716. // Safety: MinimalHeader is POD so read_unaligned is safe
  717. let minimal_header = unsafe {
  718. ptr::read_unaligned::<MinimalHeader>(data.as_ptr() as *const MinimalHeader)
  719. };
  720. let len_to_read = minimal_header.hdr_len as usize;
  721. // prevent invalid input from causing UB
  722. if data.len() < len_to_read {
  723. return Err(BtfError::InvalidHeader);
  724. }
  725. // forwards compatibility: if newer headers are bigger
  726. // than the pre-generated btf_ext_header we should only
  727. // read up to btf_ext_header
  728. let len_to_read = len_to_read.min(core::mem::size_of::<btf_ext_header>());
  729. // now create our full-fledge header; but start with it
  730. // zeroed out so unavailable fields stay as zero on older
  731. // BTF.ext sections
  732. let mut header = core::mem::MaybeUninit::<btf_ext_header>::zeroed();
  733. // Safety: we have checked that len_to_read is less than
  734. // size_of::<btf_ext_header> and less than
  735. // data.len(). Additionally, we know that the header has
  736. // been initialized so it's safe to call for assume_init.
  737. unsafe {
  738. core::ptr::copy(data.as_ptr(), header.as_mut_ptr() as *mut u8, len_to_read);
  739. header.assume_init()
  740. }
  741. };
  742. let btf_ext_header {
  743. hdr_len,
  744. func_info_off,
  745. func_info_len,
  746. line_info_off,
  747. line_info_len,
  748. core_relo_off,
  749. core_relo_len,
  750. ..
  751. } = header;
  752. let rec_size = |offset, len| {
  753. let offset = hdr_len as usize + offset as usize;
  754. let len = len as usize;
  755. // check that there's at least enough space for the `rec_size` field
  756. if (len > 0 && len < 4) || offset + len > data.len() {
  757. return Err(BtfError::InvalidInfo {
  758. offset,
  759. len,
  760. section_len: data.len(),
  761. });
  762. }
  763. let read_u32 = if endianness == Endianness::Little {
  764. u32::from_le_bytes
  765. } else {
  766. u32::from_be_bytes
  767. };
  768. Ok(if len > 0 {
  769. read_u32(data[offset..offset + 4].try_into().unwrap()) as usize
  770. } else {
  771. 0
  772. })
  773. };
  774. let mut ext = BtfExt {
  775. header,
  776. relocations: Vec::new(),
  777. func_info: FuncInfo::new(),
  778. line_info: LineInfo::new(),
  779. func_info_rec_size: rec_size(func_info_off, func_info_len)?,
  780. line_info_rec_size: rec_size(line_info_off, line_info_len)?,
  781. core_relo_rec_size: rec_size(core_relo_off, core_relo_len)?,
  782. data: data.to_vec(),
  783. _endianness: endianness,
  784. };
  785. let func_info_rec_size = ext.func_info_rec_size;
  786. ext.func_info.data.extend(
  787. SecInfoIter::new(ext.func_info_data(), ext.func_info_rec_size, endianness)
  788. .map(move |sec| {
  789. let name = btf
  790. .string_at(sec.name_offset)
  791. .ok()
  792. .map(String::from)
  793. .unwrap();
  794. let info = FuncSecInfo::parse(
  795. sec.name_offset,
  796. sec.num_info,
  797. func_info_rec_size,
  798. sec.data,
  799. endianness,
  800. );
  801. Ok((name, info))
  802. })
  803. .collect::<Result<HashMap<_, _>, _>>()?,
  804. );
  805. let line_info_rec_size = ext.line_info_rec_size;
  806. ext.line_info.data.extend(
  807. SecInfoIter::new(ext.line_info_data(), ext.line_info_rec_size, endianness)
  808. .map(move |sec| {
  809. let name = btf
  810. .string_at(sec.name_offset)
  811. .ok()
  812. .map(String::from)
  813. .unwrap();
  814. let info = LineSecInfo::parse(
  815. sec.name_offset,
  816. sec.num_info,
  817. line_info_rec_size,
  818. sec.data,
  819. endianness,
  820. );
  821. Ok((name, info))
  822. })
  823. .collect::<Result<HashMap<_, _>, _>>()?,
  824. );
  825. let rec_size = ext.core_relo_rec_size;
  826. ext.relocations.extend(
  827. SecInfoIter::new(ext.core_relo_data(), ext.core_relo_rec_size, endianness)
  828. .map(move |sec| {
  829. let relos = sec
  830. .data
  831. .chunks(rec_size)
  832. .enumerate()
  833. .map(|(n, rec)| unsafe { Relocation::parse(rec, n) })
  834. .collect::<Result<Vec<_>, _>>()?;
  835. Ok((sec.name_offset, relos))
  836. })
  837. .collect::<Result<Vec<_>, _>>()?,
  838. );
  839. Ok(ext)
  840. }
  841. fn info_data(&self, offset: u32, len: u32) -> &[u8] {
  842. let offset = (self.header.hdr_len + offset) as usize;
  843. let data = &self.data[offset..offset + len as usize];
  844. if len > 0 {
  845. // skip `rec_size`
  846. &data[4..]
  847. } else {
  848. data
  849. }
  850. }
  851. fn core_relo_data(&self) -> &[u8] {
  852. self.info_data(self.header.core_relo_off, self.header.core_relo_len)
  853. }
  854. fn func_info_data(&self) -> &[u8] {
  855. self.info_data(self.header.func_info_off, self.header.func_info_len)
  856. }
  857. fn line_info_data(&self) -> &[u8] {
  858. self.info_data(self.header.line_info_off, self.header.line_info_len)
  859. }
  860. pub(crate) fn relocations(&self) -> impl Iterator<Item = &(u32, Vec<Relocation>)> {
  861. self.relocations.iter()
  862. }
  863. pub(crate) fn func_info_rec_size(&self) -> usize {
  864. self.func_info_rec_size
  865. }
  866. pub(crate) fn line_info_rec_size(&self) -> usize {
  867. self.line_info_rec_size
  868. }
  869. }
  870. pub(crate) struct SecInfoIter<'a> {
  871. data: &'a [u8],
  872. offset: usize,
  873. rec_size: usize,
  874. endianness: Endianness,
  875. }
  876. impl<'a> SecInfoIter<'a> {
  877. fn new(data: &'a [u8], rec_size: usize, endianness: Endianness) -> Self {
  878. Self {
  879. data,
  880. rec_size,
  881. offset: 0,
  882. endianness,
  883. }
  884. }
  885. }
  886. impl<'a> Iterator for SecInfoIter<'a> {
  887. type Item = SecInfo<'a>;
  888. fn next(&mut self) -> Option<Self::Item> {
  889. let data = self.data;
  890. if self.offset + 8 >= data.len() {
  891. return None;
  892. }
  893. let read_u32 = if self.endianness == Endianness::Little {
  894. u32::from_le_bytes
  895. } else {
  896. u32::from_be_bytes
  897. };
  898. let name_offset = read_u32(data[self.offset..self.offset + 4].try_into().unwrap());
  899. self.offset += 4;
  900. let num_info = u32::from_ne_bytes(data[self.offset..self.offset + 4].try_into().unwrap());
  901. self.offset += 4;
  902. let data = &data[self.offset..self.offset + (self.rec_size * num_info as usize)];
  903. self.offset += self.rec_size * num_info as usize;
  904. Some(SecInfo {
  905. name_offset,
  906. num_info,
  907. data,
  908. })
  909. }
  910. }
  911. /// BtfTypes allows for access and manipulation of a
  912. /// collection of BtfType objects
  913. #[derive(Debug, Clone)]
  914. pub(crate) struct BtfTypes {
  915. pub(crate) types: Vec<BtfType>,
  916. }
  917. impl Default for BtfTypes {
  918. fn default() -> Self {
  919. Self {
  920. types: vec![BtfType::Unknown],
  921. }
  922. }
  923. }
  924. impl BtfTypes {
  925. pub(crate) fn to_bytes(&self) -> Vec<u8> {
  926. let mut buf = vec![];
  927. for t in self.types.iter().skip(1) {
  928. let b = t.to_bytes();
  929. buf.extend(b)
  930. }
  931. buf
  932. }
  933. pub(crate) fn len(&self) -> usize {
  934. self.types.len()
  935. }
  936. pub(crate) fn push(&mut self, value: BtfType) {
  937. self.types.push(value)
  938. }
  939. pub(crate) fn type_by_id(&self, type_id: u32) -> Result<&BtfType, BtfError> {
  940. self.types
  941. .get(type_id as usize)
  942. .ok_or(BtfError::UnknownBtfType { type_id })
  943. }
  944. pub(crate) fn resolve_type(&self, root_type_id: u32) -> Result<u32, BtfError> {
  945. let mut type_id = root_type_id;
  946. for () in core::iter::repeat_n((), MAX_RESOLVE_DEPTH) {
  947. let ty = self.type_by_id(type_id)?;
  948. use BtfType::*;
  949. match ty {
  950. Volatile(ty) => {
  951. type_id = ty.btf_type;
  952. continue;
  953. }
  954. Const(ty) => {
  955. type_id = ty.btf_type;
  956. continue;
  957. }
  958. Restrict(ty) => {
  959. type_id = ty.btf_type;
  960. continue;
  961. }
  962. Typedef(ty) => {
  963. type_id = ty.btf_type;
  964. continue;
  965. }
  966. TypeTag(ty) => {
  967. type_id = ty.btf_type;
  968. continue;
  969. }
  970. _ => return Ok(type_id),
  971. }
  972. }
  973. Err(BtfError::MaximumTypeDepthReached {
  974. type_id: root_type_id,
  975. })
  976. }
  977. }
  978. #[derive(Debug)]
  979. pub(crate) struct SecInfo<'a> {
  980. name_offset: u32,
  981. num_info: u32,
  982. data: &'a [u8],
  983. }
  984. #[cfg(test)]
  985. mod tests {
  986. use assert_matches::assert_matches;
  987. use super::*;
  988. use crate::btf::{
  989. BtfEnum64, BtfParam, DataSec, DataSecEntry, DeclTag, Enum64, Float, Func, FuncProto, Ptr,
  990. TypeTag, Var,
  991. };
  992. #[test]
  993. fn test_parse_header() {
  994. let header = btf_header {
  995. magic: 0xeb9f,
  996. version: 0x01,
  997. flags: 0x00,
  998. hdr_len: 0x18,
  999. type_off: 0x00,
  1000. type_len: 0x2a5464,
  1001. str_off: 0x2a5464,
  1002. str_len: 0x1c6410,
  1003. };
  1004. let data = unsafe { bytes_of::<btf_header>(&header).to_vec() };
  1005. let header = unsafe { read_btf_header(&data) };
  1006. assert_eq!(header.magic, 0xeb9f);
  1007. assert_eq!(header.version, 0x01);
  1008. assert_eq!(header.flags, 0x00);
  1009. assert_eq!(header.hdr_len, 0x18);
  1010. assert_eq!(header.type_off, 0x00);
  1011. assert_eq!(header.type_len, 0x2a5464);
  1012. assert_eq!(header.str_off, 0x2a5464);
  1013. assert_eq!(header.str_len, 0x1c6410);
  1014. }
  1015. #[test]
  1016. fn test_parse_btf() {
  1017. // this generated BTF data is from an XDP program that simply returns XDP_PASS
  1018. // compiled using clang
  1019. let data: &[u8] = if cfg!(target_endian = "little") {
  1020. &[
  1021. 0x9f, 0xeb, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x01,
  1022. 0x00, 0x00, 0x0c, 0x01, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  1023. 0x00, 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00,
  1024. 0x00, 0x04, 0x18, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
  1025. 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00,
  1026. 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
  1027. 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x30, 0x00,
  1028. 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00,
  1029. 0x03, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00,
  1030. 0x00, 0x08, 0x04, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  1031. 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
  1032. 0x00, 0x0d, 0x06, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
  1033. 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00,
  1034. 0x00, 0x01, 0x69, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0c, 0x05, 0x00, 0x00, 0x00,
  1035. 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00,
  1036. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
  1037. 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xbc, 0x00,
  1038. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
  1039. 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00,
  1040. 0x00, 0x00, 0xd9, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00,
  1041. 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x78,
  1042. 0x64, 0x70, 0x5f, 0x6d, 0x64, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x64, 0x61, 0x74,
  1043. 0x61, 0x5f, 0x65, 0x6e, 0x64, 0x00, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x6d, 0x65, 0x74,
  1044. 0x61, 0x00, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x66, 0x69, 0x6e,
  1045. 0x64, 0x65, 0x78, 0x00, 0x72, 0x78, 0x5f, 0x71, 0x75, 0x65, 0x75, 0x65, 0x5f, 0x69,
  1046. 0x6e, 0x64, 0x65, 0x78, 0x00, 0x65, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x66,
  1047. 0x69, 0x6e, 0x64, 0x65, 0x78, 0x00, 0x5f, 0x5f, 0x75, 0x33, 0x32, 0x00, 0x75, 0x6e,
  1048. 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x00, 0x63, 0x74, 0x78,
  1049. 0x00, 0x69, 0x6e, 0x74, 0x00, 0x78, 0x64, 0x70, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x00,
  1050. 0x78, 0x64, 0x70, 0x2f, 0x70, 0x61, 0x73, 0x73, 0x00, 0x2f, 0x68, 0x6f, 0x6d, 0x65,
  1051. 0x2f, 0x64, 0x61, 0x76, 0x65, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x62, 0x70, 0x66, 0x64,
  1052. 0x2f, 0x62, 0x70, 0x66, 0x2f, 0x78, 0x64, 0x70, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x2e,
  1053. 0x62, 0x70, 0x66, 0x2e, 0x63, 0x00, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
  1054. 0x72, 0x6e, 0x20, 0x58, 0x44, 0x50, 0x5f, 0x50, 0x41, 0x53, 0x53, 0x3b, 0x00, 0x63,
  1055. 0x68, 0x61, 0x72, 0x00, 0x5f, 0x5f, 0x41, 0x52, 0x52, 0x41, 0x59, 0x5f, 0x53, 0x49,
  1056. 0x5a, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x5f, 0x00, 0x5f, 0x6c, 0x69, 0x63,
  1057. 0x65, 0x6e, 0x73, 0x65, 0x00, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x00,
  1058. ]
  1059. } else {
  1060. &[
  1061. 0xeb, 0x9f, 0x01, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  1062. 0x01, 0x0c, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x00, 0xe1, 0x00, 0x00, 0x00, 0x00,
  1063. 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00,
  1064. 0x00, 0x06, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03,
  1065. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
  1066. 0x00, 0x20, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x40,
  1067. 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00,
  1068. 0x00, 0x30, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x3f,
  1069. 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x4e, 0x08, 0x00,
  1070. 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x54, 0x01, 0x00, 0x00, 0x00,
  1071. 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00,
  1072. 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x01,
  1073. 0x00, 0x00, 0x00, 0x65, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00,
  1074. 0x00, 0x20, 0x00, 0x00, 0x00, 0x69, 0x0c, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05,
  1075. 0x00, 0x00, 0x00, 0xb7, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00,
  1076. 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  1077. 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
  1078. 0x00, 0xbc, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20,
  1079. 0x00, 0x00, 0x00, 0xd0, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00,
  1080. 0x00, 0x01, 0x00, 0x00, 0x00, 0xd9, 0x0f, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
  1081. 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x78,
  1082. 0x64, 0x70, 0x5f, 0x6d, 0x64, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x64, 0x61, 0x74,
  1083. 0x61, 0x5f, 0x65, 0x6e, 0x64, 0x00, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x6d, 0x65, 0x74,
  1084. 0x61, 0x00, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x66, 0x69, 0x6e,
  1085. 0x64, 0x65, 0x78, 0x00, 0x72, 0x78, 0x5f, 0x71, 0x75, 0x65, 0x75, 0x65, 0x5f, 0x69,
  1086. 0x6e, 0x64, 0x65, 0x78, 0x00, 0x65, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x69, 0x66,
  1087. 0x69, 0x6e, 0x64, 0x65, 0x78, 0x00, 0x5f, 0x5f, 0x75, 0x33, 0x32, 0x00, 0x75, 0x6e,
  1088. 0x73, 0x69, 0x67, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x00, 0x63, 0x74, 0x78,
  1089. 0x00, 0x69, 0x6e, 0x74, 0x00, 0x78, 0x64, 0x70, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x00,
  1090. 0x78, 0x64, 0x70, 0x2f, 0x70, 0x61, 0x73, 0x73, 0x00, 0x2f, 0x68, 0x6f, 0x6d, 0x65,
  1091. 0x2f, 0x64, 0x61, 0x76, 0x65, 0x2f, 0x64, 0x65, 0x76, 0x2f, 0x62, 0x70, 0x66, 0x64,
  1092. 0x2f, 0x62, 0x70, 0x66, 0x2f, 0x78, 0x64, 0x70, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x2e,
  1093. 0x62, 0x70, 0x66, 0x2e, 0x63, 0x00, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
  1094. 0x72, 0x6e, 0x20, 0x58, 0x44, 0x50, 0x5f, 0x50, 0x41, 0x53, 0x53, 0x3b, 0x00, 0x63,
  1095. 0x68, 0x61, 0x72, 0x00, 0x5f, 0x5f, 0x41, 0x52, 0x52, 0x41, 0x59, 0x5f, 0x53, 0x49,
  1096. 0x5a, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x5f, 0x00, 0x5f, 0x6c, 0x69, 0x63,
  1097. 0x65, 0x6e, 0x73, 0x65, 0x00, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x00,
  1098. ]
  1099. };
  1100. assert_eq!(data.len(), 517);
  1101. let btf = Btf::parse(data, Endianness::default()).unwrap_or_else(|e| panic!("{}", e));
  1102. let data2 = btf.to_bytes();
  1103. assert_eq!(data2.len(), 517);
  1104. assert_eq!(data, data2);
  1105. const FUNC_LEN: u32 = 0x14;
  1106. const LINE_INFO_LEN: u32 = 0x1c;
  1107. const CORE_RELO_LEN: u32 = 0;
  1108. const DATA_LEN: u32 = (FUNC_LEN + LINE_INFO_LEN + CORE_RELO_LEN) / 4;
  1109. struct TestStruct {
  1110. _header: btf_ext_header,
  1111. _data: [u32; DATA_LEN as usize],
  1112. }
  1113. let test_data = TestStruct {
  1114. _header: btf_ext_header {
  1115. magic: 0xeb9f,
  1116. version: 1,
  1117. flags: 0,
  1118. hdr_len: 0x20,
  1119. func_info_off: 0,
  1120. func_info_len: FUNC_LEN,
  1121. line_info_off: FUNC_LEN,
  1122. line_info_len: LINE_INFO_LEN,
  1123. core_relo_off: FUNC_LEN + LINE_INFO_LEN,
  1124. core_relo_len: CORE_RELO_LEN,
  1125. },
  1126. _data: [
  1127. 0x00000008u32,
  1128. 0x00000072u32,
  1129. 0x00000001u32,
  1130. 0x00000000u32,
  1131. 0x00000007u32,
  1132. 0x00000010u32,
  1133. 0x00000072u32,
  1134. 0x00000001u32,
  1135. 0x00000000u32,
  1136. 0x0000007bu32,
  1137. 0x000000a2u32,
  1138. 0x00002c05u32,
  1139. ],
  1140. };
  1141. let ext_data = unsafe { bytes_of::<TestStruct>(&test_data).to_vec() };
  1142. assert_eq!(ext_data.len(), 80);
  1143. let _: BtfExt = BtfExt::parse(&ext_data, Endianness::default(), &btf)
  1144. .unwrap_or_else(|e| panic!("{}", e));
  1145. }
  1146. #[test]
  1147. fn parsing_older_ext_data() {
  1148. const TYPE_LEN: u32 = 0;
  1149. const STR_LEN: u32 = 1;
  1150. struct BtfTestStruct {
  1151. _header: btf_header,
  1152. _data: [u8; (TYPE_LEN + STR_LEN) as usize],
  1153. }
  1154. let btf_test_data = BtfTestStruct {
  1155. _header: btf_header {
  1156. magic: 0xeb9f,
  1157. version: 0x01,
  1158. flags: 0x00,
  1159. hdr_len: 24,
  1160. type_off: 0,
  1161. type_len: TYPE_LEN,
  1162. str_off: TYPE_LEN,
  1163. str_len: TYPE_LEN + STR_LEN,
  1164. },
  1165. _data: [0x00u8],
  1166. };
  1167. let btf_data = unsafe { bytes_of::<BtfTestStruct>(&btf_test_data).to_vec() };
  1168. const FUNC_INFO_LEN: u32 = 4;
  1169. const LINE_INFO_LEN: u32 = 4;
  1170. const CORE_RELO_LEN: u32 = 16;
  1171. let ext_header = btf_ext_header {
  1172. magic: 0xeb9f,
  1173. version: 1,
  1174. flags: 0,
  1175. hdr_len: 24,
  1176. func_info_off: 0,
  1177. func_info_len: FUNC_INFO_LEN,
  1178. line_info_off: FUNC_INFO_LEN,
  1179. line_info_len: LINE_INFO_LEN,
  1180. core_relo_off: FUNC_INFO_LEN + LINE_INFO_LEN,
  1181. core_relo_len: CORE_RELO_LEN,
  1182. };
  1183. let btf_ext_data = unsafe { bytes_of::<btf_ext_header>(&ext_header).to_vec() };
  1184. let btf = Btf::parse(&btf_data, Endianness::default()).unwrap();
  1185. let btf_ext = BtfExt::parse(&btf_ext_data, Endianness::default(), &btf).unwrap();
  1186. assert_eq!(btf_ext.func_info_rec_size(), 8);
  1187. assert_eq!(btf_ext.line_info_rec_size(), 16);
  1188. }
  1189. #[test]
  1190. fn test_write_btf() {
  1191. let mut btf = Btf::new();
  1192. let name_offset = btf.add_string("int");
  1193. let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
  1194. btf.add_type(int_type);
  1195. let name_offset = btf.add_string("widget");
  1196. let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
  1197. btf.add_type(int_type);
  1198. let btf_bytes = btf.to_bytes();
  1199. let raw_btf = btf_bytes.as_slice();
  1200. let btf = Btf::parse(raw_btf, Endianness::default()).unwrap_or_else(|e| panic!("{}", e));
  1201. assert_eq!(btf.string_at(1).unwrap(), "int");
  1202. assert_eq!(btf.string_at(5).unwrap(), "widget");
  1203. }
  1204. #[test]
  1205. fn test_fixup_ptr() {
  1206. let mut btf = Btf::new();
  1207. let name_offset = btf.add_string("int");
  1208. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1209. name_offset,
  1210. 4,
  1211. IntEncoding::Signed,
  1212. 0,
  1213. )));
  1214. let name_offset = btf.add_string("&mut int");
  1215. let ptr_type_id = btf.add_type(BtfType::Ptr(Ptr::new(name_offset, int_type_id)));
  1216. let features = Default::default();
  1217. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1218. .unwrap();
  1219. assert_matches!(btf.type_by_id(ptr_type_id).unwrap(), BtfType::Ptr(fixed) => {
  1220. assert_eq!(fixed.name_offset, 0);
  1221. });
  1222. // Ensure we can convert to bytes and back again
  1223. let raw = btf.to_bytes();
  1224. Btf::parse(&raw, Endianness::default()).unwrap();
  1225. }
  1226. #[test]
  1227. fn test_sanitize_var() {
  1228. let mut btf = Btf::new();
  1229. let name_offset = btf.add_string("int");
  1230. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1231. name_offset,
  1232. 4,
  1233. IntEncoding::Signed,
  1234. 0,
  1235. )));
  1236. let name_offset = btf.add_string("&mut int");
  1237. let var_type_id = btf.add_type(BtfType::Var(Var::new(
  1238. name_offset,
  1239. int_type_id,
  1240. VarLinkage::Static,
  1241. )));
  1242. let features = BtfFeatures {
  1243. btf_datasec: false,
  1244. ..Default::default()
  1245. };
  1246. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1247. .unwrap();
  1248. assert_matches!(btf.type_by_id(var_type_id).unwrap(), BtfType::Int(fixed) => {
  1249. assert_eq!(fixed.name_offset, name_offset);
  1250. });
  1251. // Ensure we can convert to bytes and back again
  1252. let raw = btf.to_bytes();
  1253. Btf::parse(&raw, Endianness::default()).unwrap();
  1254. }
  1255. #[test]
  1256. fn test_sanitize_datasec() {
  1257. let mut btf = Btf::new();
  1258. let name_offset = btf.add_string("int");
  1259. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1260. name_offset,
  1261. 4,
  1262. IntEncoding::Signed,
  1263. 0,
  1264. )));
  1265. let var_name_offset = btf.add_string("foo");
  1266. let var_type_id = btf.add_type(BtfType::Var(Var::new(
  1267. var_name_offset,
  1268. int_type_id,
  1269. VarLinkage::Static,
  1270. )));
  1271. let name_offset = btf.add_string("data");
  1272. let variables = vec![DataSecEntry {
  1273. btf_type: var_type_id,
  1274. offset: 0,
  1275. size: 4,
  1276. }];
  1277. let datasec_type_id =
  1278. btf.add_type(BtfType::DataSec(DataSec::new(name_offset, variables, 0)));
  1279. let features = BtfFeatures {
  1280. btf_datasec: false,
  1281. ..Default::default()
  1282. };
  1283. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1284. .unwrap();
  1285. assert_matches!(btf.type_by_id(datasec_type_id).unwrap(), BtfType::Struct(fixed) => {
  1286. assert_eq!(fixed.name_offset , name_offset);
  1287. assert_matches!(*fixed.members, [
  1288. BtfMember {
  1289. name_offset: name_offset1,
  1290. btf_type,
  1291. offset: 0,
  1292. },
  1293. ] => {
  1294. assert_eq!(name_offset1, var_name_offset);
  1295. assert_eq!(btf_type, var_type_id);
  1296. })
  1297. });
  1298. // Ensure we can convert to bytes and back again
  1299. let raw = btf.to_bytes();
  1300. Btf::parse(&raw, Endianness::default()).unwrap();
  1301. }
  1302. #[test]
  1303. fn test_fixup_datasec() {
  1304. let mut btf = Btf::new();
  1305. let name_offset = btf.add_string("int");
  1306. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1307. name_offset,
  1308. 4,
  1309. IntEncoding::Signed,
  1310. 0,
  1311. )));
  1312. let name_offset = btf.add_string("foo");
  1313. let var_type_id = btf.add_type(BtfType::Var(Var::new(
  1314. name_offset,
  1315. int_type_id,
  1316. VarLinkage::Global,
  1317. )));
  1318. let name_offset = btf.add_string(".data/foo");
  1319. let variables = vec![DataSecEntry {
  1320. btf_type: var_type_id,
  1321. offset: 0,
  1322. size: 4,
  1323. }];
  1324. let datasec_type_id =
  1325. btf.add_type(BtfType::DataSec(DataSec::new(name_offset, variables, 0)));
  1326. let features = BtfFeatures {
  1327. btf_datasec: true,
  1328. ..Default::default()
  1329. };
  1330. btf.fixup_and_sanitize(
  1331. &HashMap::from([(".data/foo".to_owned(), (SectionIndex(0), 32u64))]),
  1332. &HashMap::from([("foo".to_owned(), 64u64)]),
  1333. &features,
  1334. )
  1335. .unwrap();
  1336. assert_matches!(btf.type_by_id(datasec_type_id).unwrap(), BtfType::DataSec(fixed) => {
  1337. assert_ne!(fixed.name_offset, name_offset);
  1338. assert_eq!(fixed.size, 32);
  1339. assert_matches!(*fixed.entries, [
  1340. DataSecEntry {
  1341. btf_type,
  1342. offset,
  1343. size,
  1344. },
  1345. ] => {
  1346. assert_eq!(btf_type, var_type_id);
  1347. assert_eq!(offset, 64);
  1348. assert_eq!(size, 4);
  1349. }
  1350. );
  1351. assert_eq!(btf.string_at(fixed.name_offset).unwrap(), ".data.foo");
  1352. });
  1353. // Ensure we can convert to bytes and back again
  1354. let raw = btf.to_bytes();
  1355. Btf::parse(&raw, Endianness::default()).unwrap();
  1356. }
  1357. #[test]
  1358. fn test_sanitize_func_and_proto() {
  1359. let mut btf = Btf::new();
  1360. let name_offset = btf.add_string("int");
  1361. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1362. name_offset,
  1363. 4,
  1364. IntEncoding::Signed,
  1365. 0,
  1366. )));
  1367. let params = vec![
  1368. BtfParam {
  1369. name_offset: btf.add_string("a"),
  1370. btf_type: int_type_id,
  1371. },
  1372. BtfParam {
  1373. name_offset: btf.add_string("b"),
  1374. btf_type: int_type_id,
  1375. },
  1376. ];
  1377. let func_proto_type_id =
  1378. btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id)));
  1379. let inc = btf.add_string("inc");
  1380. let func_type_id = btf.add_type(BtfType::Func(Func::new(
  1381. inc,
  1382. func_proto_type_id,
  1383. FuncLinkage::Static,
  1384. )));
  1385. let features = BtfFeatures {
  1386. btf_func: false,
  1387. ..Default::default()
  1388. };
  1389. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1390. .unwrap();
  1391. assert_matches!(btf.type_by_id(func_proto_type_id).unwrap(), BtfType::Enum(fixed) => {
  1392. assert_eq!(fixed.name_offset, 0);
  1393. assert_matches!(*fixed.variants, [
  1394. BtfEnum {
  1395. name_offset: name_offset1,
  1396. value: value1,
  1397. },
  1398. BtfEnum {
  1399. name_offset: name_offset2,
  1400. value: value2,
  1401. },
  1402. ] => {
  1403. assert_eq!(btf.string_at(name_offset1).unwrap(), "a");
  1404. assert_eq!(value1, int_type_id);
  1405. assert_eq!(btf.string_at(name_offset2).unwrap(), "b");
  1406. assert_eq!(value2, int_type_id);
  1407. }
  1408. );
  1409. });
  1410. assert_matches!(btf.type_by_id(func_type_id).unwrap(), BtfType::Typedef(fixed) => {
  1411. assert_eq!(fixed.name_offset, inc);
  1412. assert_eq!(fixed.btf_type, func_proto_type_id);
  1413. });
  1414. // Ensure we can convert to bytes and back again
  1415. let raw = btf.to_bytes();
  1416. Btf::parse(&raw, Endianness::default()).unwrap();
  1417. }
  1418. #[test]
  1419. fn test_fixup_func_proto() {
  1420. let mut btf = Btf::new();
  1421. let name_offset = btf.add_string("int");
  1422. let int_type = BtfType::Int(Int::new(name_offset, 4, IntEncoding::Signed, 0));
  1423. let int_type_id = btf.add_type(int_type);
  1424. let params = vec![
  1425. BtfParam {
  1426. name_offset: 0,
  1427. btf_type: int_type_id,
  1428. },
  1429. BtfParam {
  1430. name_offset: 0,
  1431. btf_type: int_type_id,
  1432. },
  1433. ];
  1434. let func_proto = BtfType::FuncProto(FuncProto::new(params, int_type_id));
  1435. let func_proto_type_id = btf.add_type(func_proto);
  1436. let features = BtfFeatures {
  1437. btf_func: true,
  1438. ..Default::default()
  1439. };
  1440. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1441. .unwrap();
  1442. assert_matches!(btf.type_by_id(func_proto_type_id).unwrap(), BtfType::FuncProto(fixed) => {
  1443. assert_matches!(*fixed.params, [
  1444. BtfParam {
  1445. name_offset: name_offset1,
  1446. btf_type: btf_type1,
  1447. },
  1448. BtfParam {
  1449. name_offset: name_offset2,
  1450. btf_type: btf_type2,
  1451. },
  1452. ] => {
  1453. assert_eq!(btf.string_at(name_offset1).unwrap(), "param0");
  1454. assert_eq!(btf_type1, int_type_id);
  1455. assert_eq!(btf.string_at(name_offset2).unwrap(), "param1");
  1456. assert_eq!(btf_type2, int_type_id);
  1457. }
  1458. );
  1459. });
  1460. // Ensure we can convert to bytes and back again
  1461. let raw = btf.to_bytes();
  1462. Btf::parse(&raw, Endianness::default()).unwrap();
  1463. }
  1464. #[test]
  1465. fn test_sanitize_func_global() {
  1466. let mut btf = Btf::new();
  1467. let name_offset = btf.add_string("int");
  1468. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1469. name_offset,
  1470. 4,
  1471. IntEncoding::Signed,
  1472. 0,
  1473. )));
  1474. let params = vec![
  1475. BtfParam {
  1476. name_offset: btf.add_string("a"),
  1477. btf_type: int_type_id,
  1478. },
  1479. BtfParam {
  1480. name_offset: btf.add_string("b"),
  1481. btf_type: int_type_id,
  1482. },
  1483. ];
  1484. let func_proto_type_id =
  1485. btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id)));
  1486. let inc = btf.add_string("inc");
  1487. let func_type_id = btf.add_type(BtfType::Func(Func::new(
  1488. inc,
  1489. func_proto_type_id,
  1490. FuncLinkage::Global,
  1491. )));
  1492. let features = BtfFeatures {
  1493. btf_func: true,
  1494. btf_func_global: false,
  1495. ..Default::default()
  1496. };
  1497. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1498. .unwrap();
  1499. assert_matches!(btf.type_by_id(func_type_id).unwrap(), BtfType::Func(fixed) => {
  1500. assert_eq!(fixed.linkage(), FuncLinkage::Static);
  1501. });
  1502. // Ensure we can convert to bytes and back again
  1503. let raw = btf.to_bytes();
  1504. Btf::parse(&raw, Endianness::default()).unwrap();
  1505. }
  1506. #[test]
  1507. fn test_sanitize_mem_builtins() {
  1508. let mut btf = Btf::new();
  1509. let name_offset = btf.add_string("int");
  1510. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1511. name_offset,
  1512. 4,
  1513. IntEncoding::Signed,
  1514. 0,
  1515. )));
  1516. let params = vec![
  1517. BtfParam {
  1518. name_offset: btf.add_string("a"),
  1519. btf_type: int_type_id,
  1520. },
  1521. BtfParam {
  1522. name_offset: btf.add_string("b"),
  1523. btf_type: int_type_id,
  1524. },
  1525. ];
  1526. let func_proto_type_id =
  1527. btf.add_type(BtfType::FuncProto(FuncProto::new(params, int_type_id)));
  1528. let builtins = ["memset", "memcpy", "memcmp", "memmove"];
  1529. for fname in builtins {
  1530. let func_name_offset = btf.add_string(fname);
  1531. let func_type_id = btf.add_type(BtfType::Func(Func::new(
  1532. func_name_offset,
  1533. func_proto_type_id,
  1534. FuncLinkage::Global,
  1535. )));
  1536. let features = BtfFeatures {
  1537. btf_func: true,
  1538. btf_func_global: true, // to force function name check
  1539. ..Default::default()
  1540. };
  1541. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1542. .unwrap();
  1543. assert_matches!(btf.type_by_id(func_type_id).unwrap(), BtfType::Func(fixed) => {
  1544. assert_eq!(fixed.linkage(), FuncLinkage::Static);
  1545. });
  1546. // Ensure we can convert to bytes and back again
  1547. let raw = btf.to_bytes();
  1548. Btf::parse(&raw, Endianness::default()).unwrap();
  1549. }
  1550. }
  1551. #[test]
  1552. fn test_sanitize_float() {
  1553. let mut btf = Btf::new();
  1554. let name_offset = btf.add_string("float");
  1555. let float_type_id = btf.add_type(BtfType::Float(Float::new(name_offset, 16)));
  1556. let features = BtfFeatures {
  1557. btf_float: false,
  1558. ..Default::default()
  1559. };
  1560. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1561. .unwrap();
  1562. assert_matches!(btf.type_by_id(float_type_id).unwrap(), BtfType::Struct(fixed) => {
  1563. assert_eq!(fixed.name_offset, 0);
  1564. assert_eq!(fixed.size, 16);
  1565. });
  1566. // Ensure we can convert to bytes and back again
  1567. let raw = btf.to_bytes();
  1568. Btf::parse(&raw, Endianness::default()).unwrap();
  1569. }
  1570. #[test]
  1571. fn test_sanitize_decl_tag() {
  1572. let mut btf = Btf::new();
  1573. let name_offset = btf.add_string("int");
  1574. let int_type_id = btf.add_type(BtfType::Int(Int::new(
  1575. name_offset,
  1576. 4,
  1577. IntEncoding::Signed,
  1578. 0,
  1579. )));
  1580. let name_offset = btf.add_string("foo");
  1581. let var_type_id = btf.add_type(BtfType::Var(Var::new(
  1582. name_offset,
  1583. int_type_id,
  1584. VarLinkage::Static,
  1585. )));
  1586. let name_offset = btf.add_string("decl_tag");
  1587. let decl_tag_type_id =
  1588. btf.add_type(BtfType::DeclTag(DeclTag::new(name_offset, var_type_id, -1)));
  1589. let features = BtfFeatures {
  1590. btf_decl_tag: false,
  1591. ..Default::default()
  1592. };
  1593. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1594. .unwrap();
  1595. assert_matches!(btf.type_by_id(decl_tag_type_id).unwrap(), BtfType::Int(fixed) => {
  1596. assert_eq!(fixed.name_offset, name_offset);
  1597. assert_eq!(fixed.size, 1);
  1598. });
  1599. // Ensure we can convert to bytes and back again
  1600. let raw = btf.to_bytes();
  1601. Btf::parse(&raw, Endianness::default()).unwrap();
  1602. }
  1603. #[test]
  1604. fn test_sanitize_type_tag() {
  1605. let mut btf = Btf::new();
  1606. let int_type_id = btf.add_type(BtfType::Int(Int::new(0, 4, IntEncoding::Signed, 0)));
  1607. let name_offset = btf.add_string("int");
  1608. let type_tag_type = btf.add_type(BtfType::TypeTag(TypeTag::new(name_offset, int_type_id)));
  1609. btf.add_type(BtfType::Ptr(Ptr::new(0, type_tag_type)));
  1610. let features = BtfFeatures {
  1611. btf_type_tag: false,
  1612. ..Default::default()
  1613. };
  1614. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1615. .unwrap();
  1616. assert_matches!(btf.type_by_id(type_tag_type).unwrap(), BtfType::Const(fixed) => {
  1617. assert_eq!(fixed.btf_type, int_type_id);
  1618. });
  1619. // Ensure we can convert to bytes and back again
  1620. let raw = btf.to_bytes();
  1621. Btf::parse(&raw, Endianness::default()).unwrap();
  1622. }
  1623. #[test]
  1624. #[cfg(feature = "std")]
  1625. #[cfg_attr(miri, ignore = "`open` not available when isolation is enabled")]
  1626. #[cfg_attr(
  1627. target_endian = "big",
  1628. ignore = "Not possible to emulate \"/sys/kernel/btf/vmlinux\" as big endian"
  1629. )]
  1630. fn test_read_btf_from_sys_fs() {
  1631. let btf = Btf::parse_file("/sys/kernel/btf/vmlinux", Endianness::default()).unwrap();
  1632. let task_struct_id = btf
  1633. .id_by_type_name_kind("task_struct", BtfKind::Struct)
  1634. .unwrap();
  1635. // we can't assert on exact ID since this may change across kernel versions
  1636. assert!(task_struct_id != 0);
  1637. let netif_id = btf
  1638. .id_by_type_name_kind("netif_receive_skb", BtfKind::Func)
  1639. .unwrap();
  1640. assert!(netif_id != 0);
  1641. let u32_def = btf.id_by_type_name_kind("__u32", BtfKind::Typedef).unwrap();
  1642. assert!(u32_def != 0);
  1643. let u32_base = btf.resolve_type(u32_def).unwrap();
  1644. assert!(u32_base != 0);
  1645. let u32_ty = btf.type_by_id(u32_base).unwrap();
  1646. assert_eq!(u32_ty.kind(), BtfKind::Int);
  1647. }
  1648. #[test]
  1649. fn test_sanitize_signed_enum() {
  1650. let mut btf = Btf::new();
  1651. let name_offset = btf.add_string("signed_enum");
  1652. let name_a = btf.add_string("A");
  1653. let name_b = btf.add_string("B");
  1654. let name_c = btf.add_string("C");
  1655. let enum64_type = Enum::new(
  1656. name_offset,
  1657. true,
  1658. vec![
  1659. BtfEnum::new(name_a, -1i32 as u32),
  1660. BtfEnum::new(name_b, -2i32 as u32),
  1661. BtfEnum::new(name_c, -3i32 as u32),
  1662. ],
  1663. );
  1664. let enum_type_id = btf.add_type(BtfType::Enum(enum64_type));
  1665. let features = BtfFeatures {
  1666. btf_enum64: false,
  1667. ..Default::default()
  1668. };
  1669. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1670. .unwrap();
  1671. assert_matches!(btf.type_by_id(enum_type_id).unwrap(), BtfType::Enum(fixed) => {
  1672. assert!(!fixed.is_signed());
  1673. assert_matches!(fixed.variants[..], [
  1674. BtfEnum { name_offset: name1, value: 0xFFFF_FFFF },
  1675. BtfEnum { name_offset: name2, value: 0xFFFF_FFFE },
  1676. BtfEnum { name_offset: name3, value: 0xFFFF_FFFD },
  1677. ] => {
  1678. assert_eq!(name1, name_a);
  1679. assert_eq!(name2, name_b);
  1680. assert_eq!(name3, name_c);
  1681. });
  1682. });
  1683. // Ensure we can convert to bytes and back again.
  1684. let raw = btf.to_bytes();
  1685. Btf::parse(&raw, Endianness::default()).unwrap();
  1686. }
  1687. #[test]
  1688. fn test_sanitize_enum64() {
  1689. let mut btf = Btf::new();
  1690. let name_offset = btf.add_string("enum64");
  1691. let name_a = btf.add_string("A");
  1692. let name_b = btf.add_string("B");
  1693. let name_c = btf.add_string("C");
  1694. let enum64_type = Enum64::new(
  1695. name_offset,
  1696. false,
  1697. vec![
  1698. BtfEnum64::new(name_a, 1),
  1699. BtfEnum64::new(name_b, 2),
  1700. BtfEnum64::new(name_c, 3),
  1701. ],
  1702. );
  1703. let enum_type_id = btf.add_type(BtfType::Enum64(enum64_type));
  1704. let features = BtfFeatures {
  1705. btf_enum64: false,
  1706. ..Default::default()
  1707. };
  1708. btf.fixup_and_sanitize(&HashMap::new(), &HashMap::new(), &features)
  1709. .unwrap();
  1710. assert_matches!(btf.type_by_id(enum_type_id).unwrap(), BtfType::Union(fixed) => {
  1711. let placeholder = btf.id_by_type_name_kind("enum64_placeholder", BtfKind::Int)
  1712. .expect("enum64_placeholder type not found");
  1713. assert_matches!(fixed.members[..], [
  1714. BtfMember { name_offset: name_offset1, btf_type: btf_type1, offset: 0 },
  1715. BtfMember { name_offset: name_offset2, btf_type: btf_type2, offset: 0 },
  1716. BtfMember { name_offset: name_offset3, btf_type: btf_type3, offset: 0 },
  1717. ] => {
  1718. assert_eq!(name_offset1, name_a);
  1719. assert_eq!(btf_type1, placeholder);
  1720. assert_eq!(name_offset2, name_b);
  1721. assert_eq!(btf_type2, placeholder);
  1722. assert_eq!(name_offset3, name_c);
  1723. assert_eq!(btf_type3, placeholder);
  1724. });
  1725. });
  1726. // Ensure we can convert to bytes and back again.
  1727. let raw = btf.to_bytes();
  1728. Btf::parse(&raw, Endianness::default()).unwrap();
  1729. }
  1730. }