1 //! Reading proc-macro rustc version information from binary data
9 use object::read::{File as BinaryFile, Object, ObjectSection};
11 use snap::read::FrameDecoder as SnapDecoder;
14 pub struct RustCInfo {
15 pub version: (usize, usize, usize),
17 pub commit: Option<String>,
18 pub date: Option<String>,
19 // something like "rustc 1.58.1 (db9d1b20b 2022-01-20)"
20 pub version_string: String,
23 /// Read rustc dylib information
24 pub fn read_dylib_info(dylib_path: &AbsPath) -> io::Result<RustCInfo> {
27 io::Error::new(io::ErrorKind::InvalidData, $e)
31 let ver_str = read_version(dylib_path)?;
32 let mut items = ver_str.split_whitespace();
33 let tag = items.next().ok_or_else(|| err!("version format error"))?;
35 return Err(err!("version format error (No rustc tag)"));
38 let version_part = items.next().ok_or_else(|| err!("no version string"))?;
39 let mut version_parts = version_part.split('-');
40 let version = version_parts.next().ok_or_else(|| err!("no version"))?;
41 let channel = version_parts.next().unwrap_or_default().to_string();
43 let commit = match items.next() {
47 _ => Some(commit[1..].to_string() /* remove ( */),
52 let date = match items.next() {
56 _ => Some(date[0..date.len() - 2].to_string() /* remove ) */),
62 let version_numbers = version
64 .map(|it| it.parse::<usize>())
65 .collect::<Result<Vec<_>, _>>()
66 .map_err(|_| err!("version number error"))?;
68 if version_numbers.len() != 3 {
69 return Err(err!("version number format error"));
71 let version = (version_numbers[0], version_numbers[1], version_numbers[2]);
73 Ok(RustCInfo { version, channel, commit, date, version_string: ver_str })
76 /// This is used inside read_version() to locate the ".rustc" section
77 /// from a proc macro crate's binary file.
78 fn read_section<'a>(dylib_binary: &'a [u8], section_name: &str) -> io::Result<&'a [u8]> {
79 BinaryFile::parse(dylib_binary)
80 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
81 .section_by_name(section_name)
82 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "section read error"))?
84 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
87 /// Check the version of rustc that was used to compile a proc macro crate's
90 /// A proc macro crate binary's ".rustc" section has following byte layout:
91 /// * [b'r',b'u',b's',b't',0,0,0,5] is the first 8 bytes
92 /// * ff060000 734e6150 is followed, it's the snappy format magic bytes,
93 /// means bytes from here(including this sequence) are compressed in
94 /// snappy compression format. Version info is inside here, so decompress
96 /// The bytes you get after decompressing the snappy format portion has
98 /// * [b'r',b'u',b's',b't',0,0,0,5] is the first 8 bytes(again)
99 /// * [crate root bytes] next 4 bytes is to store crate root position,
100 /// according to rustc's source code comment
101 /// * [length byte] next 1 byte tells us how many bytes we should read next
102 /// for the version string's utf8 bytes
103 /// * [version string bytes encoded in utf8] <- GET THIS BOI
104 /// * [some more bytes that we don't really care but about still there] :-)
105 /// Check this issue for more about the bytes layout:
106 /// <https://github.com/rust-lang/rust-analyzer/issues/6174>
107 pub fn read_version(dylib_path: &AbsPath) -> io::Result<String> {
108 let dylib_file = File::open(dylib_path)?;
109 let dylib_mmaped = unsafe { Mmap::map(&dylib_file) }?;
111 let dot_rustc = read_section(&dylib_mmaped, ".rustc")?;
113 // check if magic is valid
114 if &dot_rustc[0..4] != b"rust" {
115 return Err(io::Error::new(
116 io::ErrorKind::InvalidData,
117 format!("unknown metadata magic, expected `rust`, found `{:?}`", &dot_rustc[0..4]),
120 let version = u32::from_be_bytes([dot_rustc[4], dot_rustc[5], dot_rustc[6], dot_rustc[7]]);
121 // Last supported version is:
122 // https://github.com/rust-lang/rust/commit/0696e79f2740ad89309269b460579e548a5cd632
126 return Err(io::Error::new(
127 io::ErrorKind::InvalidData,
128 format!("unsupported metadata version {}", version),
133 let snappy_portion = &dot_rustc[8..];
135 let mut snappy_decoder = SnapDecoder::new(snappy_portion);
137 // the bytes before version string bytes, so this basically is:
138 // 8 bytes for [b'r',b'u',b's',b't',0,0,0,5]
139 // 4 bytes for [crate root bytes]
140 // 1 byte for length of version string
141 // so 13 bytes in total, and we should check the 13th byte
142 // to know the length
143 let mut bytes_before_version = [0u8; 13];
144 snappy_decoder.read_exact(&mut bytes_before_version)?;
145 let length = bytes_before_version[12];
147 let mut version_string_utf8 = vec![0u8; length as usize];
148 snappy_decoder.read_exact(&mut version_string_utf8)?;
149 let version_string = String::from_utf8(version_string_utf8);
150 version_string.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))