1 //===- Binary.cpp - A generic binary file -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Binary class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/Binary.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/Path.h"
20 // Include headers for createBinary.
21 #include "llvm/Object/Archive.h"
22 #include "llvm/Object/MachOUniversal.h"
23 #include "llvm/Object/ObjectFile.h"
26 using namespace object;
32 Binary::Binary(unsigned int Type, MemoryBuffer *Source)
36 StringRef Binary::getData() const {
37 return Data->getBuffer();
40 StringRef Binary::getFileName() const {
41 return Data->getBufferIdentifier();
44 ErrorOr<Binary *> object::createBinary(MemoryBuffer *Source) {
45 OwningPtr<MemoryBuffer> scopedSource(Source);
46 sys::fs::file_magic type = sys::fs::identify_magic(Source->getBuffer());
48 case sys::fs::file_magic::archive:
49 return Archive::create(scopedSource.take());
50 case sys::fs::file_magic::elf_relocatable:
51 case sys::fs::file_magic::elf_executable:
52 case sys::fs::file_magic::elf_shared_object:
53 case sys::fs::file_magic::elf_core:
54 return ObjectFile::createELFObjectFile(scopedSource.take());
55 case sys::fs::file_magic::macho_object:
56 case sys::fs::file_magic::macho_executable:
57 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
58 case sys::fs::file_magic::macho_core:
59 case sys::fs::file_magic::macho_preload_executable:
60 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
61 case sys::fs::file_magic::macho_dynamic_linker:
62 case sys::fs::file_magic::macho_bundle:
63 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
64 case sys::fs::file_magic::macho_dsym_companion:
65 return ObjectFile::createMachOObjectFile(scopedSource.take());
66 case sys::fs::file_magic::macho_universal_binary:
67 return MachOUniversalBinary::create(scopedSource.take());
68 case sys::fs::file_magic::coff_object:
69 case sys::fs::file_magic::coff_import_library:
70 case sys::fs::file_magic::pecoff_executable:
71 return ObjectFile::createCOFFObjectFile(scopedSource.take());
72 case sys::fs::file_magic::unknown:
73 case sys::fs::file_magic::bitcode:
74 case sys::fs::file_magic::windows_resource: {
75 // Unrecognized object file format.
76 return object_error::invalid_file_type;
79 llvm_unreachable("Unexpected Binary File Type");
82 ErrorOr<Binary *> object::createBinary(StringRef Path) {
83 OwningPtr<MemoryBuffer> File;
84 if (error_code EC = MemoryBuffer::getFileOrSTDIN(Path, File))
86 return createBinary(File.take());