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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! Common types and errors used in `symbolic`.

use std::borrow::Cow;
use std::fmt;
use std::mem;
use std::str;

#[cfg(feature = "with_dwarf")]
use gimli;

/// Represents endianness.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum Endianness {
    Little,
    Big,
}

impl Default for Endianness {
    #[cfg(target_endian = "little")]
    #[inline]
    fn default() -> Endianness {
        Endianness::Little
    }

    #[cfg(target_endian = "big")]
    #[inline]
    fn default() -> Endianness {
        Endianness::Big
    }
}

#[cfg(feature = "with_dwarf")]
impl gimli::Endianity for Endianness {
    #[inline]
    fn is_big_endian(self) -> bool {
        self == Endianness::Big
    }
}

/// Represents a family of CPUs.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[repr(u32)]
pub enum CpuFamily {
    Unknown,
    Intel32,
    Intel64,
    Arm32,
    Arm64,
    Ppc32,
    Ppc64,
}

/// An error returned for unknown or invalid `Arch`s.
#[derive(Debug, Fail, Clone, Copy)]
#[fail(display = "unknown architecture")]
pub struct UnknownArchError;

/// An enum of supported architectures.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[allow(non_camel_case_types)]
#[repr(u32)]
pub enum Arch {
    Unknown,
    X86,
    X86_64,
    X86_64h,
    Arm,
    ArmV5,
    ArmV6,
    ArmV6m,
    ArmV7,
    ArmV7f,
    ArmV7s,
    ArmV7k,
    ArmV7m,
    ArmV7em,
    Arm64,
    Arm64V8,
    Arm64e,
    Ppc,
    Ppc64,
    #[doc(hidden)]
    __Max,
}

impl Arch {
    /// Creates an arch from the u32 it represents.
    pub fn from_u32(val: u32) -> Result<Arch, UnknownArchError> {
        if val >= (Arch::__Max as u32) {
            Err(UnknownArchError)
        } else {
            Ok(unsafe { mem::transmute(val) })
        }
    }

