LLVM 22.0.0git
ObjectFile.cpp
Go to the documentation of this file.
1//===- ObjectFile.cpp - File format independent object file ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a file format independent ObjectFile class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/StringRef.h"
16#include "llvm/Object/Binary.h"
17#include "llvm/Object/COFF.h"
19#include "llvm/Object/Error.h"
20#include "llvm/Object/MachO.h"
21#include "llvm/Object/Wasm.h"
22#include "llvm/Support/Error.h"
25#include "llvm/Support/Format.h"
28#include <cstdint>
29#include <memory>
30#include <system_error>
31
32using namespace llvm;
33using namespace object;
34
36 OS << "SectionedAddress{" << format_hex(Addr.Address, 10);
37 if (Addr.SectionIndex != SectionedAddress::UndefSection)
38 OS << ", " << Addr.SectionIndex;
39 return OS << "}";
40}
41
42void ObjectFile::anchor() {}
43
45 : SymbolicFile(Type, Source) {}
46
49 if (!SymSec) {
50 // TODO: Actually report errors helpfully.
51 consumeError(SymSec.takeError());
52 return false;
53 }
54 return *this == **SymSec;
55}
56
58 uint32_t Flags;
59 if (Error E = getSymbolFlags(Ref).moveInto(Flags))
60 // TODO: Test this error.
61 return std::move(E);
62
63 if (Flags & SymbolRef::SF_Undefined)
64 return 0;
65 if (Flags & SymbolRef::SF_Common)
67 return getSymbolValueImpl(Ref);
68}
69
72 if (!Name)
73 return Name.takeError();
74 OS << *Name;
75 return Error::success();
76}
77
79
81 Expected<StringRef> NameOrErr = getSectionName(Sec);
82 if (NameOrErr)
83 return *NameOrErr == ".llvm.lto";
84 consumeError(NameOrErr.takeError());
85 return false;
86}
87
88bool ObjectFile::isSectionStripped(DataRefImpl Sec) const { return false; }
89
91 return isSectionText(Sec);
92}
93
95 return isSectionData(Sec);
96}
97
98bool ObjectFile::isDebugSection(DataRefImpl Sec) const { return false; }
99
101 return any_of(sections(),
102 [](SectionRef Sec) { return Sec.isDebugSection(); });
103}
104
107 return section_iterator(SectionRef(Sec, this));
108}
109
111 Triple TheTriple;
112 auto Arch = getArch();
113 TheTriple.setArch(Triple::ArchType(Arch));
114
115 auto OS = getOS();
116 if (OS != Triple::UnknownOS)
117 TheTriple.setOS(OS);
118
119 // For ARM targets, try to use the build attributes to build determine
120 // the build target. Target features are also added, but later during
121 // disassembly.
122 if (Arch == Triple::arm || Arch == Triple::armeb)
123 setARMSubArch(TheTriple);
124
125 // TheTriple defaults to ELF, and COFF doesn't have an environment:
126 // something we can do here is indicate that it is mach-o.
127 if (isMachO()) {
129 } else if (isCOFF()) {
130 const auto COFFObj = cast<COFFObjectFile>(this);
131 if (COFFObj->getArch() == Triple::thumb)
132 TheTriple.setTriple("thumbv7-windows");
133 } else if (isXCOFF()) {
134 // XCOFF implies AIX.
135 TheTriple.setOS(Triple::AIX);
137 } else if (isGOFF()) {
138 TheTriple.setOS(Triple::ZOS);
139 TheTriple.setObjectFormat(Triple::GOFF);
140 } else if (TheTriple.isAMDGPU()) {
141 TheTriple.setVendor(Triple::AMD);
142 } else if (TheTriple.isNVPTX()) {
143 TheTriple.setVendor(Triple::NVIDIA);
144 }
145
146 return TheTriple;
147}
148
151 bool InitContent) {
152 StringRef Data = Object.getBuffer();
155
156 switch (Type) {
164 case file_magic::pdb:
175 case file_magic::elf:
180 return createELFObjectFile(Object, InitContent);
193 return createMachOObjectFile(Object);
197 return createCOFFObjectFile(Object);
203 return createWasmObjectFile(Object);
205 return createDXContainerObjectFile(Object);
206 }
207 llvm_unreachable("Unexpected Object File Type");
208}
209
213 MemoryBuffer::getFile(ObjectPath);
214 if (std::error_code EC = FileOrErr.getError())
215 return errorCodeToError(EC);
216 std::unique_ptr<MemoryBuffer> Buffer = std::move(FileOrErr.get());
217
219 createObjectFile(Buffer->getMemBufferRef());
220 if (Error Err = ObjOrErr.takeError())
221 return std::move(Err);
222 std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
223
224 return OwningBinary<ObjectFile>(std::move(Obj), std::move(Buffer));
225}
226
229 const {
231 return ReflectionSectionKind == Swift5ReflectionSectionKind::fieldmd ||
232 ReflectionSectionKind == Swift5ReflectionSectionKind::reflstr ||
233 ReflectionSectionKind == Swift5ReflectionSectionKind::assocty;
234}
uint64_t Addr
std::string Name
Provides ErrorOr<T> smart pointer.
raw_pwrite_stream & OS
Represents either an error or a value T.
Definition: ErrorOr.h:56
reference get()
Definition: ErrorOr.h:149
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
Error takeError()
Take ownership of the stored error.
Definition: Error.h:612
reference get()
Returns a reference to the stored T value.
Definition: Error.h:582
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
LLVM_ABI void setObjectFormat(ObjectFormatType Kind)
Set the object file format.
Definition: Triple.cpp:1645
LLVM_ABI void setTriple(const Twine &Str)
Set all components to the new triple Str.
Definition: Triple.cpp:1621
bool isAMDGPU() const
Definition: Triple.h:903
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
Definition: Triple.h:896
LLVM_ABI void setOS(OSType Kind)
Set the operating system (third) component of the triple to a known type.
Definition: Triple.cpp:1633
LLVM_ABI void setArch(ArchType Kind, SubArchType SubArch=NoSubArch)
Set the architecture (first) component of the triple to a known type.
Definition: Triple.cpp:1625
LLVM_ABI void setVendor(VendorType Kind)
Set the vendor (second) component of the triple to a known type.
Definition: Triple.cpp:1629
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
MemoryBufferRef Data
Definition: Binary.h:38
bool isXCOFF() const
Definition: Binary.h:137
bool isMachO() const
Definition: Binary.h:129
bool isCOFF() const
Definition: Binary.h:133
bool isGOFF() const
Definition: Binary.h:151
virtual bool isBerkeleyText(DataRefImpl Sec) const
Definition: ObjectFile.cpp:90
virtual Expected< section_iterator > getRelocatedSection(DataRefImpl Sec) const
Definition: ObjectFile.cpp:106
uint64_t getCommonSymbolSize(DataRefImpl Symb) const
Definition: ObjectFile.h:309
static Expected< std::unique_ptr< DXContainerObjectFile > > createDXContainerObjectFile(MemoryBufferRef Object)
virtual Expected< StringRef > getSectionName(DataRefImpl Sec) const =0
virtual bool isBerkeleyData(DataRefImpl Sec) const
Definition: ObjectFile.cpp:94
virtual Expected< StringRef > getSymbolName(DataRefImpl Symb) const =0
static Expected< std::unique_ptr< MachOObjectFile > > createMachOObjectFile(MemoryBufferRef Object, uint32_t UniversalCputype=0, uint32_t UniversalIndex=0, size_t MachOFilesetEntryOffset=0)
Create a MachOObjectFile instance from a given buffer.
static Expected< std::unique_ptr< COFFObjectFile > > createCOFFObjectFile(MemoryBufferRef Object)
Error printSymbolName(raw_ostream &OS, DataRefImpl Symb) const override
Definition: ObjectFile.cpp:70
static Expected< std::unique_ptr< ObjectFile > > createELFObjectFile(MemoryBufferRef Object, bool InitContent=true)
Triple makeTriple() const
Create a triple from the data in this object file.
Definition: ObjectFile.cpp:110
virtual bool isSectionText(DataRefImpl Sec) const =0
section_iterator_range sections() const
Definition: ObjectFile.h:331
friend class SectionRef
Definition: ObjectFile.h:263
virtual uint64_t getSymbolValueImpl(DataRefImpl Symb) const =0
virtual bool isDebugSection(DataRefImpl Sec) const
Definition: ObjectFile.cpp:98
virtual void setARMSubArch(Triple &TheTriple) const
Definition: ObjectFile.h:348
static Expected< std::unique_ptr< WasmObjectFile > > createWasmObjectFile(MemoryBufferRef Object)
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:211
virtual uint32_t getSymbolAlignment(DataRefImpl Symb) const
Definition: ObjectFile.cpp:78
virtual bool isSectionData(DataRefImpl Sec) const =0
Expected< uint64_t > getSymbolValue(DataRefImpl Symb) const
Definition: ObjectFile.cpp:57
virtual Triple::OSType getOS() const
Definition: ObjectFile.h:343
bool isReflectionSectionStrippable(llvm::binaryformat::Swift5ReflectionSectionKind ReflectionSectionKind) const
True if the reflection section can be stripped by the linker.
Definition: ObjectFile.cpp:227
virtual bool hasDebugInfo() const
Definition: ObjectFile.cpp:100
static Expected< std::unique_ptr< ObjectFile > > createXCOFFObjectFile(MemoryBufferRef Object, unsigned FileType)
virtual Triple::ArchType getArch() const =0
virtual bool isSectionStripped(DataRefImpl Sec) const
Definition: ObjectFile.cpp:88
virtual bool isSectionBitcode(DataRefImpl Sec) const
Definition: ObjectFile.cpp:80
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:83
bool isDebugSection() const
Whether this section is a debug section.
Definition: ObjectFile.h:587
LLVM_ABI bool containsSymbol(SymbolRef S) const
Definition: ObjectFile.cpp:47
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: ObjectFile.h:170
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:485
virtual Expected< uint32_t > getSymbolFlags(DataRefImpl Symb) const =0
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Swift5ReflectionSectionKind
Definition: Swift.h:14
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:49
LLVM_ABI raw_ostream & operator<<(raw_ostream &OS, const SectionedAddress &Addr)
Definition: ObjectFile.cpp:35
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ABI file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:33
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1751
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:188
@ Ref
The access may reference the value stored in memory.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1083
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: Magic.h:21
@ coff_import_library
COFF import library.
Definition: Magic.h:49
@ pdb
Windows PDB debug info file.
Definition: Magic.h:55
@ spirv_object
A binary SPIR-V file.
Definition: Magic.h:62
@ elf_relocatable
ELF Relocatable object file.
Definition: Magic.h:28
@ archive
ar style archive file
Definition: Magic.h:26
@ elf_shared_object
ELF dynamically linked shared lib.
Definition: Magic.h:30
@ goff_object
GOFF object file.
Definition: Magic.h:32
@ minidump
Windows minidump file.
Definition: Magic.h:46
@ macho_dynamically_linked_shared_lib
Mach-O dynlinked shared lib.
Definition: Magic.h:38
@ xcoff_object_64
64-bit XCOFF object file
Definition: Magic.h:53
@ elf_executable
ELF Executable image.
Definition: Magic.h:29
@ macho_dynamically_linked_shared_lib_stub
Mach-O Shared lib stub.
Definition: Magic.h:41
@ macho_preload_executable
Mach-O Preloaded Executable.
Definition: Magic.h:37
@ offload_bundle
Clang offload bundle file.
Definition: Magic.h:60
@ offload_bundle_compressed
Compressed clang offload bundle file.
Definition: Magic.h:61
@ macho_file_set
Mach-O file set binary.
Definition: Magic.h:45
@ dxcontainer_object
DirectX container file.
Definition: Magic.h:59
@ macho_kext_bundle
Mach-O kext bundle file.
Definition: Magic.h:43
@ pecoff_executable
PECOFF executable file.
Definition: Magic.h:50
@ offload_binary
LLVM offload object file.
Definition: Magic.h:58
@ macho_universal_binary
Mach-O universal binary.
Definition: Magic.h:44
@ bitcode
Bitcode file.
Definition: Magic.h:24
@ macho_core
Mach-O Core File.
Definition: Magic.h:36
@ wasm_object
WebAssembly Object file.
Definition: Magic.h:54
@ xcoff_object_32
32-bit XCOFF object file
Definition: Magic.h:52
@ windows_resource
Windows compiled resource file (.res)
Definition: Magic.h:51
@ clang_ast
Clang PCH or PCM.
Definition: Magic.h:25
@ elf_core
ELF core image.
Definition: Magic.h:31
@ macho_object
Mach-O Object file.
Definition: Magic.h:33
@ coff_object
COFF object file.
Definition: Magic.h:48
@ elf
ELF Unknown type.
Definition: Magic.h:27
@ macho_bundle
Mach-O Bundle file.
Definition: Magic.h:40
@ coff_cl_gl_object
Microsoft cl.exe's intermediate code file.
Definition: Magic.h:47
@ cuda_fatbinary
CUDA Fatbinary object file.
Definition: Magic.h:57
@ macho_executable
Mach-O Executable.
Definition: Magic.h:34
@ macho_dsym_companion
Mach-O dSYM companion file.
Definition: Magic.h:42
@ unknown
Unrecognized file.
Definition: Magic.h:23
@ macho_fixed_virtual_memory_shared_lib
Mach-O Shared Lib, FVM.
Definition: Magic.h:35
@ macho_dynamic_linker
The Mach-O dynamic linker.
Definition: Magic.h:39
@ tapi_file
Text-based Dynamic Library Stub file.
Definition: Magic.h:56
static const uint64_t UndefSection
Definition: ObjectFile.h:148