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
// Copyright 2017 pdb Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

// DBI = "Debug Information"

use std::borrow::Cow;
use std::result;

use common::*;
use msf::*;
use FallibleIterator;

/// Provides access to the "DBI" stream inside the PDB.
///
/// This is only minimally implemented; it's really just so `PDB` can find the global symbol table.
///
/// # Example
///
/// ```
/// # use pdb::FallibleIterator;
/// #
/// # fn test() -> pdb::Result<usize> {
/// let file = std::fs::File::open("fixtures/self/foo.pdb")?;
/// let mut pdb = pdb::PDB::open(file)?;
///
/// let dbi = pdb.debug_information()?;

///
/// # let mut count: usize = 0;
/// let mut modules = dbi.modules()?;
/// while let Some(module) = modules.next()? {
///     println!("module name: {}, object file name: {}",
///              module.module_name(), module.object_file_name());
/// #   count += 1;
/// }
///
/// # Ok(count)
/// # }
/// # assert!(test().expect("test") == 194);
#[derive(Debug)]
pub struct DebugInformation<'s> {
    stream: Stream<'s>,
    header: Header,
    header_len: usize,
}

impl<'s> DebugInformation<'s> {
    /// Returns an iterator that can traverse the modules list in sequential order.
    pub fn modules(&self) -> Result<ModuleIter> {
        let mut buf = self.stream.parse_buffer();
        // drop the header
        buf.take(self.header_len)?;
        let modules_buf = buf.take(self.header.module_list_size as usize)?;
        Ok(ModuleIter { buf: modules_buf.into() })
    }
}

pub fn new_debug_information(stream: Stream) -> Result<DebugInformation> {
    let (header, len) = {
        let mut buf = stream.parse_buffer();
        let header = parse_header(&mut buf)?;
        (header, buf.pos())
    };

    Ok(DebugInformation{
        stream: stream,
        header: header,
        header_len: len,
    })
}

pub fn get_header(dbi: &DebugInformation) -> Header {
    dbi.header
}

#[derive(Debug,Copy,Clone)]
pub enum HeaderVersion {
    V41,
    V50,
    V60,
    V70,
    V110,
    OtherValue(u32)
}

impl From<u32> for HeaderVersion {
    fn from(v: u32) -> Self {
        match v {
            930803 => HeaderVersion::V41,
            19960307 => HeaderVersion::V50,
            19970606 => HeaderVersion::V60,
            19990903 => HeaderVersion::V70,
            20091201 => HeaderVersion::V110,
            _ => HeaderVersion::OtherValue(v),
        }
    }
}

/// A DBI header -- `NewDBIHdr`, really -- parsed from a stream.
/// Reference:
/// https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/dbi.h#L124
#[derive(Debug,Copy,Clone)]
pub struct Header {
    pub signature: u32,
    pub version: HeaderVersion,
    pub age: u32,
    pub gs_symbols_stream: u16,

    /*
    https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/dbi.h#L143-L155:
        union {
        struct {
            USHORT      usVerPdbDllMin : 8; // minor version and
            USHORT      usVerPdbDllMaj : 7; // major version and
            USHORT      fNewVerFmt     : 1; // flag telling us we have rbld stored elsewhere (high bit of original major version)
        } vernew;                           // that built this pdb last.
        struct {
            USHORT      usVerPdbDllRbld: 4;
            USHORT      usVerPdbDllMin : 7;
            USHORT      usVerPdbDllMaj : 5;
        } verold;
        USHORT          usVerAll;
    };
    */
    pub internal_version: u16,
    pub ps_symbols_stream: u16,
    // "build version of the pdb dll that built this pdb last."
    pub pdb_dll_build_version: u16,

    pub symbol_records_stream: u16,

    // "rbld version of the pdb dll that built this pdb last."
    pub pdb_dll_rbld_version: u16,
    pub module_list_size: u32,
    pub section_contribution_size: u32,
    pub section_map_size: u32,
    pub file_info_size: u32,

