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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use crate::common::{Format, SectionId};
use crate::constants;
use crate::endianity::Endianity;
use crate::leb128;
use crate::write::{Address, Error, Result};

/// A trait for writing the data to a DWARF section.
///
/// All write operations append to the section unless otherwise specified.
#[allow(clippy::len_without_is_empty)]
pub trait Writer {
    /// The endianity of bytes that are written.
    type Endian: Endianity;

    /// Return the endianity of bytes that are written.
    fn endian(&self) -> Self::Endian;

    /// Return the current section length.
    ///
    /// This may be used as an offset for future `write_at` calls.
    fn len(&self) -> usize;

    /// Write a slice.
    fn write(&mut self, bytes: &[u8]) -> Result<()>;

    /// Write a slice at a given offset.
    ///
    /// The write must not extend past the current section length.
    fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()>;

    /// Write an address.
    ///
    /// If the writer supports relocations, then it must provide its own implementation
    /// of this method.
    // TODO: use write_reference instead?
    fn write_address(&mut self, address: Address, size: u8) -> Result<()> {
        match address {
            Address::Constant(val) => self.write_udata(val, size),
            Address::Symbol { .. } => Err(Error::InvalidAddress),
        }
    }

    /// Write an address with a `.eh_frame` pointer encoding.
    ///
    /// The given size is only used for `DW_EH_PE_absptr` formats.
    ///
    /// If the writer supports relocations, then it must provide its own implementation
    /// of this method.
    fn write_eh_pointer(
        &mut self,
        address: Address,
        eh_pe: constants::DwEhPe,
        size: u8,
    ) -> Result<()> {
        match address {
            Address::Constant(val) => {
                // Indirect doesn't matter here.
                let val = match eh_pe.application() {
                    constants::DW_EH_PE_absptr => val,
                    constants::DW_EH_PE_pcrel => {
                        // TODO: better handling of sign
                        let offset = self.len() as u64;
                        val.wrapping_sub(offset)
                    }
                    _ => {
                        return Err(Error::UnsupportedPointerEncoding(eh_pe));
                    }
                };
                self.write_eh_pointer_data(val, eh_pe.format(), size)
            }
            Address::Symbol { .. } => Err(Error::InvalidAddress),
        }
    }

    /// Write a value with a `.eh_frame` pointer format.
    ///
    /// The given size is only used for `DW_EH_PE_absptr` formats.
    ///
    /// This must not be used directly for values that may require relocation.
    fn write_eh_pointer_data(
        &mut self,
        val: u64,
        format: constants::DwEhPe,
        size: u8,
    ) -> Result<()> {
        match format {
            constants::DW_EH_PE_absptr => self.write_udata(val, size),
            constants::DW_EH_PE_uleb128 => self.write_uleb128(val),
            constants::DW_EH_PE_udata2 => self.write_udata(val, 2),
            constants::DW_EH_PE_udata4 => self.write_udata(val, 4),
            constants::DW_EH_PE_udata8 => self.write_udata(val, 8),
            constants::DW_EH_PE_sleb128 => self.write_sleb128(val as i64),
            constants::DW_EH_PE_sdata2 => self.write_sdata(val as i64, 2),
            constants::DW_EH_PE_sdata4 => self.write_sdata(val as i64, 4),
            constants::DW_EH_PE_sdata8 => self.write_sdata(val as i64, 8),
            _ => Err(Error::UnsupportedPointerEncoding(format)),
        }
    }

    /// Write an offset that is relative to the start of the given section.
    ///
    /// If the writer supports relocations, then it must provide its own implementation
    /// of this method.
    fn write_offset(&mut self, val: usize, _section: SectionId, size: u8) -> Result<()> {
        self.write_udata(val as u64, size)
    }

    /// Write an offset that is relative to the start of the given section.
    ///
    /// If the writer supports relocations, then it must provide its own implementation
    /// of this method.
    fn write_offset_at(
        &mut self,
        offset: usize,
        val: usize,
        _section: SectionId,
        size: u8,
    ) -> Result<()> {
        self.write_udata_at(offset, val as u64, size)
    }

