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
use debugid::DebugId;
use object::FileKind;
use pdb_addr2line::pdb::Error as PdbError;
use std::path::PathBuf;
use thiserror::Error;

use crate::{breakpad::BreakpadParseError, CodeId, FatArchiveMember, LibraryInfo};

/// The error type used in this crate.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
    #[error("Unmatched breakpad_id: Expected {0}, but received {1}")]
    UnmatchedDebugId(DebugId, DebugId),

    #[error("Unmatched breakpad_id: Expected {0}, but received {1:?}")]
    UnmatchedDebugIdOptional(DebugId, Option<DebugId>),

    #[error("Unmatched CodeId: Expected {0}, but received {1:?}")]
    UnmatchedCodeId(CodeId, Option<CodeId>),

    #[error("The Breakpad sym file was malformed, causing a parsing error: {0}")]
    BreakpadParsing(#[from] BreakpadParseError),

    #[error("Invalid index {0} for file or inline_origin in breakpad sym file")]
    InvalidFileOrInlineOriginIndexInBreakpadFile(u32),

    #[error("Invalid breakpad ID {0}")]
    InvalidBreakpadId(String),

    #[error("Not enough information was supplied to identify the requested binary.")]
    NotEnoughInformationToIdentifyBinary,

    #[error("Could not determine the FileKind of the external file.")]
    CouldNotDetermineExternalFileFileKind,

    #[error("External file has an unexpected FileKind: {0:?}")]
    UnexpectedExternalFileFileKind(FileKind),

    #[error("Not enough information was supplied to identify the requested symbol map. The debug ID is required.")]
    NotEnoughInformationToIdentifySymbolMap,

    #[error("The FileLocation for the debug file does not support loading dyld subcache files.")]
    FileLocationRefusedSubcacheLocation,

    #[error("The FileLocation for the debug file does not support loading external objects.")]
    FileLocationRefusedExternalObjectLocation,

    #[error(
        "The FileLocation for the binary file does not allow following the PDB path found in it."
    )]
    FileLocationRefusedPdbLocation,

    #[error("The FileLocation for the debug file does not support loading source files.")]
    FileLocationRefusedSourceFileLocation,

    #[error(
        "No disambiguator supplied for universal binary, available images: {}", format_multiarch_members(.0)
    )]
    NoDisambiguatorForFatArchive(Vec<FatArchiveMember>),

    #[error("The universal binary (fat archive) was empty")]
    EmptyFatArchive,

    #[error("No match in multi-arch binary, available UUIDs: {}", format_multiarch_members(.0))]
    NoMatchMultiArch(Vec<FatArchiveMember>),

    #[error("Couldn't get symbols from system library, errors: {}", format_errors(.0))]
    NoLuckMacOsSystemLibrary(Vec<Error>),

    #[error("CRC mismatch on file found via GNU debug link, got {0}, expected {1}")]
    DebugLinkCrcMismatch(u32, u32),

    #[error("PDB error: {1} ({0})")]
    PdbError(&'static str, PdbError),

    #[error("pdb-addr2line error: {1} ({0})")]
    PdbAddr2lineErrorWithContext(&'static str, #[source] pdb_addr2line::Error),

    #[error("Invalid input: {0}")]
    InvalidInputError(&'static str),

    #[error("Object could not parse the file as {0:?}: {1}")]
    ObjectParseError(object::read::FileKind, #[source] object::read::Error),

    #[error("Dyld cache parsing error: {0}")]
    DyldCacheParseError(#[source] object::read::Error),

    #[error("The dyld shared cache file did not include an entry for the dylib at {0}")]
    NoMatchingDyldCacheImagePath(String),

    #[error("MachOHeader parsing error: {0}")]
    MachOHeaderParseError(#[source] object::read::Error),

    #[error("get_candidate_paths_for_debug_file helper callback for {0:?} returned error: {1}")]
    HelperErrorDuringGetCandidatePathsForDebugFile(
        LibraryInfo,
        #[source] Box<dyn std::error::Error + Send + Sync>,
    ),

    #[error("get_candidate_paths_for_binary helper callback for returned error: {0}")]
    HelperErrorDuringGetCandidatePathsForBinary(#[source] Box<dyn std::error::Error + Send + Sync>),

    #[error("get_dyld_shared_cache_paths helper callback returned error: {0}")]
    HelperErrorDuringGetDyldSharedCachePaths(#[source] Box<dyn std::error::Error + Send + Sync>),

    #[error("open_file helper callback for file {0} returned error: {1}")]
    HelperErrorDuringOpenFile(String, #[source] Box<dyn std::error::Error + Send + Sync>),

    #[error("FileContents read_bytes_at for file {0} returned error: {1}")]
    HelperErrorDuringFileReading(String, #[source] Box<dyn std::error::Error + Send + Sync>),

    #[error("No candidate path for binary, for {0:?} {1:?}")]
    NoCandidatePathForBinary(Option<String>, Option<DebugId>),

    #[error("No candidate path for dyld shared cache")]
    NoCandidatePathForDyldCache,

    #[error("No candidate path for binary, for {0:?}")]
    NoCandidatePathForDebugFile(LibraryInfo),

    #[error("No associated PDB file with the right debug ID was found for the PE (Windows) binary at path {0}")]
    NoMatchingPdbForBinary(String),

    #[error("The PE (Windows) binary at path {0} did not contain information about an associated PDB file")]
    NoDebugInfoInPeBinary(String),

    #[error("In the PE (Windows) binary at path {0}, the embedded path to the PDB file was not valid utf-8.")]
    PdbPathNotUtf8(String),

    #[error("In the PE (Windows) binary, the embedded path to the PDB file did not end with a file name: {0}")]
    PdbPathWithoutFilename(String),

    #[error("Could not parse archive file at {0}, ArchiveFile::parse returned error: {1}.")]
    ArchiveParseError(PathBuf, #[source] Box<dyn std::error::Error + Send + Sync>),

    #[error("Could not find file {0} in the archive file.")]
    FileNotInArchive(String),

    #[error("Error while getting function info from PDB: {0}")]
    PdbAddr2lineError(
        #[from]
        #[source]
        pdb_addr2line::Error,
    ),

    #[error("Error while parsing srcsrv stream from PDB: {0}")]
    SrcSrvParseError(
        #[from]
        #[source]
        srcsrv::ParseError,
    ),

    #[error("Error while evaluating srcsrv entry PDB: {0}")]
    SrcSrvEvalError(
        #[from]
        #[source]
        srcsrv::EvalError,
    ),

    #[error("Could not create addr2line Context: {0}")]
    Addr2lineContextCreationError(#[source] gimli::Error),
}

fn format_errors(errors: &[Error]) -> String {
    errors
        .iter()
        .map(|e| format!("{}", e))
        .collect::<Vec<String>>()
        .join(", ")
}

fn format_multiarch_members(members: &[FatArchiveMember]) -> String {
    members
        .iter()
        .map(|member| {
            let uuid_string = member
                .uuid
                .map(|uuid| DebugId::from_uuid(uuid).breakpad().to_string());
            format!(
                "{} ({} {:08x}/{:08x})",
                uuid_string.as_deref().unwrap_or("<no debug ID>"),
                member.arch.as_deref().unwrap_or("<unrecognized arch>"),
                member.cputype,
                member.cpusubtype
            )
        })
        .collect::<Vec<String>>()
        .join(", ")
}

pub trait Context<T> {
    fn context(self, context_description: &'static str) -> Result<T, Error>;
}

impl<T> Context<T> for std::result::Result<T, PdbError> {
    fn context(self, context_description: &'static str) -> Result<T, Error> {
        self.map_err(|e| Error::PdbError(context_description, e))
    }
}

impl<T> Context<T> for std::result::Result<T, pdb_addr2line::Error> {
    fn context(self, context_description: &'static str) -> Result<T, Error> {
        self.map_err(|e| Error::PdbAddr2lineErrorWithContext(context_description, e))
    }
}

impl From<PdbError> for Error {
    fn from(err: PdbError) -> Error {
        Error::PdbError("Unknown", err)
    }
}

impl Error {
    pub fn enum_as_string(&self) -> &'static str {
        match self {
            Error::UnmatchedDebugId(_, _) => "UnmatchedDebugId",
            Error::NoDisambiguatorForFatArchive(_) => "NoDisambiguatorForFatArchive",
            Error::BreakpadParsing(_) => "BreakpadParsing",
            Error::NotEnoughInformationToIdentifyBinary => "NotEnoughInformationToIdentifyBinary",
            Error::NotEnoughInformationToIdentifySymbolMap => {
                "NotEnoughInformationToIdentifySymbolMap"
            }
            Error::InvalidFileOrInlineOriginIndexInBreakpadFile(_) => {
                "InvalidFileOrInlineOriginIndexInBreakpadFile"
            }
            Error::UnmatchedDebugIdOptional(_, _) => "UnmatchedDebugIdOptional",
            Error::DebugLinkCrcMismatch(_, _) => "DebugLinkCrcMismatch",
            Error::UnmatchedCodeId(_, _) => "UnmatchedCodeId",
            Error::InvalidBreakpadId(_) => "InvalidBreakpadId",
            Error::EmptyFatArchive => "EmptyFatArchive",
            Error::CouldNotDetermineExternalFileFileKind => "CouldNotDetermineExternalFileFileKind",
            Error::FileLocationRefusedSubcacheLocation => "FileLocationRefusedSubcacheLocation",
            Error::FileLocationRefusedExternalObjectLocation => {
                "FileLocationRefusedExternalObjectLocation"
            }
            Error::FileLocationRefusedPdbLocation => "FileLocationRefusedPdbLocation",
            Error::FileLocationRefusedSourceFileLocation => "FileLocationRefusedSourceFileLocation",
            Error::UnexpectedExternalFileFileKind(_) => "UnexpectedExternalFileFileKind",
            Error::NoMatchMultiArch(_) => "NoMatchMultiArch",
            Error::NoLuckMacOsSystemLibrary(_) => "NoLuckMacOsSystemLibrary",
            Error::PdbError(_, _) => "PdbError",
            Error::PdbAddr2lineErrorWithContext(_, _) => "PdbAddr2lineErrorWithContext",
            Error::InvalidInputError(_) => "InvalidInputError",
            Error::DyldCacheParseError(_) => "DyldCacheParseError",
            Error::NoMatchingDyldCacheImagePath(_) => "NoMatchingDyldCacheImagePath",
            Error::ObjectParseError(_, _) => "ObjectParseError",
            Error::MachOHeaderParseError(_) => "MachOHeaderParseError",
            Error::HelperErrorDuringGetCandidatePathsForDebugFile(_, _) => {
                "HelperErrorDuringGetCandidatePathsForDebugFile"
            }
            Error::HelperErrorDuringGetCandidatePathsForBinary(_) => {
                "HelperErrorDuringGetCandidatePathsForBinary"
            }
            Error::HelperErrorDuringGetDyldSharedCachePaths(_) => {
                "HelperErrorDuringGetDyldSharedCachePaths"
            }
            Error::HelperErrorDuringOpenFile(_, _) => "HelperErrorDuringOpenFile",
            Error::HelperErrorDuringFileReading(_, _) => "HelperErrorDuringFileReading",
            Error::NoCandidatePathForDebugFile(_) => "NoCandidatePathForDebugFile",
            Error::NoCandidatePathForBinary(_, _) => "NoCandidatePathForBinary",
            Error::NoCandidatePathForDyldCache => "NoCandidatePathForDyldCache",
            Error::NoDebugInfoInPeBinary(_) => "NoDebugInfoInPeBinary",
            Error::NoMatchingPdbForBinary(_) => "NoMatchingPdbForBinary",
            Error::PdbPathNotUtf8(_) => "PdbPathNotUtf8",
            Error::PdbPathWithoutFilename(_) => "PdbPathWithoutFilename",
            Error::ArchiveParseError(_, _) => "ArchiveParseError",
            Error::FileNotInArchive(_) => "FileNotInArchive",
            Error::PdbAddr2lineError(_) => "PdbAddr2lineError",
            Error::SrcSrvParseError(_) => "SrcSrvParseError",
            Error::SrcSrvEvalError(_) => "SrcSrvEvalError",
            Error::Addr2lineContextCreationError(_) => "Addr2lineContextCreationError",
        }
    }
}