LLVM 20.0.0git
Object.cpp
Go to the documentation of this file.
1//===- Object.cpp - C bindings to the object file library--------*- C++ -*-===//
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 the C bindings to the file-format-independent object
10// library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-c/Object.h"
16#include "llvm/IR/LLVMContext.h"
20
21using namespace llvm;
22using namespace object;
23
25 return reinterpret_cast<OwningBinary<ObjectFile> *>(OF);
26}
27
29 return reinterpret_cast<LLVMObjectFileRef>(
30 const_cast<OwningBinary<ObjectFile> *>(OF));
31}
32
34 return reinterpret_cast<section_iterator*>(SI);
35}
36
39 return reinterpret_cast<LLVMSectionIteratorRef>
40 (const_cast<section_iterator*>(SI));
41}
42
44 return reinterpret_cast<symbol_iterator*>(SI);
45}
46
49 return reinterpret_cast<LLVMSymbolIteratorRef>
50 (const_cast<symbol_iterator*>(SI));
51}
52
54 return reinterpret_cast<relocation_iterator*>(SI);
55}
56
59 return reinterpret_cast<LLVMRelocationIteratorRef>
60 (const_cast<relocation_iterator*>(SI));
61}
62
63/*--.. Operations on binary files ..........................................--*/
64
66 LLVMContextRef Context,
67 char **ErrorMessage) {
68 auto maybeContext = Context ? unwrap(Context) : nullptr;
70 createBinary(unwrap(MemBuf)->getMemBufferRef(), maybeContext));
71 if (!ObjOrErr) {
72 *ErrorMessage = strdup(toString(ObjOrErr.takeError()).c_str());
73 return nullptr;
74 }
75
76 return wrap(ObjOrErr.get().release());
77}
78
80 auto Buf = unwrap(BR)->getMemoryBufferRef();
82 Buf.getBuffer(), Buf.getBufferIdentifier(),
83 /*RequiresNullTerminator*/false).release());
84}
85
87 delete unwrap(BR);
88}
89
91 class BinaryTypeMapper final : public Binary {
92 public:
93 static LLVMBinaryType mapBinaryTypeToLLVMBinaryType(unsigned Kind) {
94 switch (Kind) {
95 case ID_Archive:
101 case ID_IR:
102 return LLVMBinaryTypeIR;
103 case ID_WinRes:
105 case ID_COFF:
106 return LLVMBinaryTypeCOFF;
107 case ID_ELF32L:
109 case ID_ELF32B:
111 case ID_ELF64L:
113 case ID_ELF64B:
115 case ID_MachO32L:
117 case ID_MachO32B:
119 case ID_MachO64L:
121 case ID_MachO64B:
123 case ID_Offload:
125 case ID_Wasm:
126 return LLVMBinaryTypeWasm;
127 case ID_StartObjects:
128 case ID_EndObjects:
129 llvm_unreachable("Marker types are not valid binary kinds!");
130 default:
131 llvm_unreachable("Unknown binary kind!");
132 }
133 }
134 };
135 return BinaryTypeMapper::mapBinaryTypeToLLVMBinaryType(unwrap(BR)->getType());
136}
137
139 const char *Arch,
140 size_t ArchLen,
141 char **ErrorMessage) {
142 auto universal = cast<MachOUniversalBinary>(unwrap(BR));
144 universal->getMachOObjectForArch({Arch, ArchLen}));
145 if (!ObjOrErr) {
146 *ErrorMessage = strdup(toString(ObjOrErr.takeError()).c_str());
147 return nullptr;
148 }
149 return wrap(ObjOrErr.get().release());
150}
151
153 auto OF = cast<ObjectFile>(unwrap(BR));
154 auto sections = OF->sections();
155 if (sections.begin() == sections.end())
156 return nullptr;
157 return wrap(new section_iterator(sections.begin()));
158}
159
162 auto OF = cast<ObjectFile>(unwrap(BR));
163 return (*unwrap(SI) == OF->section_end()) ? 1 : 0;
164}
165
167 auto OF = cast<ObjectFile>(unwrap(BR));
168 auto symbols = OF->symbols();
169 if (symbols.begin() == symbols.end())
170 return nullptr;
171 return wrap(new symbol_iterator(symbols.begin()));
172}
173
176 auto OF = cast<ObjectFile>(unwrap(BR));
177 return (*unwrap(SI) == OF->symbol_end()) ? 1 : 0;
178}
179
180// ObjectFile creation
182 std::unique_ptr<MemoryBuffer> Buf(unwrap(MemBuf));
184 ObjectFile::createObjectFile(Buf->getMemBufferRef()));
185 std::unique_ptr<ObjectFile> Obj;
186 if (!ObjOrErr) {
187 // TODO: Actually report errors helpfully.
188 consumeError(ObjOrErr.takeError());
189 return nullptr;
190 }
191
192 auto *Ret = new OwningBinary<ObjectFile>(std::move(ObjOrErr.get()), std::move(Buf));
193 return wrap(Ret);
194}
195
197 delete unwrap(ObjectFile);
198}
199
200// ObjectFile Section iterators
203 section_iterator SI = OB->getBinary()->section_begin();
204 return wrap(new section_iterator(SI));
205}
206
208 delete unwrap(SI);
209}
210
214 return (*unwrap(SI) == OB->getBinary()->section_end()) ? 1 : 0;
215}
216
218 ++(*unwrap(SI));
219}
220
224 if (!SecOrErr) {
225 std::string Buf;
229 }
230 *unwrap(Sect) = *SecOrErr;
231}
232
233// ObjectFile Symbol iterators
236 symbol_iterator SI = OB->getBinary()->symbol_begin();
237 return wrap(new symbol_iterator(SI));
238}
239
241 delete unwrap(SI);
242}
243
247 return (*unwrap(SI) == OB->getBinary()->symbol_end()) ? 1 : 0;
248}
249
251 ++(*unwrap(SI));
252}
253
254// SectionRef accessors
256 auto NameOrErr = (*unwrap(SI))->getName();
257 if (!NameOrErr)
258 report_fatal_error(NameOrErr.takeError());
259 return NameOrErr->data();
260}
261
263 return (*unwrap(SI))->getSize();
264}
265
267 if (Expected<StringRef> E = (*unwrap(SI))->getContents())
268 return E->data();
269 else
270 report_fatal_error(E.takeError());
271}
272
274 return (*unwrap(SI))->getAddress();
275}
276
279 return (*unwrap(SI))->containsSymbol(**unwrap(Sym));
280}
281
282// Section Relocation iterators
284 relocation_iterator SI = (*unwrap(Section))->relocation_begin();
285 return wrap(new relocation_iterator(SI));
286}
287
289 delete unwrap(SI);
290}
291
294 return (*unwrap(SI) == (*unwrap(Section))->relocation_end()) ? 1 : 0;
295}
296
298 ++(*unwrap(SI));
299}
300
301
302// SymbolRef accessors
304 Expected<StringRef> Ret = (*unwrap(SI))->getName();
305 if (!Ret) {
306 std::string Buf;
308 logAllUnhandledErrors(Ret.takeError(), OS);
310 }
311 return Ret->data();
312}
313
315 Expected<uint64_t> Ret = (*unwrap(SI))->getAddress();
316 if (!Ret) {
317 std::string Buf;
319 logAllUnhandledErrors(Ret.takeError(), OS);
321 }
322 return *Ret;
323}
324
326 return (*unwrap(SI))->getCommonSize();
327}
328
329// RelocationRef accessors
331 return (*unwrap(RI))->getOffset();
332}
333
335 symbol_iterator ret = (*unwrap(RI))->getSymbol();
336 return wrap(new symbol_iterator(ret));
337}
338
340 return (*unwrap(RI))->getType();
341}
342
343// NOTE: Caller takes ownership of returned string.
346 (*unwrap(RI))->getTypeName(ret);
347 char *str = static_cast<char*>(safe_malloc(ret.size()));
348 llvm::copy(ret, str);
349 return str;
350}
351
352// NOTE: Caller takes ownership of returned string.
354 return strdup("");
355}
356
bbsections Prepares for basic block sections
Symbol * Sym
Definition: ELF_riscv.cpp:479
This file defines counterparts of C library allocation functions defined in the namespace 'std'.
LLVMObjectFileRef wrap(const OwningBinary< ObjectFile > *OF)
Definition: Object.cpp:28
OwningBinary< ObjectFile > * unwrap(LLVMObjectFileRef OF)
Definition: Object.cpp:24
static StringRef getName(Value *V)
const Value * getAddress(const DbgVariableIntrinsic *DVI)
Definition: SROA.cpp:5023
raw_pwrite_stream & OS
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:39
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
size_t size() const
Definition: SmallVector.h:78
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
This class is the base class for all object file types.
Definition: ObjectFile.h:229
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:209
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI)
Definition: Object.cpp:339
LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf)
Deprecated: Use LLVMCreateBinary instead.
Definition: Object.cpp:181
LLVMSymbolIteratorRef LLVMObjectFileCopySymbolIterator(LLVMBinaryRef BR)
Retrieve a copy of the symbol iterator for this object file.
Definition: Object.cpp:166
LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section, LLVMRelocationIteratorRef SI)
Definition: Object.cpp:292
struct LLVMOpaqueSymbolIterator * LLVMSymbolIteratorRef
Definition: Object.h:37
void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef SI)
Definition: Object.cpp:297
void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI)
Definition: Object.cpp:207
const char * LLVMGetSectionContents(LLVMSectionIteratorRef SI)
Definition: Object.cpp:266
const char * LLVMGetSectionName(LLVMSectionIteratorRef SI)
Definition: Object.cpp:255
uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI)
Definition: Object.cpp:330
uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI)
Definition: Object.cpp:325
const char * LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI)
Definition: Object.cpp:344
LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef OF, LLVMSectionIteratorRef SI)
Deprecated: Use LLVMObjectFileIsSectionIteratorAtEnd instead.
Definition: Object.cpp:211
uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI)
Definition: Object.cpp:262
void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI)
Definition: Object.cpp:240
LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef OF)
Deprecated: Use LLVMObjectFileCopySymbolIterator instead.
Definition: Object.cpp:234
LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef OF)
Deprecated: Use LLVMObjectFileCopySectionIterator instead.
Definition: Object.cpp:201
uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI)
Definition: Object.cpp:273
LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef OF, LLVMSymbolIteratorRef SI)
Deprecated: Use LLVMObjectFileIsSymbolIteratorAtEnd instead.
Definition: Object.cpp:244
LLVMBinaryType LLVMBinaryGetType(LLVMBinaryRef BR)
Retrieve the specific type of a binary.
Definition: Object.cpp:90
LLVMBool LLVMObjectFileIsSectionIteratorAtEnd(LLVMBinaryRef BR, LLVMSectionIteratorRef SI)
Returns whether the given section iterator is at the end.
Definition: Object.cpp:160
void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI)
Definition: Object.cpp:250
LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Section)
Definition: Object.cpp:283
struct LLVMOpaqueSectionIterator * LLVMSectionIteratorRef
Definition: Object.h:36
LLVMBinaryRef LLVMMachOUniversalBinaryCopyObjectForArch(LLVMBinaryRef BR, const char *Arch, size_t ArchLen, char **ErrorMessage)
Definition: Object.cpp:138
LLVMBinaryType
Definition: Object.h:40
void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect, LLVMSymbolIteratorRef Sym)
Definition: Object.cpp:221
void LLVMDisposeBinary(LLVMBinaryRef BR)
Dispose of a binary file.
Definition: Object.cpp:86
LLVMSectionIteratorRef LLVMObjectFileCopySectionIterator(LLVMBinaryRef BR)
Retrieve a copy of the section iterator for this object file.
Definition: Object.cpp:152
void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef SI)
Definition: Object.cpp:288
LLVMBinaryRef LLVMCreateBinary(LLVMMemoryBufferRef MemBuf, LLVMContextRef Context, char **ErrorMessage)
Create a binary file from the given memory buffer.
Definition: Object.cpp:65
LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI)
Definition: Object.cpp:334
void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile)
Deprecated: Use LLVMDisposeBinary instead.
Definition: Object.cpp:196
LLVMBool LLVMObjectFileIsSymbolIteratorAtEnd(LLVMBinaryRef BR, LLVMSymbolIteratorRef SI)
Returns whether the given symbol iterator is at the end.
Definition: Object.cpp:174
const char * LLVMGetSymbolName(LLVMSymbolIteratorRef SI)
Definition: Object.cpp:303
struct LLVMOpaqueRelocationIterator * LLVMRelocationIteratorRef
Definition: Object.h:38
struct LLVMOpaqueObjectFile * LLVMObjectFileRef
Deprecated: Use LLVMBinaryRef instead.
Definition: Object.h:205
LLVMMemoryBufferRef LLVMBinaryCopyMemoryBuffer(LLVMBinaryRef BR)
Retrieves a copy of the memory buffer associated with this object file.
Definition: Object.cpp:79
void LLVMMoveToNextSection(LLVMSectionIteratorRef SI)
Definition: Object.cpp:217
LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI, LLVMSymbolIteratorRef Sym)
Definition: Object.cpp:277
const char * LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI)
Definition: Object.cpp:353
uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI)
Definition: Object.cpp:314
@ LLVMBinaryTypeIR
LLVM IR.
Definition: Object.h:44
@ LLVMBinaryTypeELF64B
ELF 64-bit, big endian.
Definition: Object.h:50
@ LLVMBinaryTypeArchive
Archive file.
Definition: Object.h:41
@ LLVMBinaryTypeMachO32B
MachO 32-bit, big endian.
Definition: Object.h:52
@ LLVMBinaryTypeWasm
Web Assembly.
Definition: Object.h:55
@ LLVMBinaryTypeELF64L
ELF 64-bit, little endian.
Definition: Object.h:49
@ LLVMBinaryTypeWinRes
Windows resource (.res) file.
Definition: Object.h:45
@ LLVMBinaryTypeMachOUniversalBinary
Mach-O Universal Binary file.
Definition: Object.h:42
@ LLVMBinaryTypeMachO64B
MachO 64-bit, big endian.
Definition: Object.h:54
@ LLVMBinaryTypeCOFF
COFF Object file.
Definition: Object.h:46
@ LLVMBinaryTypeCOFFImportFile
COFF Import file.
Definition: Object.h:43
@ LLVMBinaryTypeELF32B
ELF 32-bit, big endian.
Definition: Object.h:48
@ LLVMBinaryTypeELF32L
ELF 32-bit, little endian.
Definition: Object.h:47
@ LLVMBinaryTypeMachO32L
MachO 32-bit, little endian.
Definition: Object.h:51
@ LLVMBinaryTypeMachO64L
MachO 64-bit, little endian.
Definition: Object.h:53
@ LLVMBinaryTypeOffload
Offloading fatbinary.
Definition: Object.h:56
int LLVMBool
Definition: Types.h:28
struct LLVMOpaqueBinary * LLVMBinaryRef
Definition: Types.h:170
struct LLVMOpaqueMemoryBuffer * LLVMMemoryBufferRef
LLVM uses a polymorphic type hierarchy which C cannot represent, therefore parameters must be passed ...
Definition: Types.h:48
struct LLVMOpaqueContext * LLVMContextRef
The top-level container for all LLVM global data.
Definition: Types.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition: ELF.h:534
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:47
content_iterator< RelocationRef > relocation_iterator
Definition: ObjectFile.h:77
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:45
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:65
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_malloc(size_t Sz)
Definition: MemAlloc.h:25
StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
Definition: TypeName.h:63
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1841
const char * toString(DWARFSectionKind Kind)
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069