    // "size of the Type Server Map substream"
    pub type_server_map_size: u32,

    // "index of MFC type server"
    pub mfc_type_server_index: u32,

    // "size of optional DbgHdr info appended to the end of the stream"
    pub debug_header_size: u32,

    // "number of bytes in EC substream, or 0 if EC no EC enabled Mods"
    pub ec_substream_size: u32,

    /*
    https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/dbi.h#L187-L192:
        USHORT  fIncLink:1;     // true if linked incrmentally (really just if ilink thunks are present)
        USHORT  fStripped:1;    // true if PDB::CopyTo stripped the private data out
        USHORT  fCTypes:1;      // true if this PDB is using CTypes.
        USHORT  unused:13;      // reserved, must be 0.
    */
    pub flags: u16,

    pub machine_type: u16,
    pub reserved: u32,
}

pub fn parse_header(buf: &mut ParseBuffer) -> Result<Header> {
    let header = Header {
        signature: buf.parse_u32()?,
        version: From::from(buf.parse_u32()?),
        age: buf.parse_u32()?,
        gs_symbols_stream: buf.parse_u16()?,
        internal_version: buf.parse_u16()?,
        ps_symbols_stream: buf.parse_u16()?,
        pdb_dll_build_version: buf.parse_u16()?,
        symbol_records_stream: buf.parse_u16()?,
        pdb_dll_rbld_version: buf.parse_u16()?,
        module_list_size: buf.parse_u32()?,
        section_contribution_size: buf.parse_u32()?,
        section_map_size: buf.parse_u32()?,
        file_info_size: buf.parse_u32()?,
        type_server_map_size: buf.parse_u32()?,
        mfc_type_server_index: buf.parse_u32()?,
        debug_header_size: buf.parse_u32()?,
        ec_substream_size: buf.parse_u32()?,
        flags: buf.parse_u16()?,
        machine_type: buf.parse_u16()?,
        reserved: buf.parse_u32()?,
    };

    if header.signature != 0xffffffff {
        // this is likely a DBIHdr, not a NewDBIHdr
        // it could be promoted:
        //   https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/dbi.cpp#L291-L313
        //   https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/langapi/include/pdb.h#L1180-L1184
        // but that seems like a lot of work
        return Err(Error::UnimplementedFeature("ancient DBI header"));
    }

    Ok(header)
}

/// Information about a module's contribution to a section.
/// `struct SC` in Microsoft's code:
/// https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/include/dbicommon.h#L42
#[derive(Debug, Copy, Clone)]
pub struct DBISectionContribution {
    /// The index of the section.
    section: u16,
    _padding1: u16,
    /// The offset within the section.
    offset: u32,
    /// The size of the contribution, in bytes.
    size: u32,
    /// The characteristics, which map to the `Characteristics` field of
    /// the [`IMAGE_SECTION_HEADER`][1] field in binaries.
    /// [1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms680341(v=vs.85).aspx
    characteristics: u32,
    /// The index of the module.
    module: u16,
    _padding2: u16,
    /// CRC of the contribution(?)
    data_crc: u32,
    /// CRC of relocations(?)
    reloc_crc: u32,
}

/// Information about a module parsed from the DBI stream. Named `MODI` in
/// the Microsoft PDB source:
/// https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/dbi.h#L1197
#[derive(Debug, Copy, Clone)]
pub struct DBIModuleInfo {
    /// Currently open module.
    pub opened: u32,
    /// This module's first section contribution.
    pub section: DBISectionContribution,
    /// Flags, expressed as bitfields in the C struct:
    /// written, EC enabled, unused, tsm
    /// https://github.com/Microsoft/microsoft-pdb/blob/082c5290e5aff028ae84e43affa8be717aa7af73/PDB/dbi/dbi.h#L1201-L1204
    pub flags: u16,
    /// Stream number of module debug info (syms, lines, fpo).
    pub stream: u16,
    /// Size of local symbols debug info in `stream`.
    pub symbols_size: u32,
    /// Size of line number debug info in `stream`.
    pub lines_size: u32,
    /// Size of C13 style line number info in `stream`.
    pub c13_lines_size: u32,
    /// Number of files contributing to this module.
    pub files: u16,
    _padding: u16,
    /// Used as a pointer into an array of filename indicies in the Microsoft code.
    pub filename_offsets: u32,
    /// Source file name index.
    pub source: u32,
    /// Path to compiler PDB name index.
    pub compiler: u32,
}

