|
| 1 | +use std::sync::OnceLock; |
| 2 | + |
| 3 | +use regex::bytes; |
| 4 | + |
| 5 | +#[cfg(test)] |
| 6 | +mod tests; |
| 7 | + |
| 8 | +/// Given the raw contents of a string literal in LLVM IR assembly, decodes any |
| 9 | +/// backslash escapes and returns a vector containing the resulting byte string. |
| 10 | +pub(crate) fn unescape_llvm_string_contents(contents: &str) -> Vec<u8> { |
| 11 | + let escape_re = { |
| 12 | + static RE: OnceLock<bytes::Regex> = OnceLock::new(); |
| 13 | + // LLVM IR supports two string escapes: `\\` and `\xx`. |
| 14 | + RE.get_or_init(|| bytes::Regex::new(r"\\\\|\\([0-9A-Za-z]{2})").unwrap()) |
| 15 | + }; |
| 16 | + |
| 17 | + fn u8_from_hex_digits(digits: &[u8]) -> u8 { |
| 18 | + // We know that the input contains exactly 2 hex digits, so these calls |
| 19 | + // should never fail. |
| 20 | + assert_eq!(digits.len(), 2); |
| 21 | + let digits = std::str::from_utf8(digits).unwrap(); |
| 22 | + u8::from_str_radix(digits, 16).unwrap() |
| 23 | + } |
| 24 | + |
| 25 | + escape_re |
| 26 | + .replace_all(contents.as_bytes(), |captures: &bytes::Captures<'_>| { |
| 27 | + let byte = match captures.get(1) { |
| 28 | + None => b'\\', |
| 29 | + Some(hex_digits) => u8_from_hex_digits(hex_digits.as_bytes()), |
| 30 | + }; |
| 31 | + [byte] |
| 32 | + }) |
| 33 | + .into_owned() |
| 34 | +} |
| 35 | + |
| 36 | +/// LLVM's profiler/coverage metadata often uses an MD5 hash truncated to |
| 37 | +/// 64 bits as a way to associate data stored in different tables/sections. |
| 38 | +pub(crate) fn truncated_md5(bytes: &[u8]) -> u64 { |
| 39 | + use md5::{Digest, Md5}; |
| 40 | + let mut hasher = Md5::new(); |
| 41 | + hasher.update(bytes); |
| 42 | + let hash: [u8; 8] = hasher.finalize().as_slice()[..8].try_into().unwrap(); |
| 43 | + // The truncated hash is explicitly little-endian, regardless of host |
| 44 | + // or target platform. (See `MD5Result::low` in LLVM's `MD5.h`.) |
| 45 | + u64::from_le_bytes(hash) |
| 46 | +} |
0 commit comments