[Object, MachO] Don't crash on invalid MachO segment load commands.
[oota-llvm.git] / lib / Object / ELFObjectFile.cpp
1 //===- ELFObjectFile.cpp - ELF object file implementation -------*- 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 // Part of the ELFObjectFile class implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Object/ELFObjectFile.h"
15 #include "llvm/Support/MathExtras.h"
16
17 namespace llvm {
18 using namespace object;
19
20 ELFObjectFileBase::ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source)
21     : ObjectFile(Type, Source) {}
22
23 ErrorOr<std::unique_ptr<ObjectFile>>
24 ObjectFile::createELFObjectFile(MemoryBufferRef Obj) {
25   std::pair<unsigned char, unsigned char> Ident =
26       getElfArchType(Obj.getBuffer());
27   std::size_t MaxAlignment =
28       1ULL << countTrailingZeros(uintptr_t(Obj.getBufferStart()));
29
30   if (MaxAlignment < 2)
31     return object_error::parse_failed;
32
33   std::error_code EC;
34   std::unique_ptr<ObjectFile> R;
35   if (Ident.first == ELF::ELFCLASS32) {
36     if (Ident.second == ELF::ELFDATA2LSB)
37       R.reset(new ELFObjectFile<ELFType<support::little, false>>(Obj, EC));
38     else if (Ident.second == ELF::ELFDATA2MSB)
39       R.reset(new ELFObjectFile<ELFType<support::big, false>>(Obj, EC));
40     else
41       llvm_unreachable("Buffer is not an ELF object file!");
42   } else {
43     assert(Ident.first == ELF::ELFCLASS64);
44     if (Ident.second == ELF::ELFDATA2LSB)
45       R.reset(new ELFObjectFile<ELFType<support::little, true>>(Obj, EC));
46     else if (Ident.second == ELF::ELFDATA2MSB)
47       R.reset(new ELFObjectFile<ELFType<support::big, true>>(Obj, EC));
48     else
49       llvm_unreachable("Buffer is not an ELF object file!");
50   }
51
52   if (EC)
53     return EC;
54   return std::move(R);
55 }
56
57 } // end namespace llvm