ObjectFile.cpp revision 218893
1//===- ObjectFile.cpp - File format independent object file -----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a file format independent ObjectFile class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Object/ObjectFile.h"
15#include "llvm/ADT/OwningPtr.h"
16#include "llvm/Support/ErrorHandling.h"
17#include "llvm/Support/MemoryBuffer.h"
18#include "llvm/Support/Path.h"
19#include "llvm/Support/system_error.h"
20
21using namespace llvm;
22using namespace object;
23
24ObjectFile::ObjectFile(MemoryBuffer *Object)
25  : MapFile(Object) {
26  assert(MapFile && "Must be a valid MemoryBuffer!");
27  base = reinterpret_cast<const uint8_t *>(MapFile->getBufferStart());
28}
29
30ObjectFile::~ObjectFile() {
31  delete MapFile;
32}
33
34StringRef ObjectFile::getFilename() const {
35  return MapFile->getBufferIdentifier();
36}
37
38ObjectFile *ObjectFile::createObjectFile(MemoryBuffer *Object) {
39  if (!Object || Object->getBufferSize() < 64)
40    return 0;
41  sys::LLVMFileType type = sys::IdentifyFileType(Object->getBufferStart(),
42                                static_cast<unsigned>(Object->getBufferSize()));
43  switch (type) {
44    case sys::ELF_Relocatable_FileType:
45    case sys::ELF_Executable_FileType:
46    case sys::ELF_SharedObject_FileType:
47    case sys::ELF_Core_FileType:
48      return createELFObjectFile(Object);
49    case sys::Mach_O_Object_FileType:
50    case sys::Mach_O_Executable_FileType:
51    case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
52    case sys::Mach_O_Core_FileType:
53    case sys::Mach_O_PreloadExecutable_FileType:
54    case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
55    case sys::Mach_O_DynamicLinker_FileType:
56    case sys::Mach_O_Bundle_FileType:
57    case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
58      return 0;
59    case sys::COFF_FileType:
60      return createCOFFObjectFile(Object);
61    default:
62      llvm_unreachable("Unknown Object File Type");
63  }
64}
65
66ObjectFile *ObjectFile::createObjectFile(StringRef ObjectPath) {
67  OwningPtr<MemoryBuffer> File;
68  if (error_code ec = MemoryBuffer::getFile(ObjectPath, File))
69    return NULL;
70  return createObjectFile(File.take());
71}
72