• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Reading proc-macro rustc version information from binary data
2 
3 use std::{
4     fs::File,
5     io::{self, Read},
6 };
7 
8 use memmap2::Mmap;
9 use object::read::{File as BinaryFile, Object, ObjectSection};
10 use paths::AbsPath;
11 use snap::read::FrameDecoder as SnapDecoder;
12 
13 #[derive(Debug)]
14 pub struct RustCInfo {
15     pub version: (usize, usize, usize),
16     pub channel: String,
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,
21 }
22 
23 /// Read rustc dylib information
read_dylib_info(dylib_path: &AbsPath) -> io::Result<RustCInfo>24 pub fn read_dylib_info(dylib_path: &AbsPath) -> io::Result<RustCInfo> {
25     macro_rules! err {
26         ($e:literal) => {
27             io::Error::new(io::ErrorKind::InvalidData, $e)
28         };
29     }
30 
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"))?;
34     if tag != "rustc" {
35         return Err(err!("version format error (No rustc tag)"));
36     }
37 
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();
42 
43     let commit = match items.next() {
44         Some(commit) => {
45             match commit.len() {
46                 0 => None,
47                 _ => Some(commit[1..].to_string() /* remove ( */),
48             }
49         }
50         None => None,
51     };
52     let date = match items.next() {
53         Some(date) => {
54             match date.len() {
55                 0 => None,
56                 _ => Some(date[0..date.len() - 2].to_string() /* remove ) */),
57             }
58         }
59         None => None,
60     };
61 
62     let version_numbers = version
63         .split('.')
64         .map(|it| it.parse::<usize>())
65         .collect::<Result<Vec<_>, _>>()
66         .map_err(|_| err!("version number error"))?;
67 
68     if version_numbers.len() != 3 {
69         return Err(err!("version number format error"));
70     }
71     let version = (version_numbers[0], version_numbers[1], version_numbers[2]);
72 
73     Ok(RustCInfo { version, channel, commit, date, version_string: ver_str })
74 }
75 
76 /// This is used inside read_version() to locate the ".rustc" section
77 /// from a proc macro crate's binary file.
read_section<'a>(dylib_binary: &'a [u8], section_name: &str) -> io::Result<&'a [u8]>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"))?
83         .data()
84         .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
85 }
86 
87 /// Check the version of rustc that was used to compile a proc macro crate's
88 ///
89 /// binary file.
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
95 ///   this.
96 /// The bytes you get after decompressing the snappy format portion has
97 /// following layout:
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>
read_version(dylib_path: &AbsPath) -> io::Result<String>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) }?;
110 
111     let dot_rustc = read_section(&dylib_mmaped, ".rustc")?;
112 
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]),
118         ));
119     }
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
123     let snappy_portion = match version {
124         5 | 6 => &dot_rustc[8..],
125         7 | 8 => {
126             let len_bytes = &dot_rustc[8..12];
127             let data_len = u32::from_be_bytes(len_bytes.try_into().unwrap()) as usize;
128             &dot_rustc[12..data_len + 12]
129         }
130         _ => {
131             return Err(io::Error::new(
132                 io::ErrorKind::InvalidData,
133                 format!("unsupported metadata version {version}"),
134             ));
135         }
136     };
137 
138     let mut snappy_decoder = SnapDecoder::new(snappy_portion);
139 
140     // the bytes before version string bytes, so this basically is:
141     // 8 bytes for [b'r',b'u',b's',b't',0,0,0,5]
142     // 4 bytes for [crate root bytes]
143     // 1 byte for length of version string
144     // so 13 bytes in total, and we should check the 13th byte
145     // to know the length
146     let mut bytes_before_version = [0u8; 13];
147     snappy_decoder.read_exact(&mut bytes_before_version)?;
148     let length = bytes_before_version[12];
149 
150     let mut version_string_utf8 = vec![0u8; length as usize];
151     snappy_decoder.read_exact(&mut version_string_utf8)?;
152     let version_string = String::from_utf8(version_string_utf8);
153     version_string.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
154 }
155