LLVM 19.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"
18#include "llvm/Object/Error.h"
19#include "llvm/Object/MachO.h"
20#include "llvm/Object/Wasm.h"
21#include "llvm/Support/Error.h"
24#include "llvm/Support/Format.h"
27#include <cstdint>
28#include <memory>
29#include <system_error>
30
31using namespace llvm;
32using namespace object;
33
35 OS << "SectionedAddress{" << format_hex(Addr.Address, 10);
36 if (Addr.SectionIndex != SectionedAddress::UndefSection)
37 OS << ", " << Addr.SectionIndex;
38 return OS << "}";
39}
40
41void ObjectFile::anchor() {}
42
44 : SymbolicFile(Type, Source) {}
45
48 if (!SymSec) {
49 // TODO: Actually report errors helpfully.
50 consumeError(SymSec.takeError());
51 return false;
52 }
53 return *this == **SymSec;
54}
55
57 uint32_t Flags;
58 if (Error E = getSymbolFlags(Ref).moveInto(Flags))
59 // TODO: Test this error.
60 return std::move(E);
61
62 if (Flags & SymbolRef::SF_Undefined)
63 return 0;
64 if (Flags & SymbolRef::SF_Common)
66 return getSymbolValueImpl(Ref);
67}
68
71 if (!Name)
72 return Name.takeError();
73 OS << *Name;
74 return Error::success();
75}
76
78
80 Expected<StringRef> NameOrErr = getSectionName(Sec);
81 if (NameOrErr)
82 return *NameOrErr == ".llvm.lto";
83 consumeError(NameOrErr.takeError());
84 return false;
85}
86
87bool ObjectFile::isSectionStripped(DataRefImpl Sec) const { return false; }
88
90 return isSectionText(Sec);
91}
92
94 return isSectionData(Sec);
95}
96
97bool ObjectFile::isDebugSection(DataRefImpl Sec) const { return false; }
98
100 return any_of(sections(),
101 [](SectionRef Sec) { return Sec.isDebugSection(); });
102}
103
106 return section_iterator(SectionRef(Sec, this));
107}
108
110 Triple TheTriple;
111 auto Arch = getArch();
112 TheTriple.setArch(Triple::ArchType(Arch));
113
114 auto OS = getOS();
115 if (OS != Triple::UnknownOS)
116 TheTriple.setOS(OS);
117
118 // For ARM targets, try to use the build attributes to build determine
119 // the build target. Target features are also added, but later during
120 // disassembly.
121 if (Arch == Triple::arm || Arch == Triple::armeb)
122 setARMSubArch(TheTriple);
123
124 // TheTriple defaults to ELF, and COFF doesn't have an environment:
125 // something we can do here is indicate that it is mach-o.
126 if (isMachO()) {
128 } else if (isCOFF()) {
129 const auto COFFObj = cast<COFFObjectFile>(this);
130 if (COFFObj->getArch() == Triple::thumb)
131 TheTriple.setTriple("thumbv7-windows");
132 } else if (isXCOFF()) {
133 // XCOFF implies AIX.
134 TheTriple.setOS(Triple::AIX);
136 } else if (isGOFF()) {
137 TheTriple.setOS(Triple::ZOS);
138 TheTriple.setObjectFormat(Triple::GOFF);
139 } else if (TheTriple.isAMDGPU()) {
140 TheTriple.setVendor(Triple::AMD);
141 } else if (TheTriple.isNVPTX()) {
142 TheTriple.setVendor(Triple::NVIDIA);
143 }
144
145 return TheTriple;
146}
147
150 bool InitContent) {
151 StringRef Data = Object.getBuffer();
154
155 switch (Type) {
163 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);
204 }
205 llvm_unreachable("Unexpected Object File Type");
206}
207
211 MemoryBuffer::getFile(ObjectPath);
212 if (std::error_code EC = FileOrErr.getError())
213 return errorCodeToError(EC);
214 std::unique_ptr<MemoryBuffer> Buffer = std::move(FileOrErr.get());
215
217 createObjectFile(Buffer->getMemBufferRef());
218 if (Error Err = ObjOrErr.takeError())
219 return std::move(Err);
220 std::unique_ptr<ObjectFile> Obj = std::move(ObjOrErr.get());
221
222 return OwningBinary<ObjectFile>(std::move(Obj), std::move(Buffer));
223}
224
227 const {
229 return ReflectionSectionKind == Swift5ReflectionSectionKind::fieldmd ||
230 ReflectionSectionKind == Swift5ReflectionSectionKind::reflstr ||
231 ReflectionSectionKind == Swift5ReflectionSectionKind::assocty;
232}
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:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
reference get()
Returns a reference to the stored T value.
Definition: Error.h:571
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:50
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
void setObjectFormat(ObjectFormatType Kind)
Set the object file format.
Definition: Triple.cpp:1441
void setTriple(const Twine &Str)
Set all components to the new triple Str.
Definition: Triple.cpp:1417
bool isAMDGPU() const
Definition: Triple.h:842
bool isNVPTX() const
Tests whether the target is NVPTX (32- or 64-bit).
Definition: Triple.h:835
void setOS(OSType Kind)
Set the operating system (third) component of the triple to a known type.
Definition: Triple.cpp:1429
void setArch(ArchType Kind, SubArchType SubArch=NoSubArch)
Set the architecture (first) component of the triple to a known type.
Definition: Triple.cpp:1421
void setVendor(VendorType Kind)
Set the vendor (second) component of the triple to a known type.
Definition: Triple.cpp:1425
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:37
bool isXCOFF() const
Definition: Binary.h:135
bool isMachO() const
Definition: Binary.h:127
bool isCOFF() const
Definition: Binary.h:131
bool isGOFF() const
Definition: Binary.h:149
virtual bool isBerkeleyText(DataRefImpl Sec) const
Definition: ObjectFile.cpp:89
virtual Expected< section_iterator > getRelocatedSection(DataRefImpl Sec) const
Definition: ObjectFile.cpp:105
uint64_t getCommonSymbolSize(DataRefImpl Symb) const
Definition: ObjectFile.h:306
virtual Expected< StringRef > getSectionName(DataRefImpl Sec) const =0
virtual bool isBerkeleyData(DataRefImpl Sec) const
Definition: ObjectFile.cpp:93
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:69
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:109
virtual bool isSectionText(DataRefImpl Sec) const =0
section_iterator_range sections() const
Definition: ObjectFile.h:328
friend class SectionRef
Definition: ObjectFile.h:261
virtual uint64_t getSymbolValueImpl(DataRefImpl Symb) const =0
virtual bool isDebugSection(DataRefImpl Sec) const
Definition: ObjectFile.cpp:97
virtual void setARMSubArch(Triple &TheTriple) const
Definition: ObjectFile.h:345
static Expected< std::unique_ptr< WasmObjectFile > > createWasmObjectFile(MemoryBufferRef Object)
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:209
virtual uint32_t getSymbolAlignment(DataRefImpl Symb) const
Definition: ObjectFile.cpp:77
virtual bool isSectionData(DataRefImpl Sec) const =0
Expected< uint64_t > getSymbolValue(DataRefImpl Symb) const
Definition: ObjectFile.cpp:56
virtual Triple::OSType getOS() const
Definition: ObjectFile.h:340
bool isReflectionSectionStrippable(llvm::binaryformat::Swift5ReflectionSectionKind ReflectionSectionKind) const
True if the reflection section can be stripped by the linker.
Definition: ObjectFile.cpp:225
virtual bool hasDebugInfo() const
Definition: ObjectFile.cpp:99
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:87
virtual bool isSectionBitcode(DataRefImpl Sec) const
Definition: ObjectFile.cpp:79
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
bool isDebugSection() const
Whether this section is a debug section.
Definition: ObjectFile.h:581
bool containsSymbol(SymbolRef S) const
Definition: ObjectFile.cpp:46
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: ObjectFile.h:168
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:479
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:52
#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:47
raw_ostream & operator<<(raw_ostream &OS, const SectionedAddress &Addr)
Definition: ObjectFile.cpp:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1729
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition: Format.h:187
@ Ref
The access may reference the value stored in memory.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:103
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: Magic.h:20
@ coff_import_library
COFF import library.
Definition: Magic.h:48
@ pdb
Windows PDB debug info file.
Definition: Magic.h:54
@ spirv_object
A binary SPIR-V file.
Definition: Magic.h:61
@ elf_relocatable
ELF Relocatable object file.
Definition: Magic.h:27
@ archive
ar style archive file
Definition: Magic.h:25
@ elf_shared_object
ELF dynamically linked shared lib.
Definition: Magic.h:29
@ goff_object
GOFF object file.
Definition: Magic.h:31
@ minidump
Windows minidump file.
Definition: Magic.h:45
@ macho_dynamically_linked_shared_lib
Mach-O dynlinked shared lib.
Definition: Magic.h:37
@ xcoff_object_64
64-bit XCOFF object file
Definition: Magic.h:52
@ elf_executable
ELF Executable image.
Definition: Magic.h:28
@ macho_dynamically_linked_shared_lib_stub
Mach-O Shared lib stub.
Definition: Magic.h:40
@ macho_preload_executable
Mach-O Preloaded Executable.
Definition: Magic.h:36
@ offload_bundle
Clang offload bundle file.
Definition: Magic.h:59
@ offload_bundle_compressed
Compressed clang offload bundle file.
Definition: Magic.h:60
@ macho_file_set
Mach-O file set binary.
Definition: Magic.h:44
@ dxcontainer_object
DirectX container file.
Definition: Magic.h:58
@ macho_kext_bundle
Mach-O kext bundle file.
Definition: Magic.h:42
@ pecoff_executable
PECOFF executable file.
Definition: Magic.h:49
@ offload_binary
LLVM offload object file.
Definition: Magic.h:57
@ macho_universal_binary
Mach-O universal binary.
Definition: Magic.h:43
@ bitcode
Bitcode file.
Definition: Magic.h:23
@ macho_core
Mach-O Core File.
Definition: Magic.h:35
@ wasm_object
WebAssembly Object file.
Definition: Magic.h:53
@ xcoff_object_32
32-bit XCOFF object file
Definition: Magic.h:51
@ windows_resource
Windows compiled resource file (.res)
Definition: Magic.h:50
@ clang_ast
Clang PCH or PCM.
Definition: Magic.h:24
@ elf_core
ELF core image.
Definition: Magic.h:30
@ macho_object
Mach-O Object file.
Definition: Magic.h:32
@ coff_object
COFF object file.
Definition: Magic.h:47
@ elf
ELF Unknown type.
Definition: Magic.h:26
@ macho_bundle
Mach-O Bundle file.
Definition: Magic.h:39
@ coff_cl_gl_object
Microsoft cl.exe's intermediate code file.
Definition: Magic.h:46
@ cuda_fatbinary
CUDA Fatbinary object file.
Definition: Magic.h:56
@ macho_executable
Mach-O Executable.
Definition: Magic.h:33
@ macho_dsym_companion
Mach-O dSYM companion file.
Definition: Magic.h:41
@ unknown
Unrecognized file.
Definition: Magic.h:22
@ macho_fixed_virtual_memory_shared_lib
Mach-O Shared Lib, FVM.
Definition: Magic.h:34
@ macho_dynamic_linker
The Mach-O dynamic linker.
Definition: Magic.h:38
@ tapi_file
Text-based Dynamic Library Stub file.
Definition: Magic.h:55
static const uint64_t UndefSection
Definition: ObjectFile.h:146