| 1 | #![allow(clippy::write_with_newline)] |
| 2 | |
| 3 | use std::collections::{HashMap, HashSet}; |
| 4 | use std::convert::TryFrom; |
| 5 | use std::io::{self, Error, ErrorKind, Read, Result, Seek, Write}; |
| 6 | |
| 7 | use super::*; |
| 8 | use crate::{bail, ensure, err}; |
| 9 | |
| 10 | // ========================================================================= // |
| 11 | |
| 12 | impl Header { |
| 13 | fn write_gnu<W>( |
| 14 | &self, |
| 15 | deterministic: bool, |
| 16 | writer: &mut W, |
| 17 | names: &HashMap<Vec<u8>, usize>, |
| 18 | ) -> Result<()> |
| 19 | where |
| 20 | W: Write, |
| 21 | { |
| 22 | self.validate()?; |
| 23 | if self.identifier.len() > 15 { |
| 24 | let offset = names[&self.identifier]; |
| 25 | write!(writer, "/{:<15}", offset)?; |
| 26 | } else { |
| 27 | writer.write_all(&self.identifier)?; |
| 28 | writer.write_all(b"/")?; |
| 29 | writer.write_all(&vec![b' '; 15 - self.identifier.len()])?; |
| 30 | } |
| 31 | |
| 32 | if deterministic { |
| 33 | write!( |
| 34 | writer, |
| 35 | "{:<12}{:<6}{:<6}{:<8o}{:<10}`\n", |
| 36 | 0, 0, 0, 0o644, self.size |
| 37 | )?; |
| 38 | } else { |
| 39 | write!( |
| 40 | writer, |
| 41 | "{:<12}{:<6}{:<6}{:<8o}{:<10}`\n", |
| 42 | self.mtime, self.uid, self.gid, self.mode, self.size |
| 43 | )?; |
| 44 | } |
| 45 | |
| 46 | Ok(()) |
| 47 | } |
| 48 | } |
| 49 | // ========================================================================= // |
| 50 | |
| 51 | /// Builder for GNU archive format |
| 52 | /// |
| 53 | /// # TL;DR |
| 54 | /// The GNU format is a backwards incompatible archive format that diverges from the legacy Unix |
| 55 | /// archive format in the following significant ways: |
| 56 | /// |
| 57 | /// 1) It can contain a binary symbol table that needs to be the first member of the archive. |
| 58 | /// This table can contain either 32bit or 64bit offsets pointing to the entities that symbols |
| 59 | /// relate to. |
| 60 | /// |
| 61 | /// Unlike the BSD tables the GNU tables are _somewhat_ more formally defined and are simpler in |
| 62 | /// construction. |
| 63 | /// |
| 64 | /// 2) The handling of extended strings is done with a string lookup table (either as the first of |
| 65 | /// second member) which is little more than a large string array. |
| 66 | /// |
| 67 | /// 3) Extensions exist to create a rare format known as a thin-archive. |
| 68 | /// |
| 69 | /// 4) GNU archives have a formal [deterministic mode](#deterministic-archives) that is important |
| 70 | /// for build systems and toolchains. |
| 71 | /// |
| 72 | /// Most tools outside of BSD targets tend to use GNU format as the defacto standard, and it is |
| 73 | /// well-supported by LLVM and GNU toolchains. More subtle variants of this format exist such as |
| 74 | /// the unimplemented Microsoft extended ECOFF archive. |
| 75 | /// |
| 76 | /// # Layout |
| 77 | /// Except where indicated, the metadata for the archive is typically encoded as ascii strings. All |
| 78 | /// ascii strings in an archive are padded to the length of the given field with ascii space `0x20` |
| 79 | /// as the fill value. This gives an archive a general fixed format look if opened in a text |
| 80 | /// editor. |
| 81 | /// |
| 82 | /// Data is emplaced inline directly after a header record, no manipulations are done on data |
| 83 | /// stored in an archive, and there are no restrictions on what data can be stored in an archive. |
| 84 | /// Data might have a padding character (`\n`) added if the entity would be on an odd byte |
| 85 | /// boundary, but this is purely an internal detail of the format and not visible in any metadata. |
| 86 | /// |
| 87 | /// **Header** |
| 88 | /// |
| 89 | /// | Section | Type | |
| 90 | /// |-----------------|---------------------| |
| 91 | /// | Magic signature | Literal `!<arch>\n` | |
| 92 | /// |
| 93 | /// **Entity Header** |
| 94 | /// |
| 95 | /// | Section | Type | Notes | |
| 96 | /// |---------|----------------|--------------------------------------------------------------------------------------------------| |
| 97 | /// | Name | `[u8; 16]` | Gnu handles strings in a manner that _effectively_ reduces this to 15 bytes | |
| 98 | /// | MTime | `[u8; 12]` | Seconds since the Unix epoch. Often `0` as per [deterministic archives](#deterministic-archives) | |
| 99 | /// | Uid | `[u8; 6]` | Unix plain user id. Often `0` as per [deterministic archives](#deterministic-archives) | |
| 100 | /// | Gid | `[u8; 6]` | Unix plain group id. Often `0` as per [deterministic archives](#deterministic-archives) | |
| 101 | /// | Mode | `[u8; 8]` | Unix file mode in Octal. Often `0` as per [deterministic archives](#deterministic-archives) | |
| 102 | /// | Size | `[u8; 10]` | Entity data size in bytes, the size _does not reflect_ any padding | |
| 103 | /// | End | Literal `\`\n` | Marks the end of the entity header | |
| 104 | /// |
| 105 | /// **Symbol table (if present)** |
| 106 | /// |
| 107 | /// Symbol tables are prepended with an entity header, although most implementations choose to make |
| 108 | /// the header all spaces in contrast to general header format for [deterministic |
| 109 | /// archives](#Deterministic Archives) but with the same general effect. |
| 110 | /// |
| 111 | /// The name for the entity for the symbol table is either `//` or `/SYM64/` dependent on if the |
| 112 | /// overall size of the archive crosses the maximum addressable size allowed by 32 bits. |
| 113 | /// |
| 114 | /// | Section | Type | Notes | |
| 115 | /// |----------|-------------------|---------------------------------------------------------| |
| 116 | /// | Num syms | `u32` / `u64` | _Generally_ `u32` but can be `u64` for > 4Gb archives | |
| 117 | /// | Offsets | `[u32]` / `[u64]` | Pointer from a symbol to the relevant archive entity | |
| 118 | /// | Names | `[c_str]` | The name of each symbol as a plain C style string array | |
| 119 | /// |
| 120 | /// **Extended strings (if present)** |
| 121 | /// |
| 122 | /// GNU archives generally encode names inline in the format `/some_name.o/`. |
| 123 | /// |
| 124 | /// The bracketed `/` pairing allows GNU archives to contain embedded spaces and other metachars |
| 125 | /// (excluding `/` itself). |
| 126 | /// |
| 127 | /// If the name is _greater than_ 15 bytes it is encoded as offset number into a string table. The |
| 128 | /// string table is one of the first few members in the archive and is given as strings separated |
| 129 | /// by the byte sequence `[0x2F, 0x0A]` (or `\\/n` in ascii). |
| 130 | /// No padding is done in the string table itself and the offset written to the entity header is zero |
| 131 | /// based from the start of the string table. |
| 132 | /// |
| 133 | /// The entity name for the string table is formatted as `/#offset`, for example, for an extended |
| 134 | /// name starting at offset `4853` the value written to the entity header becomes `/#4853` |
| 135 | /// |
| 136 | /// ## Deterministic Archives |
| 137 | /// The existence of several variables in entity headers make the format poorly suited to |
| 138 | /// consistent generation of archives. This confuses toolchains which may interpret frequently |
| 139 | /// changing headers as a change to the overall archive and force needless recomputations. |
| 140 | /// |
| 141 | /// As such, a backwards compatible extension exists for GNU archives where all variable fields not |
| 142 | /// directly related to an entities data are set to ascii `0`. This is known as deterministic mode |
| 143 | /// and is common for most modern in use unix archives (the format has long since lost its original |
| 144 | /// duty as a general archive format and is now mostly used for toolchain operations). |
| 145 | pub struct GnuBuilder<W: Write + Seek> { |
| 146 | writer: W, |
| 147 | deterministic: bool, |
| 148 | short_names: HashSet<Vec<u8>>, |
| 149 | long_names: HashMap<Vec<u8>, usize>, |
| 150 | symbol_table_relocations: Vec<Vec<u64>>, |
| 151 | symbol_index: usize, |
| 152 | } |
| 153 | |
| 154 | impl<W: Write + Seek> GnuBuilder<W> { |
| 155 | /// The third argument is a map from file identifier to the name of all symbols in the file. |
| 156 | /// Create a new archive builder with the underlying writer object as the |
| 157 | /// destination of all data written. The `identifiers` parameter must give |
| 158 | /// the complete list of entry identifiers that will be included in this |
| 159 | /// archive. The last argument is a map from file identifier to the name of |
| 160 | /// all symbols in the file. |
| 161 | pub fn new_with_symbol_table( |
| 162 | mut writer: W, |
| 163 | deterministic: bool, |
| 164 | identifiers: Vec<Vec<u8>>, |
| 165 | symbol_table: Vec<Vec<Vec<u8>>>, |
| 166 | ) -> Result<GnuBuilder<W>> { |
| 167 | let mut short_names = HashSet::<Vec<u8>>::new(); |
| 168 | let mut long_names = HashMap::<Vec<u8>, usize>::new(); |
| 169 | let mut name_table_size: usize = 0; |
| 170 | for identifier in identifiers.into_iter() { |
| 171 | let length = identifier.len(); |
| 172 | if length > 15 { |
| 173 | long_names.insert(identifier, name_table_size); |
| 174 | name_table_size += length + 2; |
| 175 | } else { |
| 176 | short_names.insert(identifier); |
| 177 | } |
| 178 | } |
| 179 | let name_table_needs_padding = name_table_size % 2 != 0; |
| 180 | if name_table_needs_padding { |
| 181 | name_table_size += 3; // ` /\n` |
| 182 | } |
| 183 | |
| 184 | writer.write_all(GLOBAL_HEADER)?; |
| 185 | |
| 186 | let mut symbol_table_relocations: Vec<Vec<u64>> = Vec::with_capacity(symbol_table.len()); |
| 187 | if !symbol_table.is_empty() { |
| 188 | let wordsize = std::mem::size_of::<u32>(); |
| 189 | let symbol_count: usize = symbol_table.iter().map(|symbols| symbols.len()).sum(); |
| 190 | let symbols = symbol_table.iter().flatten(); |
| 191 | let mut symbol_table_size: usize = wordsize |
| 192 | + wordsize * symbol_count |
| 193 | + symbols.map(|symbol| symbol.len() + 1).sum::<usize>(); |
| 194 | let symbol_table_needs_padding = symbol_table_size % 2 != 0; |
| 195 | if symbol_table_needs_padding { |
| 196 | symbol_table_size += 3; // ` /\n` |
| 197 | } |
| 198 | |
| 199 | write!( |
| 200 | writer, |
| 201 | "{:<16}{:<12}{:<6}{:<6}{:<8o}{:<10}`\n", |
| 202 | GNU_SYMBOL_LOOKUP_TABLE_ID, 0, 0, 0, 0, symbol_table_size |
| 203 | )?; |
| 204 | |
| 205 | writer.write_all(&u32::to_be_bytes(u32::try_from(symbol_count).map_err( |
| 206 | |_| err!("Too many symbols for 32bit table `{}`", symbol_count), |
| 207 | )?))?; |
| 208 | |
| 209 | for symbols in &symbol_table { |
| 210 | let mut sym_rels = Vec::new(); |
| 211 | for _symbol in symbols { |
| 212 | sym_rels.push(writer.stream_position()?); |
| 213 | writer.write_all(&u32::to_be_bytes(0xcafebabe))?; |
| 214 | } |
| 215 | symbol_table_relocations.push(sym_rels); |
| 216 | } |
| 217 | |
| 218 | for symbol in symbol_table.iter().flatten() { |
| 219 | writer.write_all(symbol)?; |
| 220 | writer.write_all(b"\0")?; |
| 221 | } |
| 222 | if symbol_table_needs_padding { |
| 223 | writer.write_all(b" /\n")?; |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | if !long_names.is_empty() { |
| 228 | write!( |
| 229 | writer, |
| 230 | "{:<48}{:<10}`\n", |
| 231 | GNU_NAME_TABLE_ID, name_table_size |
| 232 | )?; |
| 233 | let mut entries: Vec<(usize, &[u8])> = long_names |
| 234 | .iter() |
| 235 | .map(|(id, &start)| (start, id.as_slice())) |
| 236 | .collect(); |
| 237 | entries.sort(); |
| 238 | for (_, id) in entries { |
| 239 | writer.write_all(id)?; |
| 240 | writer.write_all(b"/\n")?; |
| 241 | } |
| 242 | if name_table_needs_padding { |
| 243 | writer.write_all(b" /\n")?; |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | Ok(GnuBuilder { |
| 248 | writer, |
| 249 | deterministic, |
| 250 | short_names, |
| 251 | long_names, |
| 252 | symbol_table_relocations, |
| 253 | symbol_index: 0, |
| 254 | }) |
| 255 | } |
| 256 | |
| 257 | /// Adds a new entry to this archive. |
| 258 | pub fn append<R: Read>(&mut self, header: &Header, mut data: R) -> Result<()> { |
| 259 | let is_long_name = header.identifier().len() > 15; |
| 260 | let has_name = if is_long_name { |
| 261 | self.long_names.contains_key(header.identifier()) |
| 262 | } else { |
| 263 | self.short_names.contains(header.identifier()) |
| 264 | }; |
| 265 | |
| 266 | ensure!( |
| 267 | has_name, |
| 268 | "Identifier `{:?}` was not in the list of identifiers passed to GnuBuilder::new()", |
| 269 | String::from_utf8_lossy(header.identifier()) |
| 270 | ); |
| 271 | |
| 272 | if let Some(relocs) = self.symbol_table_relocations.get(self.symbol_index) { |
| 273 | let entry_offset = self.writer.stream_position()?; |
| 274 | let entry_offset_bytes = u32::to_be_bytes( |
| 275 | u32::try_from(entry_offset).map_err(|_| err!("Archive larger than 4GB"))?, |
| 276 | ); |
| 277 | for &reloc_offset in relocs { |
| 278 | self.writer.seek(io::SeekFrom::Start(reloc_offset))?; |
| 279 | self.writer.write_all(&entry_offset_bytes)?; |
| 280 | } |
| 281 | self.writer.seek(io::SeekFrom::Start(entry_offset))?; |
| 282 | self.symbol_index += 1; |
| 283 | } |
| 284 | |
| 285 | header.write_gnu(self.deterministic, &mut self.writer, &self.long_names)?; |
| 286 | let actual_size = io::copy(&mut data, &mut self.writer)?; |
| 287 | if actual_size != header.size() { |
| 288 | bail!( |
| 289 | "Wrong file size (header.size() = `{}`, actual = `{}`)", |
| 290 | header.size(), |
| 291 | actual_size |
| 292 | ); |
| 293 | } |
| 294 | if actual_size % 2 != 0 { |
| 295 | self.writer.write_all(&[b'\n'])?; |
| 296 | } |
| 297 | |
| 298 | Ok(()) |
| 299 | } |
| 300 | } |