fn parse_module_info(buf: &mut ParseBuffer) -> Result<DBIModuleInfo> {
    Ok(DBIModuleInfo {
        opened: buf.parse_u32()?,
        section: parse_section_contribution(buf)?,
        flags: buf.parse_u16()?,
        stream: buf.parse_u16()?,
        symbols_size: buf.parse_u32()?,
        lines_size: buf.parse_u32()?,
        c13_lines_size: buf.parse_u32()?,
        files: buf.parse_u16()?,
        _padding: buf.parse_u16()?,
        filename_offsets: buf.parse_u32()?,
        source: buf.parse_u32()?,
        compiler: buf.parse_u32()?,
    })
}

fn parse_section_contribution(buf: &mut ParseBuffer) -> Result<DBISectionContribution> {
    Ok(DBISectionContribution {
        section: buf.parse_u16()?,
        _padding1: buf.parse_u16()?,
        offset: buf.parse_u32()?,
        size: buf.parse_u32()?,
        characteristics: buf.parse_u32()?,
        module: buf.parse_u16()?,
        _padding2: buf.parse_u16()?,
        data_crc: buf.parse_u32()?,
        reloc_crc: buf.parse_u32()?,
    })
}

/// Represents a module from the DBI stream.
///
/// A `Module` is a single item that contributes to the binary, such as an
/// object file or import library.
///
/// Much of the useful information for a `Module` is stored in a separate stream in the PDB.
/// It can be retrieved by calling [`PDB::module_info`] with a specific module.
///
/// [`PDB::module_info`]: struct.PDB.html#method.module_info
#[derive(Debug, Clone)]
pub struct Module<'m> {
    info: DBIModuleInfo,
    module_name: RawString<'m>,
    object_file_name: RawString<'m>,
}

impl<'m> Module<'m> {
    /// The `DBIModuleInfo` from the module info substream in the DBI stream.
    pub fn info(&self) -> &DBIModuleInfo { &self.info }
    /// The module name.
    ///
    /// Usually either a full path to an object file or a string of the form `Import:<dll name>`.
    pub fn module_name(&self) -> Cow<'m, str> {
        self.module_name.to_string()
    }
    /// The object file name.
    ///
    /// May be the same as `module_name` for object files passed directly
    /// to the linker. For modules from static libraries, this is usually
    /// the full path to the archive.
    pub fn object_file_name(&self) -> Cow<'m, str> {
        self.object_file_name.to_string()
    }
}

/// A `ModuleIter` iterates over the modules in the DBI section, producing `Module`s.
#[derive(Debug)]
pub struct ModuleIter<'m> {
    buf: ParseBuffer<'m>,
}

impl<'m> FallibleIterator for ModuleIter<'m> {
    type Item = Module<'m>;
    type Error = Error;

    fn next(&mut self) -> result::Result<Option<Self::Item>, Self::Error> {
        // see if we're at EOF
        if self.buf.len() == 0 {
            return Ok(None);
        }

        let info = parse_module_info(&mut self.buf)?;
        let module_name = self.buf.parse_cstring()?;
        let object_file_name = self.buf.parse_cstring()?;
        self.buf.align(4)?;
        Ok(Some(Module {
            info,
            module_name,
            object_file_name,
        }))
    }
}