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;
33 Binary::Binary(unsigned int Type, MemoryBuffer *Source, bool BufferOwned)
34 : TypeID(Type), BufferOwned(BufferOwned), Data(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 LLVMContext *Context) {
46 std::unique_ptr<MemoryBuffer> scopedSource(Source);
47 sys::fs::file_magic Type = sys::fs::identify_magic(Source->getBuffer());
50 case sys::fs::file_magic::archive:
51 return Archive::create(scopedSource.release());
52 case sys::fs::file_magic::elf_relocatable:
53 case sys::fs::file_magic::elf_executable:
54 case sys::fs::file_magic::elf_shared_object:
55 case sys::fs::file_magic::elf_core:
56 case sys::fs::file_magic::macho_object:
57 case sys::fs::file_magic::macho_executable:
58 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
59 case sys::fs::file_magic::macho_core:
60 case sys::fs::file_magic::macho_preload_executable:
61 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
62 case sys::fs::file_magic::macho_dynamic_linker:
63 case sys::fs::file_magic::macho_bundle:
64 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
65 case sys::fs::file_magic::macho_dsym_companion:
66 case sys::fs::file_magic::coff_object:
67 case sys::fs::file_magic::coff_import_library:
68 case sys::fs::file_magic::pecoff_executable:
69 case sys::fs::file_magic::bitcode:
70 return ObjectFile::createSymbolicFile(scopedSource.release(), true, Type,
72 case sys::fs::file_magic::macho_universal_binary:
73 return MachOUniversalBinary::create(scopedSource.release());
74 case sys::fs::file_magic::unknown:
75 case sys::fs::file_magic::windows_resource:
76 // Unrecognized object file format.
77 return object_error::invalid_file_type;
79 llvm_unreachable("Unexpected Binary File Type");
82 ErrorOr<Binary *> object::createBinary(StringRef Path) {
83 std::unique_ptr<MemoryBuffer> File;
84 if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Path, File))
86 return createBinary(File.release());