    /// Write a reference to a symbol.
    ///
    /// If the writer supports symbols, then it must provide its own implementation
    /// of this method.
    fn write_reference(&mut self, _symbol: usize, _size: u8) -> Result<()> {
        Err(Error::InvalidReference)
    }

    /// Write a u8.
    fn write_u8(&mut self, val: u8) -> Result<()> {
        let bytes = [val];
        self.write(&bytes)
    }

    /// Write a u16.
    fn write_u16(&mut self, val: u16) -> Result<()> {
        let mut bytes = [0; 2];
        self.endian().write_u16(&mut bytes, val);
        self.write(&bytes)
    }

    /// Write a u32.
    fn write_u32(&mut self, val: u32) -> Result<()> {
        let mut bytes = [0; 4];
        self.endian().write_u32(&mut bytes, val);
        self.write(&bytes)
    }

    /// Write a u64.
    fn write_u64(&mut self, val: u64) -> Result<()> {
        let mut bytes = [0; 8];
        self.endian().write_u64(&mut bytes, val);
        self.write(&bytes)
    }

    /// Write a u8 at the given offset.
    fn write_u8_at(&mut self, offset: usize, val: u8) -> Result<()> {
        let bytes = [val];
        self.write_at(offset, &bytes)
    }

    /// Write a u16 at the given offset.
    fn write_u16_at(&mut self, offset: usize, val: u16) -> Result<()> {
        let mut bytes = [0; 2];
        self.endian().write_u16(&mut bytes, val);
        self.write_at(offset, &bytes)
    }

    /// Write a u32 at the given offset.
    fn write_u32_at(&mut self, offset: usize, val: u32) -> Result<()> {
        let mut bytes = [0; 4];
        self.endian().write_u32(&mut bytes, val);
        self.write_at(offset, &bytes)
    }

    /// Write a u64 at the given offset.
    fn write_u64_at(&mut self, offset: usize, val: u64) -> Result<()> {
        let mut bytes = [0; 8];
        self.endian().write_u64(&mut bytes, val);
        self.write_at(offset, &bytes)
    }

    /// Write unsigned data of the given size.
    ///
    /// Returns an error if the value is too large for the size.
    /// This must not be used directly for values that may require relocation.
    fn write_udata(&mut self, val: u64, size: u8) -> Result<()> {
        match size {
            1 => {
                let write_val = val as u8;
                if val != u64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u8(write_val)
            }
            2 => {
                let write_val = val as u16;
                if val != u64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u16(write_val)
            }
            4 => {
                let write_val = val as u32;
                if val != u64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u32(write_val)
            }
            8 => self.write_u64(val),
            otherwise => Err(Error::UnsupportedWordSize(otherwise)),
        }
    }

    /// Write signed data of the given size.
    ///
    /// Returns an error if the value is too large for the size.
    /// This must not be used directly for values that may require relocation.
    fn write_sdata(&mut self, val: i64, size: u8) -> Result<()> {
        match size {
            1 => {
                let write_val = val as i8;
                if val != i64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u8(write_val as u8)
            }
            2 => {
                let write_val = val as i16;
                if val != i64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u16(write_val as u16)
            }
            4 => {
                let write_val = val as i32;
                if val != i64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u32(write_val as u32)
            }
            8 => self.write_u64(val as u64),
            otherwise => Err(Error::UnsupportedWordSize(otherwise)),
        }
    }

    /// Write a word of the given size at the given offset.
    ///
    /// Returns an error if the value is too large for the size.
    /// This must not be used directly for values that may require relocation.
    fn write_udata_at(&mut self, offset: usize, val: u64, size: u8) -> Result<()> {
        match size {
            1 => {
                let write_val = val as u8;
                if val != u64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u8_at(offset, write_val)
            }
            2 => {
                let write_val = val as u16;
                if val != u64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u16_at(offset, write_val)
            }
            4 => {
                let write_val = val as u32;
                if val != u64::from(write_val) {
                    return Err(Error::ValueTooLarge);
                }
                self.write_u32_at(offset, write_val)
            }
            8 => self.write_u64_at(offset, val),
            otherwise => Err(Error::UnsupportedWordSize(otherwise)),
        }
    }