    /// Constructs an architecture from mach CPU types.
    #[cfg(feature = "with_objects")]
    pub fn from_mach(cputype: u32, cpusubtype: u32) -> Result<Arch, UnknownArchError> {
        use goblin::mach::constants::cputype::*;
        // from dyld-519.2.2
        const CPU_SUBTYPE_ARM64_E: u32 = 2;
        Ok(match (cputype, cpusubtype) {
            (CPU_TYPE_I386, CPU_SUBTYPE_I386_ALL) => Arch::X86,
            (CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL) => Arch::X86_64,
            (CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H) => Arch::X86_64h,
            (CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL) => Arch::Arm64,
            (CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_V8) => Arch::Arm64V8,
            (CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_E) => Arch::Arm64e,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_ALL) => Arch::Arm,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V5TEJ) => Arch::ArmV5,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6) => Arch::ArmV6,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6M) => Arch::ArmV6m,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7) => Arch::ArmV7,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7F) => Arch::ArmV7f,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S) => Arch::ArmV7s,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K) => Arch::ArmV7k,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7M) => Arch::ArmV7m,
            (CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7EM) => Arch::ArmV7em,
            (CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL) => Arch::Ppc,
            (CPU_TYPE_POWERPC64, CPU_SUBTYPE_POWERPC_ALL) => Arch::Ppc64,
            _ => return Err(UnknownArchError),
        })
    }

    /// Constructs an architecture from ELF flags.
    #[cfg(feature = "with_objects")]
    pub fn from_elf(machine: u16) -> Result<Arch, UnknownArchError> {
        use goblin::elf::header::*;
        Ok(match machine {
            EM_386 => Arch::X86,
            EM_X86_64 => Arch::X86_64,
            EM_AARCH64 => Arch::Arm64,
            // NOTE: This could actually be any of the other 32bit ARMs. Since we don't need this
            // information, we use the generic Arch::Arm. By reading CPU_arch and FP_arch attributes
            // from the SHT_ARM_ATTRIBUTES section it would be possible to distinguish the ARM arch
            // version and infer hard/soft FP.
            //
            // For more information, see:
            // http://code.metager.de/source/xref/gnu/src/binutils/readelf.c#11282
            // https://stackoverflow.com/a/20556156/4228225
            EM_ARM => Arch::Arm,
            EM_PPC => Arch::Ppc,
            EM_PPC64 => Arch::Ppc64,
            _ => return Err(UnknownArchError),
        })
    }

    /// Constructs an architecture from ELF flags.
    #[cfg(feature = "with_objects")]
    pub fn from_breakpad(string: &str) -> Result<Arch, UnknownArchError> {
        Ok(match string {
            "x86" => Arch::X86,
            // This is different in minidumps and breakpad symbols
            "x86_64" | "amd64" => Arch::X86_64,
            "arm" => Arch::Arm,
            "arm64" => Arch::Arm64,
            "ppc" => Arch::Ppc,
            "ppc64" => Arch::Ppc64,
            _ => return Err(UnknownArchError),
        })
    }

    /// Returns the breakpad name for this Arch.
    pub fn to_breakpad(self) -> &'static str {
        match self.cpu_family() {
            CpuFamily::Intel32 => "x86",
            // Use the breakpad symbol constant here
            CpuFamily::Intel64 => "x86_64",
            CpuFamily::Arm32 => "arm",
            CpuFamily::Arm64 => "arm64",
            CpuFamily::Ppc32 => "ppc",
            CpuFamily::Ppc64 => "ppc64",
            CpuFamily::Unknown => "unknown",
        }
    }

    /// Returns the CPU family.
    pub fn cpu_family(self) -> CpuFamily {
        match self {
            Arch::Unknown | Arch::__Max => CpuFamily::Unknown,
            Arch::X86 => CpuFamily::Intel32,
            Arch::X86_64 | Arch::X86_64h => CpuFamily::Intel64,
            Arch::Arm64 | Arch::Arm64V8 | Arch::Arm64e => CpuFamily::Arm64,
            Arch::Arm
            | Arch::ArmV5
            | Arch::ArmV6
            | Arch::ArmV6m
            | Arch::ArmV7
            | Arch::ArmV7f
            | Arch::ArmV7s
            | Arch::ArmV7k
            | Arch::ArmV7m
            | Arch::ArmV7em => CpuFamily::Arm32,
            Arch::Ppc => CpuFamily::Ppc32,
            Arch::Ppc64 => CpuFamily::Ppc64,
        }
    }

    /// Returns the native pointer size.
    pub fn pointer_size(self) -> Option<usize> {
        match self {
            Arch::Unknown | Arch::__Max => None,
            Arch::X86_64
            | Arch::X86_64h
            | Arch::Arm64
            | Arch::Arm64V8
            | Arch::Arm64e
            | Arch::Ppc64 => Some(8),
            Arch::X86
            | Arch::Arm
            | Arch::ArmV5
            | Arch::ArmV6
            | Arch::ArmV6m
            | Arch::ArmV7
            | Arch::ArmV7f
            | Arch::ArmV7s
            | Arch::ArmV7k
            | Arch::ArmV7m
            | Arch::ArmV7em
            | Arch::Ppc => Some(4),
        }
    }

    /// Returns the name of the arch.
    pub fn name(self) -> &'static str {
        match self {
            Arch::Unknown | Arch::__Max => "unknown",
            Arch::X86 => "x86",
            Arch::X86_64 => "x86_64",
            Arch::X86_64h => "x86_64h",
            Arch::Arm64 => "arm64",
            Arch::Arm64V8 => "arm64v8",
            Arch::Arm64e => "arm64e",
            Arch::Arm => "arm",
            Arch::ArmV5 => "armv5",
            Arch::ArmV6 => "armv6",
            Arch::ArmV6m => "armv6m",
            Arch::ArmV7 => "armv7",
            Arch::ArmV7f => "armv7f",
            Arch::ArmV7s => "armv7s",
            Arch::ArmV7k => "armv7k",
            Arch::ArmV7m => "armv7m",
            Arch::ArmV7em => "armv7em",
            Arch::Ppc => "ppc",
            Arch::Ppc64 => "ppc64",
        }
    }

    /// The name of the IP register if known.
    pub fn ip_register_name(self) -> Option<&'static str> {
        match self.cpu_family() {
            CpuFamily::Intel32 => Some("eip"),
            CpuFamily::Intel64 => Some("rip"),
            CpuFamily::Arm32 | CpuFamily::Arm64 => Some("pc"),
            CpuFamily::Ppc32 | CpuFamily::Ppc64 => Some("srr0"),
            CpuFamily::Unknown => None,
        }
    }

    /// Returns instruction alignment if fixed.
    pub fn instruction_alignment(self) -> Option<u64> {
        match self.cpu_family() {
            CpuFamily::Arm32 => Some(2),
            CpuFamily::Arm64 => Some(4),
            CpuFamily::Ppc32 => Some(4),
            CpuFamily::Ppc64 => Some(8),
            CpuFamily::Intel32 | CpuFamily::Intel64 => None,
            CpuFamily::Unknown => None,
        }
    }
}

