Debian Codegraph @

third_party/rust/embed-manifest/src/embed/coff.rs

raw
1 //! Just as much COFF object file support as is needed to write a resource data segment
2 //! for GNU Windows targets. Inspired by the `write::Object` code from the `object` crate.
3 //!
4 //! Integers are converted from u64 to u32 and added without checking because the manifest
5 //! data cannot get anywhere close to overflowing unless the supplied application name or
6 //! number of dependencies was extremely long. If this code was used more generally or if
7 //! the input was less trustworthy then more checked conversions and checked arithmetic
8 //! would be needed.
9
10 use std::io::{self, Seek, SeekFrom, Write};
11 use std::time::SystemTime;
12
13 #[derive(Debug, Clone, Copy)]
14 pub enum MachineType {
15 I386,
16 X86_64,
17 Aarch64,
18 }
19
20 impl MachineType {
21 pub fn machine(&self) -> u16 {
22 match self {
23 Self::I386 => 0x014c,
24 Self::X86_64 => 0x8664,
25 Self::Aarch64 => 0xaa64,
26 }
27 }
28
29 pub fn relocation_type(&self) -> u16 {
30 match self {
31 Self::I386 => 7,
32 Self::X86_64 => 3,
33 Self::Aarch64 => 2,
34 }
35 }
36 }
37
38 pub struct CoffWriter<W> {
39 /// wrapped writer or buffer
40 writer: W,
41 /// machine type for file header
42 machine_type: MachineType,
43 // size in bytes of resource section data
44 size_of_raw_data: u32,
45 // number of relocations at the end of the section
46 number_of_relocations: u16,
47 }
48
49 impl<W: Write + Seek> CoffWriter<W> {
50 /// Create a new instance wrapping a writer.
51 pub fn new(mut writer: W, machine_type: MachineType) -> io::Result<Self> {
52 // Add space for file header and section table.
53 writer.write_all(&[0; 60])?;
54 Ok(Self {
55 writer,
56 machine_type,
57 size_of_raw_data: 0,
58 number_of_relocations: 0,
59 })
60 }
61
62 /// Add data to a section and return its offset within the section.
63 pub fn add_data(&mut self, data: &[u8]) -> io::Result<u32> {
64 let start = self.size_of_raw_data;
65 self.writer.write_all(data)?;
66 self.size_of_raw_data = start + data.len() as u32;
67 Ok(start)
68 }
69
70 // Pad the resource data to a multiple of `n` bytes.
71 pub fn align_to(&mut self, n: u32) -> io::Result<()> {
72 let offset = self.size_of_raw_data % n;
73 if offset != 0 {
74 let padding = n - offset;
75 for _ in 0..padding {
76 self.writer.write_all(&[0])?;
77 }
78 self.size_of_raw_data += padding;
79 }
80 Ok(())
81 }
82
83 /// Write a relocation for a symbol at the end of the section.
84 pub fn add_relocation(&mut self, address: u32) -> io::Result<()> {
85 self.number_of_relocations += 1;
86 self.writer.write_all(&address.to_le_bytes())?;
87 self.writer.write_all(&[0, 0, 0, 0])?;
88 self.writer.write_all(&self.machine_type.relocation_type().to_le_bytes())
89 }
90
91 /// Write the object and section headers and write the symbol table.
92 pub fn finish(mut self) -> io::Result<W> {
93 // Get the timestamp for the header. `as` is correct here, as the low 32 bits
94 // should be used.
95 let timestamp = SystemTime::now()
96 .duration_since(SystemTime::UNIX_EPOCH)
97 .map_or(0, |d| d.as_secs() as u32);
98
99 // Copy file location of the symbol table.
100 let pointer_to_symbol_table = self.writer.stream_position()? as u32;
101
102 // Write the symbols and auxiliary data for the section.
103 self.writer.write_all(b".rsrc\0\0\0")?; // name
104 self.writer.write_all(&[0, 0, 0, 0])?; // address
105 self.writer.write_all(&[1, 0])?; // section number (1-based)
106 self.writer.write_all(&[0, 0, 3, 1])?; // type = 0, class = static, aux symbols = 1
107 self.writer.write_all(&self.size_of_raw_data.to_le_bytes())?;
108 self.writer.write_all(&self.number_of_relocations.to_le_bytes())?;
109 self.writer.write_all(&[0; 12])?;
110
111 // Write the empty string table.
112 self.writer.write_all(&[0; 4])?;
113
114 // Write the object header.
115 let end_of_file = self.writer.seek(SeekFrom::Start(0))?;
116 self.writer.write_all(&self.machine_type.machine().to_le_bytes())?;
117 self.writer.write_all(&[1, 0])?; // number of sections
118 self.writer.write_all(&timestamp.to_le_bytes())?;
119 self.writer.write_all(&pointer_to_symbol_table.to_le_bytes())?;
120 self.writer.write_all(&[2, 0, 0, 0])?; // number of symbol table entries
121 self.writer.write_all(&[0; 4])?; // optional header size = 0, characteristics = 0
122
123 // Write the section header.
124 self.writer.write_all(b".rsrc\0\0\0")?;
125 self.writer.write_all(&[0; 8])?; // virtual size = 0 and virtual address = 0
126 self.writer.write_all(&self.size_of_raw_data.to_le_bytes())?;
127 self.writer.write_all(&[60, 0, 0, 0])?; // pointer to raw data
128 self.writer.write_all(&(self.size_of_raw_data + 60).to_le_bytes())?; // pointer to relocations
129 self.writer.write_all(&[0; 4])?; // pointer to line numbers
130 self.writer.write_all(&self.number_of_relocations.to_le_bytes())?;
131 self.writer.write_all(&[0; 2])?; // number of line numbers
132 self.writer.write_all(&[0x40, 0, 0x30, 0xc0])?; // characteristics
133
134 // Return the inner writer and dispose of this object.
135 self.writer.seek(SeekFrom::Start(end_of_file))?;
136 Ok(self.writer)
137 }
138 }
139
140 /// Returns the bytes for a resource directory table.
141 ///
142 /// Most of the fields are set to zero, including the timestamp, to aid
143 /// with making builds reproducible.
144 ///
145 /// ```c
146 /// typedef struct {
147 /// DWORD Characteristics,
148 /// DWORD TimeDateStamp,
149 /// WORD MajorVersion,
150 /// WORD MinorVersion,
151 /// WORD NumberOfNamedEntries,
152 /// WORD NumberOfIdEntries
153 /// } IMAGE_RESOURCE_DIRECTORY;
154 /// ```
155 pub fn resource_directory_table(number_of_id_entries: u16) -> [u8; 16] {
156 let mut table = [0; 16];
157 table[14..16].copy_from_slice(&number_of_id_entries.to_le_bytes());
158 table
159 }
160
161 /// Returns the bytes for a resource directory entry for an ID.
162 ///
163 /// ```c
164 /// typedef struct {
165 /// DWORD Name,
166 /// DWORD OffsetToData
167 /// } IMAGE_RESOURCE_DIRECTORY_ENTRY;
168 /// ```
169 pub fn resource_directory_id_entry(id: u32, offset: u32, subdirectory: bool) -> [u8; 8] {
170 let mut entry = [0; 8];
171 entry[0..4].copy_from_slice(&id.to_le_bytes());
172 let flag: u32 = if subdirectory { 0x80000000 } else { 0 };
173 entry[4..8].copy_from_slice(&((offset & 0x7fffffff) | flag).to_le_bytes());
174 entry
175 }
176
177 /// Returns the bytes for a resource data entry.
178 ///
179 /// ```c
180 /// typedef struct {
181 /// DWORD OffsetToData,
182 /// DWORD Size,
183 /// DWORD CodePage,
184 /// DWORD Reserved
185 /// } IMAGE_RESOURCE_DATA_ENTRY;
186 /// ```
187 pub fn resource_data_entry(rva: u32, size: u32) -> [u8; 16] {
188 let mut entry = [0; 16];
189 entry[0..4].copy_from_slice(&rva.to_le_bytes());
190 entry[4..8].copy_from_slice(&size.to_le_bytes());
191 entry
192 }