implib.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //! COFF import libraries (`.lib`).
  2. //!
  3. //! An umbrella import library tells us which DLL provides each API that a
  4. //! console title may link against. That is the map the runtime needs to
  5. //! decide which of our implementations answers which import.
  6. use object::read::archive::ArchiveFile;
  7. use object::read::coff::{ImportFile, ImportName, ImportType};
  8. use crate::{ImportSymbol, PeError};
  9. /// One `dll!export` pair described by an import library.
  10. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
  11. pub struct LibImport {
  12. pub dll: String,
  13. pub export: ImportSymbol,
  14. pub kind: LibImportKind,
  15. }
  16. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
  17. pub enum LibImportKind {
  18. Code,
  19. Data,
  20. Const,
  21. }
  22. /// Result of reading an import library.
  23. #[derive(Debug, Default)]
  24. pub struct ImportLibrary {
  25. pub imports: Vec<LibImport>,
  26. /// Members that are not short-format import objects (regular objects,
  27. /// long-format import descriptors). Reported so nothing is silently lost.
  28. pub other_members: usize,
  29. }
  30. impl ImportLibrary {
  31. pub fn parse(data: &[u8]) -> Result<Self, PeError> {
  32. let archive = ArchiveFile::parse(data)?;
  33. let mut lib = ImportLibrary::default();
  34. for member in archive.members() {
  35. let member = member?;
  36. let bytes = member.data(data)?;
  37. match ImportFile::parse(bytes) {
  38. Ok(import) => lib.imports.push(LibImport {
  39. dll: String::from_utf8_lossy(import.dll()).into_owned(),
  40. export: match import.import() {
  41. ImportName::Name(name) => ImportSymbol::Name {
  42. hint: 0,
  43. name: String::from_utf8_lossy(name).into_owned(),
  44. },
  45. ImportName::Ordinal(o) => ImportSymbol::Ordinal(o),
  46. },
  47. kind: match import.import_type() {
  48. ImportType::Code => LibImportKind::Code,
  49. ImportType::Data => LibImportKind::Data,
  50. ImportType::Const => LibImportKind::Const,
  51. },
  52. }),
  53. Err(_) => lib.other_members += 1,
  54. }
  55. }
  56. lib.imports.sort();
  57. lib.imports.dedup();
  58. Ok(lib)
  59. }
  60. }