1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use crate::constants;
use crate::write::{Address, Error, Result, Writer};
use crate::SectionId;

/// A relocation to be applied to a section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Relocation {
    /// The offset within the section where the relocation should be applied.
    pub offset: usize,
    /// The size of the value to be relocated.
    pub size: u8,
    /// The target of the relocation.
    pub target: RelocationTarget,
    /// The addend to be applied to the relocated value.
    pub addend: i64,
    /// The pointer encoding for relocations in unwind information.
    pub eh_pe: Option<constants::DwEhPe>,
}

/// The target of a relocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelocationTarget {
    /// The relocation target is a symbol.
    ///
    /// The meaning of this value is decided by the writer, but
    /// will typically be an index into a symbol table.
    Symbol(usize),
    /// The relocation target is a section.
    Section(SectionId),
}

/// A `Writer` which also records relocations.
pub trait RelocateWriter {
    /// The type of the writer being used to write the section data.
    type Writer: Writer;

    /// Get the writer being used to write the section data.
    fn writer(&self) -> &Self::Writer;

    /// Get the writer being used to write the section data.
    fn writer_mut(&mut self) -> &mut Self::Writer;

    /// Record a relocation.
    fn relocate(&mut self, relocation: Relocation);
}

impl<T: RelocateWriter> Writer for T {
    type Endian = <<T as RelocateWriter>::Writer as Writer>::Endian;

    fn endian(&self) -> Self::Endian {
        self.writer().endian()
    }

    fn len(&self) -> usize {
        self.writer().len()
    }

    fn write(&mut self, bytes: &[u8]) -> Result<()> {
        self.writer_mut().write(bytes)
    }

    fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
        self.writer_mut().write_at(offset, bytes)
    }

    fn write_address(&mut self, address: Address, size: u8) -> Result<()> {
        match address {
            Address::Constant(val) => self.writer_mut().write_udata(val, size),
            Address::Symbol { symbol, addend } => {
                self.relocate(Relocation {
                    offset: self.len(),
                    size,
                    target: RelocationTarget::Symbol(symbol),
                    addend,
                    eh_pe: None,
                });
                self.writer_mut().write_udata(0, size)
            }
        }
    }

    fn write_offset(&mut self, val: usize, section: SectionId, size: u8) -> Result<()> {
        self.relocate(Relocation {
            offset: self.len(),
            size,
            target: RelocationTarget::Section(section),
            addend: val as i64,
            eh_pe: None,
        });
        self.writer_mut().write_udata(0, size)
    }

    fn write_offset_at(
        &mut self,
        offset: usize,
        val: usize,
        section: SectionId,
        size: u8,
    ) -> Result<()> {
        self.relocate(Relocation {
            offset,
            size,
            target: RelocationTarget::Section(section),
            addend: val as i64,
            eh_pe: None,
        });
        self.writer_mut().write_udata_at(offset, 0, size)
    }

    fn write_eh_pointer(
        &mut self,
        address: Address,
        eh_pe: constants::DwEhPe,
        size: u8,
    ) -> Result<()> {
        match address {
            Address::Constant(_) => self.writer_mut().write_eh_pointer(address, eh_pe, size),
            Address::Symbol { symbol, addend } => {
                let size = match eh_pe.format() {
                    constants::DW_EH_PE_absptr => size,
                    constants::DW_EH_PE_udata2 => 2,
                    constants::DW_EH_PE_udata4 => 4,
                    constants::DW_EH_PE_udata8 => 8,
                    constants::DW_EH_PE_sdata2 => 2,
                    constants::DW_EH_PE_sdata4 => 4,
                    constants::DW_EH_PE_sdata8 => 8,
                    _ => return Err(Error::UnsupportedPointerEncoding(eh_pe)),
                };
                self.relocate(Relocation {
                    offset: self.len(),
                    size,
                    target: RelocationTarget::Symbol(symbol),
                    addend,
                    eh_pe: Some(eh_pe),
                });
                self.writer_mut().write_udata(0, size)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::write::EndianVec;
    use crate::{LittleEndian, SectionId};
    use alloc::vec::Vec;

    struct Section {
        writer: EndianVec<LittleEndian>,
        relocations: Vec<Relocation>,
    }

    impl RelocateWriter for Section {
        type Writer = EndianVec<LittleEndian>;

        fn writer(&self) -> &Self::Writer {
            &self.writer
        }

        fn writer_mut(&mut self) -> &mut Self::Writer {
            &mut self.writer
        }

        fn relocate(&mut self, relocation: Relocation) {
            self.relocations.push(relocation);
        }
    }

    #[test]
    fn test_relocate_writer() {
        let mut expected_data = Vec::new();
        let mut expected_relocations = Vec::new();

        let mut section = Section {
            writer: EndianVec::new(LittleEndian),
            relocations: Vec::new(),
        };

        // No relocation for plain data.
        section.write_udata(0x12345678, 4).unwrap();
        expected_data.extend_from_slice(&0x12345678u32.to_le_bytes());

        // No relocation for a constant address.
        section
            .write_address(Address::Constant(0x87654321), 4)
            .unwrap();
        expected_data.extend_from_slice(&0x87654321u32.to_le_bytes());

        // Relocation for a symbol address.
        let offset = section.len();
        section
            .write_address(
                Address::Symbol {
                    symbol: 1,
                    addend: 0x12345678,
                },
                4,
            )
            .unwrap();
        expected_data.extend_from_slice(&[0; 4]);
        expected_relocations.push(Relocation {
            offset,
            size: 4,
            target: RelocationTarget::Symbol(1),
            addend: 0x12345678,
            eh_pe: None,
        });

        // Relocation for a section offset.
        let offset = section.len();
        section
            .write_offset(0x12345678, SectionId::DebugAbbrev, 4)
            .unwrap();
        expected_data.extend_from_slice(&[0; 4]);
        expected_relocations.push(Relocation {
            offset,
            size: 4,
            target: RelocationTarget::Section(SectionId::DebugAbbrev),
            addend: 0x12345678,
            eh_pe: None,
        });

        // Relocation for a section offset at a specific offset.
        let offset = section.len();
        section.write_udata(0x12345678, 4).unwrap();
        section
            .write_offset_at(offset, 0x12345678, SectionId::DebugStr, 4)
            .unwrap();
        expected_data.extend_from_slice(&[0; 4]);
        expected_relocations.push(Relocation {
            offset,
            size: 4,
            target: RelocationTarget::Section(SectionId::DebugStr),
            addend: 0x12345678,
            eh_pe: None,
        });

        // No relocation for a constant in unwind information.
        section
            .write_eh_pointer(Address::Constant(0x87654321), constants::DW_EH_PE_absptr, 8)
            .unwrap();
        expected_data.extend_from_slice(&0x87654321u64.to_le_bytes());

        // No relocation for a relative constant in unwind information.
        let offset = section.len();
        section
            .write_eh_pointer(
                Address::Constant(offset as u64 - 8),
                constants::DW_EH_PE_pcrel | constants::DW_EH_PE_sdata4,
                8,
            )
            .unwrap();
        expected_data.extend_from_slice(&(-8i32).to_le_bytes());

        // Relocation for a symbol in unwind information.
        let offset = section.len();
        section
            .write_eh_pointer(
                Address::Symbol {
                    symbol: 2,
                    addend: 0x12345678,
                },
                constants::DW_EH_PE_pcrel | constants::DW_EH_PE_sdata4,
                8,
            )
            .unwrap();
        expected_data.extend_from_slice(&[0; 4]);
        expected_relocations.push(Relocation {
            offset,
            size: 4,
            target: RelocationTarget::Symbol(2),
            addend: 0x12345678,
            eh_pe: Some(constants::DW_EH_PE_pcrel | constants::DW_EH_PE_sdata4),
        });

        assert_eq!(section.writer.into_vec(), expected_data);
        assert_eq!(section.relocations, expected_relocations);
    }
}