    /// Write an unsigned LEB128 encoded integer.
    fn write_uleb128(&mut self, val: u64) -> Result<()> {
        let mut bytes = [0u8; 10];
        // bytes is long enough so this will never fail.
        let len = leb128::write::unsigned(&mut { &mut bytes[..] }, val).unwrap();
        self.write(&bytes[..len])
    }

    /// Read an unsigned LEB128 encoded integer.
    fn write_sleb128(&mut self, val: i64) -> Result<()> {
        let mut bytes = [0u8; 10];
        // bytes is long enough so this will never fail.
        let len = leb128::write::signed(&mut { &mut bytes[..] }, val).unwrap();
        self.write(&bytes[..len])
    }

    /// Write an initial length according to the given DWARF format.
    ///
    /// This will only write a length of zero, since the length isn't
    /// known yet, and a subsequent call to `write_initial_length_at`
    /// will write the actual length.
    fn write_initial_length(&mut self, format: Format) -> Result<InitialLengthOffset> {
        if format == Format::Dwarf64 {
            self.write_u32(0xffff_ffff)?;
        }
        let offset = InitialLengthOffset(self.len());
        self.write_udata(0, format.word_size())?;
        Ok(offset)
    }

    /// Write an initial length at the given offset according to the given DWARF format.
    ///
    /// `write_initial_length` must have previously returned the offset.
    fn write_initial_length_at(
        &mut self,
        offset: InitialLengthOffset,
        length: u64,
        format: Format,
    ) -> Result<()> {
        self.write_udata_at(offset.0, length, format.word_size())
    }
}