impl Default for Arch {
    fn default() -> Arch {
        Arch::Unknown
    }
}

impl fmt::Display for Arch {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl str::FromStr for Arch {
    type Err = UnknownArchError;

    fn from_str(string: &str) -> Result<Arch, UnknownArchError> {
        Ok(match string {
            // this is an alias that is known among macho users
            "i386" => Arch::X86,
            "x86" => Arch::X86,
            "x86_64" => Arch::X86_64,
            "x86_64h" => Arch::X86_64h,
            "arm64" => Arch::Arm64,
            "arm64v8" => Arch::Arm64V8,
            "arm64e" => Arch::Arm64e,
            "arm" => Arch::Arm,
            "armv5" => Arch::ArmV5,
            "armv6" => Arch::ArmV6,
            "armv6m" => Arch::ArmV6m,
            "armv7" => Arch::ArmV7,
            "armv7f" => Arch::ArmV7f,
            "armv7s" => Arch::ArmV7s,
            "armv7k" => Arch::ArmV7k,
            "armv7m" => Arch::ArmV7m,
            "armv7em" => Arch::ArmV7em,
            "ppc" => Arch::Ppc,
            "ppc64" => Arch::Ppc64,
            _ => return Err(UnknownArchError),
        })
    }
}

#[cfg(feature = "with_serde")]
derive_deserialize_from_str!(Arch, "Arch");

#[cfg(feature = "with_serde")]
derive_serialize_from_display!(Arch);

/// An error returned for unknown or invalid `Language`s.
#[derive(Debug, Fail, Clone, Copy)]
#[fail(display = "unknown language")]
pub struct UnknownLanguageError;

/// Supported programming languages for demangling.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
#[repr(u32)]
pub enum Language {
    Unknown,
    C,
    Cpp,
    D,
    Go,
    ObjC,
    ObjCpp,
    Rust,
    Swift,
    #[doc(hidden)]
    __Max,
}

impl Language {
    /// Creates a language from the u32 it represents.
    pub fn from_u32(val: u32) -> Result<Language, UnknownLanguageError> {
        if val >= (Language::__Max as u32) {
            Err(UnknownLanguageError)
        } else {
            Ok(unsafe { mem::transmute(val) })
        }
    }

    /// Converts a DWARF language tag into a supported language.
    #[cfg(feature = "with_dwarf")]
    pub fn from_dwarf_lang(lang: gimli::DwLang) -> Result<Language, UnknownLanguageError> {
        Ok(match lang {
            gimli::DW_LANG_C | gimli::DW_LANG_C11 | gimli::DW_LANG_C89 | gimli::DW_LANG_C99 => {
                Language::C
            }
            gimli::DW_LANG_C_plus_plus
            | gimli::DW_LANG_C_plus_plus_03
            | gimli::DW_LANG_C_plus_plus_11
            | gimli::DW_LANG_C_plus_plus_14 => Language::Cpp,
            gimli::DW_LANG_D => Language::D,
            gimli::DW_LANG_Go => Language::Go,
            gimli::DW_LANG_ObjC => Language::ObjC,
            gimli::DW_LANG_ObjC_plus_plus => Language::ObjCpp,
            gimli::DW_LANG_Rust => Language::Rust,
            gimli::DW_LANG_Swift => Language::Swift,
            _ => return Err(UnknownLanguageError),
        })
    }

    /// Returns the name of the language.
    pub fn name(self) -> &'static str {
        match self {
            Language::Unknown | Language::__Max => "unknown",
            Language::C => "c",
            Language::Cpp => "cpp",
            Language::D => "d",
            Language::Go => "go",
            Language::ObjC => "objc",
            Language::ObjCpp => "objcpp",
            Language::Rust => "rust",
            Language::Swift => "swift",
        }
    }
}

impl Default for Language {
    fn default() -> Language {
        Language::Unknown
    }
}

impl fmt::Display for Language {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let formatted = match *self {
            Language::Unknown | Language::__Max => "unknown",
            Language::C => "C",
            Language::Cpp => "C++",
            Language::D => "D",
            Language::Go => "Go",
            Language::ObjC => "Objective-C",
            Language::ObjCpp => "Objective-C++",
            Language::Rust => "Rust",
            Language::Swift => "Swift",
        };

        write!(f, "{}", formatted)
    }
}

impl str::FromStr for Language {
    type Err = UnknownLanguageError;

    fn from_str(string: &str) -> Result<Language, UnknownLanguageError> {
        Ok(match string {
            "c" => Language::C,
            "cpp" => Language::Cpp,
            "d" => Language::D,
            "go" => Language::Go,
            "objc" => Language::ObjC,
            "objcpp" => Language::ObjCpp,
            "rust" => Language::Rust,
            "swift" => Language::Swift,
            _ => return Err(UnknownLanguageError),
        })
    }
}

#[cfg(feature = "with_serde")]
derive_deserialize_from_str!(Language, "Language");

#[cfg(feature = "with_serde")]
derive_serialize_from_display!(Language);

/// Represents a potentially mangled symbol.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct Name<'a> {
    string: Cow<'a, str>,
    lang: Option<Language>,
}

impl<'a> Name<'a> {
    /// Constructs a new mangled symbol.
    pub fn new<S>(string: S) -> Name<'a>
    where
        S: Into<Cow<'a, str>>,
    {
        Name {
            string: string.into(),
            lang: None,
        }
    }

    /// Constructs a new mangled symbol with known language.
    pub fn with_language<S>(string: S, lang: Language) -> Name<'a>
    where
        S: Into<Cow<'a, str>>,
    {
        let lang_opt = match lang {
            // Ignore unknown languages and apply heuristics instead
            Language::Unknown | Language::__Max => None,
            _ => Some(lang),
        };

        Name {
            string: string.into(),
            lang: lang_opt,
        }
    }

    /// The raw, mangled string of the symbol.
    pub fn as_str(&self) -> &str {
        &self.string
    }

    /// The language of the mangled symbol.
    pub fn language(&self) -> Option<Language> {
        self.lang
    }
}

impl<'a> AsRef<str> for Name<'a> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<'a> Into<String> for Name<'a> {
    fn into(self) -> String {
        self.string.into()
    }
}

impl<'a> Into<Cow<'a, str>> for Name<'a> {
    fn into(self) -> Cow<'a, str> {
        self.string
    }
}

impl<'a> fmt::Display for Name<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// An error returned for unknown or invalid `ObjectKind`s.
#[derive(Debug, Fail, Clone, Copy)]
#[fail(display = "unknown object kind")]
pub struct UnknownObjectKindError;

/// Represents the physical object file format.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub enum ObjectKind {
    Breakpad,
    Elf,
    MachO,
}

impl ObjectKind {
    /// Returns the name of the object kind.
    pub fn name(self) -> &'static str {
        match self {
            ObjectKind::Breakpad => "breakpad",
            ObjectKind::Elf => "elf",
            ObjectKind::MachO => "macho",
        }
    }
}

impl fmt::Display for ObjectKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl str::FromStr for ObjectKind {
    type Err = UnknownObjectKindError;

    fn from_str(string: &str) -> Result<ObjectKind, UnknownObjectKindError> {
        Ok(match string {
            "breakpad" => ObjectKind::Breakpad,
            "elf" => ObjectKind::Elf,
            "macho" => ObjectKind::MachO,
            _ => return Err(UnknownObjectKindError),
        })
    }
}

#[cfg(feature = "with_serde")]
derive_deserialize_from_str!(ObjectKind, "ObjectKind");

#[cfg(feature = "with_serde")]
derive_serialize_from_display!(ObjectKind);

/// An error returned for unknown or invalid `ObjectClass`es.
#[derive(Debug, Fail, Clone, Copy)]
#[fail(display = "unknown object class")]
pub struct UnknownObjectClassError;

/// Represents the designated use of the object file and hints at its contents.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub enum ObjectClass {
    /// There is no object class specified for this object file.
    None,

    /// The Relocatable file type is the format used for intermediate object
    /// files. It is a very compact format containing all its sections in one
    /// segment. The compiler and assembler usually create one Relocatable file
    /// for each source code file. By convention, the file name extension for
    /// this format is .o.
    Relocatable,

    /// The Executable file type is the format used by standard executable
    /// programs.
    Executable,

    /// The Library file type is for dynamic shared libraries. It contains
    /// some additional tables to support multiple modules. By convention, the
    /// file name extension for this format is .dylib, except for the main
    /// shared library of a framework, which does not usually have a file name
    /// extension.
    Library,

    /// The Dump file type is used to store core files, which are
    /// traditionally created when a program crashes. Core files store the
    /// entire address space of a process at the time it crashed. You can
    /// later run gdb on the core file to figure out why the crash occurred.
    Dump,

    /// The Debug file type designates files that store symbol information
    /// for a corresponding binary file.
    Debug,

    /// The Other type represents any valid object class that does not fit any
    /// of the other classes. These are mostly CPU or OS dependent, or unique
    /// to a single kind of object.
    Other,
}