/// The offset at which an initial length should be written.
#[derive(Debug, Clone, Copy)]
pub struct InitialLengthOffset(usize);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::write;
    use crate::{BigEndian, LittleEndian};

    #[test]
    fn test_writer() {
        let mut w = write::EndianVec::new(LittleEndian);
        w.write_address(Address::Constant(0x1122_3344), 4).unwrap();
        assert_eq!(w.slice(), &[0x44, 0x33, 0x22, 0x11]);
        assert_eq!(
            w.write_address(
                Address::Symbol {
                    symbol: 0,
                    addend: 0
                },
                4
            ),
            Err(Error::InvalidAddress)
        );

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_offset(0x1122_3344, SectionId::DebugInfo, 4)
            .unwrap();
        assert_eq!(w.slice(), &[0x44, 0x33, 0x22, 0x11]);
        w.write_offset_at(1, 0x5566, SectionId::DebugInfo, 2)
            .unwrap();
        assert_eq!(w.slice(), &[0x44, 0x66, 0x55, 0x11]);

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_u8(0x11).unwrap();
        w.write_u16(0x2233).unwrap();
        w.write_u32(0x4455_6677).unwrap();
        w.write_u64(0x8081_8283_8485_8687).unwrap();
        #[rustfmt::skip]
        assert_eq!(w.slice(), &[
            0x11,
            0x33, 0x22,
            0x77, 0x66, 0x55, 0x44,
            0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80,
        ]);
        w.write_u8_at(14, 0x11).unwrap();
        w.write_u16_at(12, 0x2233).unwrap();
        w.write_u32_at(8, 0x4455_6677).unwrap();
        w.write_u64_at(0, 0x8081_8283_8485_8687).unwrap();
        #[rustfmt::skip]
        assert_eq!(w.slice(), &[
            0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80,
            0x77, 0x66, 0x55, 0x44,
            0x33, 0x22,
            0x11,
        ]);

        let mut w = write::EndianVec::new(BigEndian);
        w.write_u8(0x11).unwrap();
        w.write_u16(0x2233).unwrap();
        w.write_u32(0x4455_6677).unwrap();
        w.write_u64(0x8081_8283_8485_8687).unwrap();
        #[rustfmt::skip]
        assert_eq!(w.slice(), &[
            0x11,
            0x22, 0x33,
            0x44, 0x55, 0x66, 0x77,
            0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
        ]);
        w.write_u8_at(14, 0x11).unwrap();
        w.write_u16_at(12, 0x2233).unwrap();
        w.write_u32_at(8, 0x4455_6677).unwrap();
        w.write_u64_at(0, 0x8081_8283_8485_8687).unwrap();
        #[rustfmt::skip]
        assert_eq!(w.slice(), &[
            0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
            0x44, 0x55, 0x66, 0x77,
            0x22, 0x33,
            0x11,
        ]);

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_udata(0x11, 1).unwrap();
        w.write_udata(0x2233, 2).unwrap();
        w.write_udata(0x4455_6677, 4).unwrap();
        w.write_udata(0x8081_8283_8485_8687, 8).unwrap();
        #[rustfmt::skip]
        assert_eq!(w.slice(), &[
            0x11,
            0x33, 0x22,
            0x77, 0x66, 0x55, 0x44,
            0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80,
        ]);
        assert_eq!(w.write_udata(0x100, 1), Err(Error::ValueTooLarge));
        assert_eq!(w.write_udata(0x1_0000, 2), Err(Error::ValueTooLarge));
        assert_eq!(w.write_udata(0x1_0000_0000, 4), Err(Error::ValueTooLarge));
        assert_eq!(w.write_udata(0x00, 3), Err(Error::UnsupportedWordSize(3)));
        w.write_udata_at(14, 0x11, 1).unwrap();
        w.write_udata_at(12, 0x2233, 2).unwrap();
        w.write_udata_at(8, 0x4455_6677, 4).unwrap();
        w.write_udata_at(0, 0x8081_8283_8485_8687, 8).unwrap();
        #[rustfmt::skip]
        assert_eq!(w.slice(), &[
            0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80,
            0x77, 0x66, 0x55, 0x44,
            0x33, 0x22,
            0x11,
        ]);
        assert_eq!(w.write_udata_at(0, 0x100, 1), Err(Error::ValueTooLarge));
        assert_eq!(w.write_udata_at(0, 0x1_0000, 2), Err(Error::ValueTooLarge));
        assert_eq!(
            w.write_udata_at(0, 0x1_0000_0000, 4),
            Err(Error::ValueTooLarge)
        );
        assert_eq!(
            w.write_udata_at(0, 0x00, 3),
            Err(Error::UnsupportedWordSize(3))
        );

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_uleb128(0).unwrap();
        assert_eq!(w.slice(), &[0]);

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_uleb128(u64::MAX).unwrap();
        assert_eq!(
            w.slice(),
            &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1]
        );

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_sleb128(0).unwrap();
        assert_eq!(w.slice(), &[0]);

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_sleb128(i64::MAX).unwrap();
        assert_eq!(
            w.slice(),
            &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0]
        );

        let mut w = write::EndianVec::new(LittleEndian);
        w.write_sleb128(i64::MIN).unwrap();
        assert_eq!(
            w.slice(),
            &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f]
        );

        let mut w = write::EndianVec::new(LittleEndian);
        let offset = w.write_initial_length(Format::Dwarf32).unwrap();
        assert_eq!(w.slice(), &[0, 0, 0, 0]);
        w.write_initial_length_at(offset, 0x1122_3344, Format::Dwarf32)
            .unwrap();
        assert_eq!(w.slice(), &[0x44, 0x33, 0x22, 0x11]);
        assert_eq!(
            w.write_initial_length_at(offset, 0x1_0000_0000, Format::Dwarf32),
            Err(Error::ValueTooLarge)
        );

        let mut w = write::EndianVec::new(LittleEndian);
        let offset = w.write_initial_length(Format::Dwarf64).unwrap();
        assert_eq!(w.slice(), &[0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0]);
        w.write_initial_length_at(offset, 0x1122_3344_5566_7788, Format::Dwarf64)
            .unwrap();
        assert_eq!(
            w.slice(),
            &[0xff, 0xff, 0xff, 0xff, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11]
        );
    }
}