impl ObjectClass {
    pub fn name(self) -> &'static str {
        match self {
            ObjectClass::None => "none",
            ObjectClass::Relocatable => "rel",
            ObjectClass::Executable => "exe",
            ObjectClass::Library => "lib",
            ObjectClass::Dump => "dump",
            ObjectClass::Debug => "dbg",
            ObjectClass::Other => "other",
        }
    }

    pub fn human_name(self) -> &'static str {
        match self {
            ObjectClass::None => "file",
            ObjectClass::Relocatable => "object",
            ObjectClass::Executable => "executable",
            ObjectClass::Library => "library",
            ObjectClass::Dump => "memory dump",
            ObjectClass::Debug => "debug companion",
            ObjectClass::Other => "file",
        }
    }

    #[cfg(feature = "with_objects")]
    pub fn from_mach(mach_type: u32) -> ObjectClass {
        use goblin::mach::header::*;

        match mach_type {
            MH_OBJECT => ObjectClass::Relocatable,
            MH_EXECUTE => ObjectClass::Executable,
            MH_DYLIB => ObjectClass::Library,
            MH_CORE => ObjectClass::Dump,
            MH_DSYM => ObjectClass::Debug,
            _ => ObjectClass::Other,
        }
    }

    #[cfg(feature = "with_objects")]
    pub fn from_elf(elf_type: u16) -> ObjectClass {
        use goblin::elf::header::*;

        match elf_type {
            ET_NONE => ObjectClass::None,
            ET_REL => ObjectClass::Relocatable,
            ET_EXEC => ObjectClass::Executable,
            ET_DYN => ObjectClass::Library,
            ET_CORE => ObjectClass::Dump,
            _ => ObjectClass::Other,
        }
    }

    #[cfg(feature = "with_objects")]
    pub fn from_elf_full(elf_type: u16, has_interpreter: bool) -> ObjectClass {
        let class = ObjectClass::from_elf(elf_type);

        // When stripping debug information into a separate file with objcopy,
        // the eh_type field still reads ET_EXEC. However, the interpreter is
        // removed. Since an executable without interpreter does not make any
        // sense, we assume ``Debug`` in this case.
        if class == ObjectClass::Executable && !has_interpreter {
            ObjectClass::Debug
        } else {
            class
        }
    }
}

impl fmt::Display for ObjectClass {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if f.alternate() {
            write!(f, "{}", self.human_name())
        } else {
            write!(f, "{}", self.name())
        }
    }
}

impl str::FromStr for ObjectClass {
    type Err = UnknownObjectClassError;

    fn from_str(string: &str) -> Result<ObjectClass, UnknownObjectClassError> {
        Ok(match string {
            "none" => ObjectClass::None,
            "rel" => ObjectClass::Relocatable,
            "exe" => ObjectClass::Executable,
            "lib" => ObjectClass::Library,
            "dump" => ObjectClass::Dump,
            "dbg" => ObjectClass::Debug,
            "other" => ObjectClass::Other,
            _ => return Err(UnknownObjectClassError),
        })
    }
}

#[cfg(feature = "with_serde")]
derive_deserialize_from_str!(ObjectClass, "ObjectClass");

#[cfg(feature = "with_serde")]
derive_serialize_from_display!(ObjectClass);

/// An error returned for unknown or invalid `DebugKind`s.
#[derive(Debug, Fail, Clone, Copy)]
#[fail(display = "unknown debug kind")]
pub struct UnknownDebugKindError;

/// Represents the kind of debug information inside an object.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub enum DebugKind {
    Dwarf,
    Breakpad,
}

impl DebugKind {
    /// Returns the name of the object kind.
    pub fn name(self) -> &'static str {
        match self {
            DebugKind::Dwarf => "dwarf",
            DebugKind::Breakpad => "breakpad",
        }
    }
}

impl fmt::Display for DebugKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl str::FromStr for DebugKind {
    type Err = UnknownDebugKindError;

    fn from_str(string: &str) -> Result<DebugKind, UnknownDebugKindError> {
        Ok(match string {
            "dwarf" => DebugKind::Dwarf,
            "breakpad" => DebugKind::Breakpad,
            _ => return Err(UnknownDebugKindError),
        })
    }
}

#[cfg(feature = "with_serde")]
derive_deserialize_from_str!(DebugKind, "DebugKind");

#[cfg(feature = "with_serde")]
derive_serialize_from_display!(DebugKind);

pub use debugid::*;