llvm.org GIT mirror llvm / 548f2b6
Don't own the buffer in object::Binary. Owning the buffer is somewhat inflexible. Some Binaries have sub Binaries (like Archive) and we had to create dummy buffers just to handle that. It is also a bad fit for IRObjectFile where the Module wants to own the buffer too. Keeping this ownership would make supporting IR inside native objects particularly painful. This patch focuses in lib/Object. If something elsewhere used to own an Binary, now it also owns a MemoryBuffer. This patch introduces a few new types. * MemoryBufferRef. This is just a pair of StringRefs for the data and name. This is to MemoryBuffer as StringRef is to std::string. * OwningBinary. A combination of Binary and a MemoryBuffer. This is needed for convenience functions that take a filename and return both the buffer and the Binary using that buffer. The C api now uses OwningBinary to avoid any change in semantics. I will start a new thread to see if we want to change it and how. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@216002 91177308-0d34-0410-b5e6-96231b3b80d8 Rafael Espindola 5 years ago
48 changed file(s) with 387 addition(s) and 326 deletion(s). Raw diff Collapse all Expand all
2121 #include "llvm/IR/ValueHandle.h"
2222 #include "llvm/IR/ValueMap.h"
2323 #include "llvm/MC/MCCodeGenInfo.h"
24 #include "llvm/Object/Binary.h"
2425 #include "llvm/Support/ErrorHandling.h"
2526 #include "llvm/Support/Mutex.h"
2627 #include "llvm/Target/TargetMachine.h"
194195 /// resolve external symbols in objects it is loading. If a symbol is found
195196 /// in the Archive the contained object file will be extracted (in memory)
196197 /// and loaded for possible execution.
197 virtual void addArchive(std::unique_ptr A);
198 virtual void addArchive(object::OwningBinary A);
198199
199200 //===--------------------------------------------------------------------===//
200201
2323 /// This class acts as a container for the memory buffer used during generation
2424 /// and loading of executable objects using MCJIT and RuntimeDyld. The
2525 /// underlying memory for the object will be owned by the ObjectBuffer instance
26 /// throughout its lifetime. The getMemBuffer() method provides a way to create
27 /// a MemoryBuffer wrapper object instance to be owned by other classes (such as
28 /// ObjectFile) as needed, but the MemoryBuffer instance returned does not own
29 /// the actual memory it points to.
26 /// throughout its lifetime.
3027 class ObjectBuffer {
3128 virtual void anchor();
3229 public:
3431 ObjectBuffer(MemoryBuffer* Buf) : Buffer(Buf) {}
3532 virtual ~ObjectBuffer() {}
3633
37 /// Like MemoryBuffer::getMemBuffer() this function returns a pointer to an
38 /// object that is owned by the caller. However, the caller does not take
39 /// ownership of the underlying memory.
40 std::unique_ptr getMemBuffer() const {
41 return std::unique_ptr(MemoryBuffer::getMemBuffer(
42 Buffer->getBuffer(), Buffer->getBufferIdentifier(), false));
43 }
34 MemoryBufferRef getMemBuffer() const { return Buffer->getMemBufferRef(); }
4435
4536 const char *getBufferStart() const { return Buffer->getBufferStart(); }
4637 size_t getBufferSize() const { return Buffer->getBufferSize(); }
2626 virtual ~ObjectCache() { }
2727
2828 /// notifyObjectCompiled - Provides a pointer to compiled code for Module M.
29 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) = 0;
29 virtual void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) = 0;
3030
3131 /// Returns a pointer to a newly allocated MemoryBuffer that contains the
3232 /// object which corresponds with Module M, or 0 if an object is not
201201 /// Get string that the data pointer points to.
202202 bool objcClassNameFromExpression(const Constant *c, std::string &name);
203203
204 /// Create an LTOModule (private version). N.B. This method takes ownership of
205 /// the buffer.
206 static LTOModule *makeLTOModule(std::unique_ptr Buffer,
207 TargetOptions options, std::string &errMsg);
204 /// Create an LTOModule (private version).
205 static LTOModule *makeLTOModule(MemoryBufferRef Buffer, TargetOptions options,
206 std::string &errMsg);
208207 };
209208 }
210209 #endif
8888 return StringRef(Data.data() + StartOfFile, getSize());
8989 }
9090
91 ErrorOr>
92 getMemoryBuffer(bool FullPath = false) const;
91 ErrorOr getMemoryBufferRef() const;
9392
9493 ErrorOr>
9594 getAsBinary(LLVMContext *Context = nullptr) const;
163162 }
164163 };
165164
166 Archive(std::unique_ptr Source, std::error_code &EC);
167 static ErrorOr>
168 create(std::unique_ptr Source);
165 Archive(MemoryBufferRef Source, std::error_code &EC);
166 static ErrorOr> create(MemoryBufferRef Source);
169167
170168 enum Kind {
171169 K_GNU,
1616 #include "llvm/Object/Error.h"
1717 #include "llvm/Support/ErrorOr.h"
1818 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/MemoryBuffer.h"
1920
2021 namespace llvm {
2122
2223 class LLVMContext;
23 class MemoryBuffer;
2424 class StringRef;
2525
2626 namespace object {
3333 unsigned int TypeID;
3434
3535 protected:
36 std::unique_ptr Data;
36 MemoryBufferRef Data;
3737
38 Binary(unsigned int Type, std::unique_ptr Source);
38 Binary(unsigned int Type, MemoryBufferRef Source);
3939
4040 enum {
4141 ID_Archive,
7777 virtual ~Binary();
7878
7979 StringRef getData() const;
80 MemoryBuffer *releaseBuffer() { return Data.release(); }
8180 StringRef getFileName() const;
81 MemoryBufferRef getMemoryBufferRef() const;
8282
8383 // Cast methods.
8484 unsigned int getType() const { return TypeID; }
125125 /// @brief Create a Binary from Source, autodetecting the file type.
126126 ///
127127 /// @param Source The data to create the Binary from.
128 ErrorOr>
129 createBinary(std::unique_ptr Source,
130 LLVMContext *Context = nullptr);
128 ErrorOr> createBinary(MemoryBufferRef Source,
129 LLVMContext *Context = nullptr);
131130
132 ErrorOr> createBinary(StringRef Path);
131 template class OwningBinary {
132 std::unique_ptr Bin;
133 std::unique_ptr Buf;
134
135 public:
136 OwningBinary();
137 OwningBinary(std::unique_ptr Bin, std::unique_ptr Buf);
138 std::unique_ptr &getBinary();
139 std::unique_ptr &getBuffer();
140 };
141
142 template
143 OwningBinary::OwningBinary(std::unique_ptr Bin,
144 std::unique_ptr Buf)
145 : Bin(std::move(Bin)), Buf(std::move(Buf)) {}
146
147 template OwningBinary::OwningBinary() {}
148
149 template std::unique_ptr &OwningBinary::getBinary() {
150 return Bin;
151 }
152
153 template
154 std::unique_ptr &OwningBinary::getBuffer() {
155 return Buf;
156 }
157
158 ErrorOr> createBinary(StringRef Path);
133159 }
134160 }
135161
414414 SmallVectorImpl &Result) const override;
415415
416416 public:
417 COFFObjectFile(std::unique_ptr Object, std::error_code &EC);
417 COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
418418 basic_symbol_iterator symbol_begin_impl() const override;
419419 basic_symbol_iterator symbol_end_impl() const override;
420420 section_iterator section_begin() const override;
3636
3737 class ELFObjectFileBase : public ObjectFile {
3838 protected:
39 ELFObjectFileBase(unsigned int Type, std::unique_ptr Source);
39 ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
4040
4141 public:
4242 virtual std::error_code getRelocationAddend(DataRefImpl Rel,
185185 bool isDyldELFObject;
186186
187187 public:
188 ELFObjectFile(std::unique_ptr Object, std::error_code &EC);
188 ELFObjectFile(MemoryBufferRef Object, std::error_code &EC);
189189
190190 const Elf_Sym *getSymbol(DataRefImpl Symb) const;
191191
796796 }
797797
798798 template
799 ELFObjectFile::ELFObjectFile(std::unique_ptr Object,
800 std::error_code &EC)
799 ELFObjectFile::ELFObjectFile(MemoryBufferRef Object, std::error_code &EC)
801800 : ELFObjectFileBase(
802801 getELFType(static_cast(ELFT::TargetEndianness) ==
803802 support::little,
804803 ELFT::Is64Bits),
805 std::move(Object)),
806 EF(Data->getBuffer(), EC) {}
804 Object),
805 EF(Data.getBuffer(), EC) {}
807806
808807 template
809808 basic_symbol_iterator ELFObjectFile::symbol_begin_impl() const {
2727 std::vector> AsmSymbols;
2828
2929 public:
30 IRObjectFile(std::unique_ptr Object, std::unique_ptr M);
30 IRObjectFile(MemoryBufferRef Object, std::unique_ptr M);
3131 ~IRObjectFile();
3232 void moveSymbolNext(DataRefImpl &Symb) const override;
3333 std::error_code printSymbolName(raw_ostream &OS,
4848 return v->isIR();
4949 }
5050
51 static ErrorOr
52 createIRObjectFile(std::unique_ptr Object,
53 LLVMContext &Context);
51 static ErrorOr createIRObjectFile(MemoryBufferRef Object,
52 LLVMContext &Context);
5453 };
5554 }
5655 }
5555 MachO::load_command C; // The command itself.
5656 };
5757
58 MachOObjectFile(std::unique_ptr Object, bool IsLittleEndian,
59 bool Is64Bits, std::error_code &EC);
58 MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
59 std::error_code &EC);
6060
6161 void moveSymbolNext(DataRefImpl &Symb) const override;
6262 std::error_code getSymbolName(DataRefImpl Symb,
8383 }
8484 };
8585
86 MachOUniversalBinary(std::unique_ptr Source,
87 std::error_code &ec);
88 static ErrorOr
89 create(std::unique_ptr Source);
86 MachOUniversalBinary(MemoryBufferRef Souce, std::error_code &EC);
87 static ErrorOr create(MemoryBufferRef Source);
9088
9189 object_iterator begin_objects() const {
9290 return ObjectForArch(this, 0);
186186 ObjectFile(const ObjectFile &other) LLVM_DELETED_FUNCTION;
187187
188188 protected:
189 ObjectFile(unsigned int Type, std::unique_ptr Source);
189 ObjectFile(unsigned int Type, MemoryBufferRef Source);
190190
191191 const uint8_t *base() const {
192 return reinterpret_cast(Data->getBufferStart());
192 return reinterpret_cast(Data.getBufferStart());
193193 }
194194
195195 // These functions are for SymbolRef to call internally. The main goal of
308308 /// @param ObjectPath The path to the object file. ObjectPath.isObject must
309309 /// return true.
310310 /// @brief Create ObjectFile from path.
311 static ErrorOr>
312 createObjectFile(StringRef ObjectPath);
313
311314 static ErrorOr>
312 createObjectFile(StringRef ObjectPath);
313
315 createObjectFile(MemoryBufferRef Object, sys::fs::file_magic Type);
314316 static ErrorOr>
315 createObjectFile(std::unique_ptr &Object,
316 sys::fs::file_magic Type);
317 static ErrorOr>
318 createObjectFile(std::unique_ptr &Object) {
317 createObjectFile(MemoryBufferRef Object) {
319318 return createObjectFile(Object, sys::fs::file_magic::unknown);
320319 }
321320
325324 }
326325
327326 static ErrorOr>
328 createCOFFObjectFile(std::unique_ptr Object);
327 createCOFFObjectFile(MemoryBufferRef Object);
329328
330329 static ErrorOr>
331 createELFObjectFile(std::unique_ptr &Object);
330 createELFObjectFile(MemoryBufferRef Object);
332331
333332 static ErrorOr>
334 createMachOObjectFile(std::unique_ptr &Object);
333 createMachOObjectFile(MemoryBufferRef Object);
335334 };
336335
337336 // Inline function definitions.
115115 class SymbolicFile : public Binary {
116116 public:
117117 virtual ~SymbolicFile();
118 SymbolicFile(unsigned int Type, std::unique_ptr Source);
118 SymbolicFile(unsigned int Type, MemoryBufferRef Source);
119119
120120 // virtual interface.
121121 virtual void moveSymbolNext(DataRefImpl &Symb) const = 0;
143143
144144 // construction aux.
145145 static ErrorOr>
146 createSymbolicFile(std::unique_ptr &Object,
147 sys::fs::file_magic Type, LLVMContext *Context);
146 createSymbolicFile(MemoryBufferRef Object, sys::fs::file_magic Type,
147 LLVMContext *Context);
148148
149149 static ErrorOr>
150 createSymbolicFile(std::unique_ptr &Object) {
150 createSymbolicFile(MemoryBufferRef Object) {
151151 return createSymbolicFile(Object, sys::fs::file_magic::unknown, nullptr);
152152 }
153 static ErrorOr<std::unique_ptr>
153 static ErrorOr<OwningBinary>
154154 createSymbolicFile(StringRef ObjectPath);
155155
156156 static inline bool classof(const Binary *v) {
156156
157157 private:
158158 std::error_code LastError;
159 std::unique_ptrobject::ObjectFile> Object;
159 object::OwningBinary<object::ObjectFile> Object;
160160 std::vector Filenames;
161161 std::vector MappingRecords;
162162 size_t CurrentRecord;
2323 #include
2424
2525 namespace llvm {
26 /// This interface provides simple read-only access to a block/ of memory, and
26 class MemoryBufferRef;
27
28 /// This interface provides simple read-only access to a block of memory, and
2729 /// provides simple methods for reading files and standard input into a memory
28 /// buffer. In addition to basic access to the characters in the file, this
30 /// buffer. In addition to basic access to the characters in the file, this
2931 /// interface guarantees you can read one character past the end of the file,
3032 /// and that this character will read as '\0'.
3133 ///
135137
136138 /// Return information on the memory mechanism used to support the
137139 /// MemoryBuffer.
138 virtual BufferKind getBufferKind() const = 0;
140 virtual BufferKind getBufferKind() const = 0;
141
142 MemoryBufferRef getMemBufferRef() const;
143 };
144
145 class MemoryBufferRef {
146 StringRef Buffer;
147 StringRef Identifier;
148
149 public:
150 MemoryBufferRef() {}
151 MemoryBufferRef(StringRef Buffer, StringRef Identifier)
152 : Buffer(Buffer), Identifier(Identifier) {}
153
154 StringRef getBuffer() const { return Buffer; }
155
156 StringRef getBufferIdentifier() const { return Identifier; }
157
158 const char *getBufferStart() const { return Buffer.begin(); }
159 const char *getBufferEnd() const { return Buffer.end(); }
160 size_t getBufferSize() const { return Buffer.size(); }
139161 };
140162
141163 // Create wrappers for C Binding types (see CBindingWrapping.h).
260260 sys::path::append(AbsolutePath, CompilationDir);
261261 }
262262 sys::path::append(AbsolutePath, DWOFileName);
263 ErrorOr<std::unique_ptr> DWOFile =
263 ErrorOr<object::OwningBinary> DWOFile =
264264 object::ObjectFile::createObjectFile(AbsolutePath);
265265 if (!DWOFile)
266266 return false;
267267 // Reset DWOHolder.
268 DWO = llvm::make_unique(std::move(*DWOFile));
268 DWO = llvm::make_unique(std::move(DWOFile->getBinary()));
269269 DWARFUnit *DWOCU = DWO->getUnit();
270270 // Verify that compile unit in .dwo file is valid.
271271 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
123123 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
124124 }
125125
126 void ExecutionEngine::addArchive(std::unique_ptr A) {
126 void ExecutionEngine::addArchive(object::OwningBinary A) {
127127 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
128128 }
129129
118118 NotifyObjectEmitted(*LoadedObject);
119119 }
120120
121 void MCJIT::addArchive(std::unique_ptr A) {
121 void MCJIT::addArchive(object::OwningBinary A) {
122122 Archives.push_back(std::move(A));
123123 }
124124
160160 if (ObjCache) {
161161 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
162162 // to create a temporary object here and delete it after the call.
163 std::unique_ptr MB = CompiledObject->getMemBuffer();
164 ObjCache->notifyObjectCompiled(M, MB.get());
163 MemoryBufferRef MB = CompiledObject->getMemBuffer();
164 ObjCache->notifyObjectCompiled(M, MB);
165165 }
166166
167167 return CompiledObject.release();
294294 if (Addr)
295295 return Addr;
296296
297 for (std::unique_ptr &A : Archives) {
297 for (object::OwningBinary &OB : Archives) {
298 object::Archive *A = OB.getBinary().get();
298299 // Look for our symbols in each Archive
299300 object::Archive::child_iterator ChildIt = A->findSym(Name);
300301 if (ChildIt != A->child_end()) {
215215
216216 OwningModuleContainer OwnedModules;
217217
218 SmallVector<std::unique_ptr, 2> Archives;
218 SmallVector<object::OwningBinary, 2> Archives;
219219
220220 typedef SmallVector LoadedObjectList;
221221 LoadedObjectList LoadedObjects;
239239 /// @{
240240 void addModule(std::unique_ptr M) override;
241241 void addObjectFile(std::unique_ptr O) override;
242 void addArchive(std::unique_ptr O) override;
242 void addArchive(object::OwningBinary O) override;
243243 bool removeModule(Module *M) override;
244244
245245 /// FindFunctionNamed - Search all of the active modules to find the one that
4747 {
4848 // FIXME: error checking? createObjectFile returns an ErrorOr
4949 // and should probably be checked for failure.
50 std::unique_ptr Buf = Buffer->getMemBuffer();
50 MemoryBufferRef Buf = Buffer->getMemBuffer();
5151 ObjFile = std::move(object::ObjectFile::createObjectFile(Buf).get());
5252 }
5353 ObjectImageCommon(std::unique_ptr Input)
5454
5555 public:
5656 DyldELFObject(std::unique_ptr UnderlyingFile,
57 std::unique_ptr Wrapper, std::error_code &ec);
58
59 DyldELFObject(std::unique_ptr Wrapper, std::error_code &ec);
57 MemoryBufferRef Wrapper, std::error_code &ec);
58
59 DyldELFObject(MemoryBufferRef Wrapper, std::error_code &ec);
6060
6161 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
6262 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
108108 // actual memory. Ultimately, the Binary parent class will take ownership of
109109 // this MemoryBuffer object but not the underlying memory.
110110 template
111 DyldELFObject::DyldELFObject(std::unique_ptr Wrapper,
112 std::error_code &EC)
113 : ELFObjectFile(std::move(Wrapper), EC) {
111 DyldELFObject::DyldELFObject(MemoryBufferRef Wrapper, std::error_code &EC)
112 : ELFObjectFile(Wrapper, EC) {
114113 this->isDyldELFObject = true;
115114 }
116115
117116 template
118117 DyldELFObject::DyldELFObject(std::unique_ptr UnderlyingFile,
119 std::unique_ptr Wrapper,
120 std::error_code &EC)
121 : ELFObjectFile(std::move(Wrapper), EC),
118 MemoryBufferRef Wrapper, std::error_code &EC)
119 : ELFObjectFile(Wrapper, EC),
122120 UnderlyingFile(std::move(UnderlyingFile)) {
123121 this->isDyldELFObject = true;
124122 }
184182 return nullptr;
185183
186184 std::error_code ec;
187 std::unique_ptr Buffer(
188 MemoryBuffer::getMemBuffer(ObjFile->getData(), "", false));
185 MemoryBufferRef Buffer = ObjFile->getMemoryBufferRef();
189186
190187 if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
191188 auto Obj =
192189 llvm::make_unique>>(
193 std::move(ObjFile), std::move(Buffer), ec);
190 std::move(ObjFile), Buffer, ec);
194191 return new ELFObjectImage>(
195192 nullptr, std::move(Obj));
196193 } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
197194 auto Obj =
198195 llvm::make_unique>>(
199 std::move(ObjFile), std::move(Buffer), ec);
196 std::move(ObjFile), Buffer, ec);
200197 return new ELFObjectImage>(nullptr, std::move(Obj));
201198 } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
202199 auto Obj = llvm::make_unique>>(
203 std::move(ObjFile), std::move(Buffer), ec);
200 std::move(ObjFile), Buffer, ec);
204201 return new ELFObjectImage>(nullptr,
205202 std::move(Obj));
206203 } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
207204 auto Obj =
208205 llvm::make_unique>>(
209 std::move(ObjFile), std::move(Buffer), ec);
206 std::move(ObjFile), Buffer, ec);
210207 return new ELFObjectImage>(
211208 nullptr, std::move(Obj));
212209 } else
221218 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
222219 std::error_code ec;
223220
224 std::unique_ptr Buf = Buffer->getMemBuffer();
221 MemoryBufferRef Buf = Buffer->getMemBuffer();
225222
226223 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
227224 auto Obj =
228225 llvm::make_unique>>(
229 std::move(Buf), ec);
226 Buf, ec);
230227 return new ELFObjectImage>(
231228 Buffer, std::move(Obj));
232229 } else if (Ident.first == ELF::ELFCLASS32 &&
233230 Ident.second == ELF::ELFDATA2MSB) {
234231 auto Obj =
235 llvm::make_unique>>(
236 std::move(Buf), ec);
232 llvm::make_unique>>(Buf,
233 ec);
237234 return new ELFObjectImage>(Buffer,
238235 std::move(Obj));
239236 } else if (Ident.first == ELF::ELFCLASS64 &&
240237 Ident.second == ELF::ELFDATA2MSB) {
241238 auto Obj = llvm::make_unique>>(
242 std::move(Buf), ec);
239 Buf, ec);
243240 return new ELFObjectImage>(Buffer, std::move(Obj));
244241 } else if (Ident.first == ELF::ELFCLASS64 &&
245242 Ident.second == ELF::ELFDATA2LSB) {
246243 auto Obj =
247 llvm::make_unique>>(
248 std::move(Buf), ec);
244 llvm::make_unique>>(Buf,
245 ec);
249246 return new ELFObjectImage>(Buffer, std::move(Obj));
250247 } else
251248 llvm_unreachable("Unexpected ELF format");
7676 errMsg = EC.message();
7777 return nullptr;
7878 }
79 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
79 std::unique_ptr Buffer = std::move(BufferOrErr.get());
80 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg);
8081 }
8182
8283 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
9596 errMsg = EC.message();
9697 return nullptr;
9798 }
98 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
99 std::unique_ptr Buffer = std::move(BufferOrErr.get());
100 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg);
99101 }
100102
101103 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
102104 TargetOptions options,
103105 std::string &errMsg, StringRef path) {
104 std::unique_ptr buffer(makeBuffer(mem, length, path));
105 if (!buffer)
106 return nullptr;
107 return makeLTOModule(std::move(buffer), options, errMsg);
108 }
109
110 LTOModule *LTOModule::makeLTOModule(std::unique_ptr Buffer,
106 StringRef Data((char *)mem, length);
107 MemoryBufferRef Buffer(Data, path);
108 return makeLTOModule(Buffer, options, errMsg);
109 }
110
111 LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
111112 TargetOptions options,
112113 std::string &errMsg) {
114 StringRef Data = Buffer.getBuffer();
115 StringRef FileName = Buffer.getBufferIdentifier();
116 std::unique_ptr MemBuf(
117 makeBuffer(Data.begin(), Data.size(), FileName));
118 if (!MemBuf)
119 return nullptr;
120
113121 ErrorOr MOrErr =
114 getLazyBitcodeModule(Buffer.get(), getGlobalContext());
122 getLazyBitcodeModule(MemBuf.get(), getGlobalContext());
115123 if (std::error_code EC = MOrErr.getError()) {
116124 errMsg = EC.message();
117125 return nullptr;
149157 M->setDataLayout(target->getSubtargetImpl()->getDataLayout());
150158
151159 std::unique_ptr IRObj(
152 new object::IRObjectFile(std::move(Buffer), std::move(M)));
160 new object::IRObjectFile(Buffer, std::move(M)));
153161
154162 LTOModule *Ret = new LTOModule(std::move(IRObj), target);
155163
108108 const char *NextLoc = Data.data() + SpaceToSkip;
109109
110110 // Check to see if this is past the end of the archive.
111 if (NextLoc >= Parent->Data->getBufferEnd())
111 if (NextLoc >= Parent->Data.getBufferEnd())
112112 return Child(Parent, nullptr);
113113
114114 return Child(Parent, NextLoc);
158158 return name;
159159 }
160160
161 ErrorOr>
162 Archive::Child::getMemoryBuffer(bool FullPath) const {
161 ErrorOr Archive::Child::getMemoryBufferRef() const {
163162 ErrorOr NameOrErr = getName();
164163 if (std::error_code EC = NameOrErr.getError())
165164 return EC;
166165 StringRef Name = NameOrErr.get();
167 SmallString<128> Path;
168 std::unique_ptr Ret(MemoryBuffer::getMemBuffer(
169 getBuffer(),
170 FullPath
171 ? (Twine(Parent->getFileName()) + "(" + Name + ")").toStringRef(Path)
172 : Name,
173 false));
174 return std::move(Ret);
166 return MemoryBufferRef(getBuffer(), Name);
175167 }
176168
177169 ErrorOr>
178170 Archive::Child::getAsBinary(LLVMContext *Context) const {
179 ErrorOr<std::unique_ptr> BuffOrErr = getMemoryBuffer();
171 ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
180172 if (std::error_code EC = BuffOrErr.getError())
181173 return EC;
182174
183 return createBinary(std::move(*BuffOrErr), Context);
184 }
185
186 ErrorOr>
187 Archive::create(std::unique_ptr Source) {
175 return createBinary(BuffOrErr.get(), Context);
176 }
177
178 ErrorOr> Archive::create(MemoryBufferRef Source) {
188179 std::error_code EC;
189 std::unique_ptr Ret(new Archive(std::move(Source), EC));
180 std::unique_ptr Ret(new Archive(Source, EC));
190181 if (EC)
191182 return EC;
192183 return std::move(Ret);
193184 }
194185
195 Archive::Archive(std::unique_ptr Source, std::error_code &ec)
196 : Binary(Binary::ID_Archive, std::move(Source)), SymbolTable(child_end()) {
186 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
187 : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()) {
197188 // Check for sufficient magic.
198 if (Data->getBufferSize() < 8 ||
199 StringRef(Data->getBufferStart(), 8) != Magic) {
189 if (Data.getBufferSize() < 8 ||
190 StringRef(Data.getBufferStart(), 8) != Magic) {
200191 ec = object_error::invalid_file_type;
201192 return;
202193 }
310301 }
311302
312303 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
313 if (Data->getBufferSize() == 8) // empty archive.
304 if (Data.getBufferSize() == 8) // empty archive.
314305 return child_end();
315306
316307 if (SkipInternal)
317308 return FirstRegular;
318309
319 const char *Loc = Data->getBufferStart() + strlen(Magic);
310 const char *Loc = Data.getBufferStart() + strlen(Magic);
320311 Child c(this, Loc);
321312 return c;
322313 }
2626
2727 Binary::~Binary() {}
2828
29 Binary::Binary(unsigned int Type, std::unique_ptr Source)
30 : TypeID(Type), Data(std::move(Source)) {}
29 Binary::Binary(unsigned int Type, MemoryBufferRef Source)
30 : TypeID(Type), Data(Source) {}
3131
32 StringRef Binary::getData() const {
33 return Data->getBuffer();
34 }
32 StringRef Binary::getData() const { return Data.getBuffer(); }
3533
36 StringRef Binary::getFileName() const {
37 return Data->getBufferIdentifier();
38 }
34 StringRef Binary::getFileName() const { return Data.getBufferIdentifier(); }
3935
40 ErrorOr>
41 object::createBinary(std::unique_ptr Buffer,
42 LLVMContext *Context) {
43 sys::fs::file_magic Type = sys::fs::identify_magic(Buffer->getBuffer());
36 MemoryBufferRef Binary::getMemoryBufferRef() const { return Data; }
37
38 ErrorOr> object::createBinary(MemoryBufferRef Buffer,
39 LLVMContext *Context) {
40 sys::fs::file_magic Type = sys::fs::identify_magic(Buffer.getBuffer());
4441
4542 switch (Type) {
4643 case sys::fs::file_magic::archive:
47 return Archive::create(std::move(Buffer));
44 return Archive::create(Buffer);
4845 case sys::fs::file_magic::elf_relocatable:
4946 case sys::fs::file_magic::elf_executable:
5047 case sys::fs::file_magic::elf_shared_object:
6562 case sys::fs::file_magic::bitcode:
6663 return ObjectFile::createSymbolicFile(Buffer, Type, Context);
6764 case sys::fs::file_magic::macho_universal_binary:
68 return MachOUniversalBinary::create(std::move(Buffer));
65 return MachOUniversalBinary::create(Buffer);
6966 case sys::fs::file_magic::unknown:
7067 case sys::fs::file_magic::windows_resource:
7168 // Unrecognized object file format.
7471 llvm_unreachable("Unexpected Binary File Type");
7572 }
7673
77 ErrorOr<std::unique_ptr> object::createBinary(StringRef Path) {
74 ErrorOr<OwningBinary> object::createBinary(StringRef Path) {
7875 ErrorOr> FileOrErr =
7976 MemoryBuffer::getFileOrSTDIN(Path);
8077 if (std::error_code EC = FileOrErr.getError())
8178 return EC;
82 return createBinary(std::move(*FileOrErr));
79 std::unique_ptr &Buffer = FileOrErr.get();
80
81 ErrorOr> BinOrErr =
82 createBinary(Buffer->getMemBufferRef());
83 if (std::error_code EC = BinOrErr.getError())
84 return EC;
85 std::unique_ptr &Bin = BinOrErr.get();
86
87 return OwningBinary(std::move(Bin), std::move(Buffer));
8388 }
3030 using support::little16_t;
3131
3232 // Returns false if size is greater than the buffer size. And sets ec.
33 static bool checkSize(const MemoryBuffer &M, std::error_code &EC,
34 uint64_t Size) {
33 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
3534 if (M.getBufferSize() < Size) {
3635 EC = object_error::unexpected_eof;
3736 return false;
4241 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
4342 // Returns unexpected_eof if error.
4443 template
45 static std::error_code getObject(const T *&Obj, const MemoryBuffer &M,
44 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
4645 const uint8_t *Ptr,
4746 const size_t Size = sizeof(T)) {
4847 uintptr_t Addr = uintptr_t(Ptr);
396395 // Initialize the pointer to the symbol table.
397396 std::error_code COFFObjectFile::initSymbolTablePtr() {
398397 if (std::error_code EC = getObject(
399 SymbolTable, *Data, base() + COFFHeader->PointerToSymbolTable,
398 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
400399 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
401400 return EC;
402401
407406 base() + COFFHeader->PointerToSymbolTable +
408407 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
409408 const ulittle32_t *StringTableSizePtr;
410 if (std::error_code EC =
411 getObject(StringTableSizePtr, *Data, StringTableAddr))
409 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
412410 return EC;
413411 StringTableSize = *StringTableSizePtr;
414412 if (std::error_code EC =
415 getObject(StringTable, *Data, StringTableAddr, StringTableSize))
413 getObject(StringTable, Data, StringTableAddr, StringTableSize))
416414 return EC;
417415
418416 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
510508 return object_error::success;
511509 }
512510
513 COFFObjectFile::COFFObjectFile(std::unique_ptr Object,
514 std::error_code &EC)
515 : ObjectFile(Binary::ID_COFF, std::move(Object)), COFFHeader(nullptr),
511 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
512 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
516513 PE32Header(nullptr), PE32PlusHeader(nullptr), DataDirectory(nullptr),
517514 SectionTable(nullptr), SymbolTable(nullptr), StringTable(nullptr),
518515 StringTableSize(0), ImportDirectory(nullptr), NumberOfImportDirectory(0),
519516 ExportDirectory(nullptr) {
520517 // Check that we at least have enough room for a header.
521 if (!checkSize(*Data, EC, sizeof(coff_file_header)))
518 if (!checkSize(Data, EC, sizeof(coff_file_header)))
522519 return;
523520
524521 // The current location in the file where we are looking at.
532529 if (base()[0] == 0x4d && base()[1] == 0x5a) {
533530 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
534531 // PE signature to find 'normal' COFF header.
535 if (!checkSize(*Data, EC, 0x3c + 8))
532 if (!checkSize(Data, EC, 0x3c + 8))
536533 return;
537534 CurPtr = *reinterpret_cast(base() + 0x3c);
538535 // Check the PE magic bytes. ("PE\0\0")
544541 HasPEHeader = true;
545542 }
546543
547 if ((EC = getObject(COFFHeader, *Data, base() + CurPtr)))
544 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
548545 return;
549546 CurPtr += sizeof(coff_file_header);
550547
551548 if (HasPEHeader) {
552549 const pe32_header *Header;
553 if ((EC = getObject(Header, *Data, base() + CurPtr)))
550 if ((EC = getObject(Header, Data, base() + CurPtr)))
554551 return;
555552
556553 const uint8_t *DataDirAddr;
568565 EC = object_error::parse_failed;
569566 return;
570567 }
571 if ((EC = getObject(DataDirectory, *Data, DataDirAddr, DataDirSize)))
568 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
572569 return;
573570 CurPtr += COFFHeader->SizeOfOptionalHeader;
574571 }
576573 if (COFFHeader->isImportLibrary())
577574 return;
578575
579 if ((EC = getObject(SectionTable, *Data, base() + CurPtr,
576 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
580577 COFFHeader->NumberOfSections * sizeof(coff_section))))
581578 return;
582579
825822 // data, as there's nothing that says that is not allowed.
826823 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
827824 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
828 if (ConEnd > uintptr_t(Data->getBufferEnd()))
825 if (ConEnd > uintptr_t(Data.getBufferEnd()))
829826 return object_error::parse_failed;
830827 Res = ArrayRef(reinterpret_cast(ConStart),
831828 Sec->SizeOfRawData);
10911088 }
10921089
10931090 ErrorOr>
1094 ObjectFile::createCOFFObjectFile(std::unique_ptr Object) {
1091 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
10951092 std::error_code EC;
1096 std::unique_ptr Ret(
1097 new COFFObjectFile(std::move(Object), EC));
1093 std::unique_ptr Ret(new COFFObjectFile(Object, EC));
10981094 if (EC)
10991095 return EC;
11001096 return std::move(Ret);
1616 namespace llvm {
1717 using namespace object;
1818
19 ELFObjectFileBase::ELFObjectFileBase(unsigned int Type,
20 std::unique_ptr Source)
21 : ObjectFile(Type, std::move(Source)) {}
19 ELFObjectFileBase::ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source)
20 : ObjectFile(Type, Source) {}
2221
2322 ErrorOr>
24 ObjectFile::createELFObjectFile(std::unique_ptr &Obj) {
23 ObjectFile::createELFObjectFile(MemoryBufferRef Obj) {
2524 std::pair Ident =
26 getElfArchType(Obj->getBuffer());
25 getElfArchType(Obj.getBuffer());
2726 std::size_t MaxAlignment =
28 1ULL << countTrailingZeros(uintptr_t(Obj->getBufferStart()));
27 1ULL << countTrailingZeros(uintptr_t(Obj.getBufferStart()));
2928
3029 std::error_code EC;
3130 std::unique_ptr R;
3231 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB)
3332 #if !LLVM_IS_UNALIGNED_ACCESS_FAST
3433 if (MaxAlignment >= 4)
35 R.reset(new ELFObjectFile>(
36 std::move(Obj), EC));
34 R.reset(new ELFObjectFile>(Obj, EC));
3735 else
3836 #endif
3937 if (MaxAlignment >= 2)
40 R.reset(new ELFObjectFile>(
41 std::move(Obj), EC));
38 R.reset(new ELFObjectFile>(Obj, EC));
4239 else
4340 return object_error::parse_failed;
4441 else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB)
4542 #if !LLVM_IS_UNALIGNED_ACCESS_FAST
4643 if (MaxAlignment >= 4)
47 R.reset(new ELFObjectFile>(std::move(Obj),
48 EC));
44 R.reset(new ELFObjectFile>(Obj, EC));
4945 else
5046 #endif
5147 if (MaxAlignment >= 2)
52 R.reset(new ELFObjectFile>(std::move(Obj),
53 EC));
48 R.reset(new ELFObjectFile>(Obj, EC));
5449 else
5550 return object_error::parse_failed;
5651 else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB)
5752 #if !LLVM_IS_UNALIGNED_ACCESS_FAST
5853 if (MaxAlignment >= 8)
59 R.reset(new ELFObjectFile>(std::move(Obj),
60 EC));
54 R.reset(new ELFObjectFile>(Obj, EC));
6155 else
6256 #endif
6357 if (MaxAlignment >= 2)
64 R.reset(new ELFObjectFile>(std::move(Obj),
65 EC));
58 R.reset(new ELFObjectFile>(Obj, EC));
6659 else
6760 return object_error::parse_failed;
6861 else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB) {
6962 #if !LLVM_IS_UNALIGNED_ACCESS_FAST
7063 if (MaxAlignment >= 8)
71 R.reset(new ELFObjectFile>(
72 std::move(Obj), EC));
64 R.reset(new ELFObjectFile>(Obj, EC));
7365 else
7466 #endif
7567 if (MaxAlignment >= 2)
76 R.reset(new ELFObjectFile>(
77 std::move(Obj), EC));
68 R.reset(new ELFObjectFile>(Obj, EC));
7869 else
7970 return object_error::parse_failed;
8071 }
3131 using namespace llvm;
3232 using namespace object;
3333
34 IRObjectFile::IRObjectFile(std::unique_ptr Object,
35 std::unique_ptr Mod)
36 : SymbolicFile(Binary::ID_IR, std::move(Object)), M(std::move(Mod)) {
34 IRObjectFile::IRObjectFile(MemoryBufferRef Object, std::unique_ptr Mod)
35 : SymbolicFile(Binary::ID_IR, Object), M(std::move(Mod)) {
3736 // If we have a DataLayout, setup a mangler.
3837 const DataLayout *DL = M->getDataLayout();
3938 if (!DL)
113112 }
114113
115114 IRObjectFile::~IRObjectFile() {
116 GVMaterializer *GVM = M->getMaterializer();
117 if (GVM)
118 GVM->releaseBuffer();
119115 }
120116
121117 static const GlobalValue *getGV(DataRefImpl &Symb) {
267263 return basic_symbol_iterator(BasicSymbolRef(Ret, this));
268264 }
269265
270 ErrorOr llvm::object::IRObjectFile::createIRObjectFile(
271 std::unique_ptr Object, LLVMContext &Context) {
272 ErrorOr MOrErr = getLazyBitcodeModule(Object.get(), Context);
266 ErrorOr
267 llvm::object::IRObjectFile::createIRObjectFile(MemoryBufferRef Object,
268 LLVMContext &Context) {
269
270 StringRef Data = Object.getBuffer();
271 StringRef FileName = Object.getBufferIdentifier();
272 std::unique_ptr Buff(
273 MemoryBuffer::getMemBuffer(Data, FileName, false));
274
275 ErrorOr MOrErr = getLazyBitcodeModule(Buff.get(), Context);
273276 if (std::error_code EC = MOrErr.getError())
274277 return EC;
278 Buff.release();
275279
276280 std::unique_ptr M(MOrErr.get());
277 return new IRObjectFile(std::move(Object), std::move(M));
278 }
281 return new IRObjectFile(Object, std::move(M));
282 }
221221 return Sect.flags;
222222 }
223223
224 MachOObjectFile::MachOObjectFile(std::unique_ptr Object,
225 bool IsLittleEndian, bool Is64bits,
226 std::error_code &EC)
227 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), std::move(Object)),
224 MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
225 bool Is64bits, std::error_code &EC)
226 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
228227 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
229228 DataInCodeLoadCmd(nullptr) {
230229 uint32_t LoadCommandCount = this->getHeader().ncmds;
17751774 }
17761775
17771776 ErrorOr>
1778 ObjectFile::createMachOObjectFile(std::unique_ptr &Buffer) {
1779 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1777 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer) {
1778 StringRef Magic = Buffer.getBuffer().slice(0, 4);
17801779 std::error_code EC;
17811780 std::unique_ptr Ret;
17821781 if (Magic == "\xFE\xED\xFA\xCE")
1783 Ret.reset(new MachOObjectFile(std::move(Buffer), false, false, EC));
1782 Ret.reset(new MachOObjectFile(Buffer, false, false, EC));
17841783 else if (Magic == "\xCE\xFA\xED\xFE")
1785 Ret.reset(new MachOObjectFile(std::move(Buffer), true, false, EC));
1784 Ret.reset(new MachOObjectFile(Buffer, true, false, EC));
17861785 else if (Magic == "\xFE\xED\xFA\xCF")
1787 Ret.reset(new MachOObjectFile(std::move(Buffer), false, true, EC));
1786 Ret.reset(new MachOObjectFile(Buffer, false, true, EC));
17881787 else if (Magic == "\xCF\xFA\xED\xFE")
1789 Ret.reset(new MachOObjectFile(std::move(Buffer), true, true, EC));
1788 Ret.reset(new MachOObjectFile(Buffer, true, true, EC));
17901789 else
17911790 return object_error::parse_failed;
17921791
7171 if (Parent) {
7272 StringRef ParentData = Parent->getData();
7373 StringRef ObjectData = ParentData.substr(Header.offset, Header.size);
74 std::string ObjectName = Parent->getFileName().str();
75 std::unique_ptr ObjBuffer(
76 MemoryBuffer::getMemBuffer(ObjectData, ObjectName, false));
74 StringRef ObjectName = Parent->getFileName().str();
75 MemoryBufferRef ObjBuffer(ObjectData, ObjectName);
7776 return ObjectFile::createMachOObjectFile(ObjBuffer);
7877 }
7978 return object_error::parse_failed;
8584 StringRef ParentData = Parent->getData();
8685 StringRef ObjectData = ParentData.substr(Header.offset, Header.size);
8786 std::string ObjectName = Parent->getFileName().str();
88 std::unique_ptr ObjBuffer(
89 MemoryBuffer::getMemBuffer(ObjectData, ObjectName, false));
90 ErrorOr> Obj =
91 Archive::create(std::move(ObjBuffer));
87 MemoryBufferRef ObjBuffer(ObjectData, ObjectName);
88 ErrorOr> Obj = Archive::create(ObjBuffer);
9289 if (std::error_code EC = Obj.getError())
9390 return EC;
9491 Result = std::move(Obj.get());
10097 void MachOUniversalBinary::anchor() { }
10198
10299 ErrorOr
103 MachOUniversalBinary::create(std::unique_ptr Source) {
100 MachOUniversalBinary::create(MemoryBufferRef Source) {
104101 std::error_code EC;
105102 std::unique_ptr Ret(
106 new MachOUniversalBinary(std::move(Source), EC));
103 new MachOUniversalBinary(Source, EC));
107104 if (EC)
108105 return EC;
109106 return Ret.release();
110107 }
111108
112 MachOUniversalBinary::MachOUniversalBinary(std::unique_ptr Source,
109 MachOUniversalBinary::MachOUniversalBinary(MemoryBufferRef Source,
113110 std::error_code &ec)
114 : Binary(Binary::ID_MachOUniversalBinary, std::move(Source)),
115 NumberOfObjects(0) {
116 if (Data->getBufferSize() < sizeof(MachO::fat_header)) {
111 : Binary(Binary::ID_MachOUniversalBinary, Source), NumberOfObjects(0) {
112 if (Data.getBufferSize() < sizeof(MachO::fat_header)) {
117113 ec = object_error::invalid_file_type;
118114 return;
119115 }
1818 using namespace llvm;
1919 using namespace object;
2020
21 inline ObjectFile *unwrap(LLVMObjectFileRef OF) {
22 return reinterpret_cast(OF);
23 }
24
25 inline LLVMObjectFileRef wrap(const ObjectFile *OF) {
26 return reinterpret_cast(const_cast(OF));
21 inline OwningBinary *unwrap(LLVMObjectFileRef OF) {
22 return reinterpret_cast *>(OF);
23 }
24
25 inline LLVMObjectFileRef wrap(const OwningBinary *OF) {
26 return reinterpret_cast(
27 const_cast *>(OF));
2728 }
2829
2930 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
6061 LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf) {
6162 std::unique_ptr Buf(unwrap(MemBuf));
6263 ErrorOr> ObjOrErr(
63 ObjectFile::createObjectFile(Buf));
64 Buf.release();
65 ObjectFile *Obj = ObjOrErr ? ObjOrErr.get().release() : nullptr;
66 return wrap(Obj);
64 ObjectFile::createObjectFile(Buf->getMemBufferRef()));
65 std::unique_ptr Obj;
66 if (ObjOrErr)
67 Obj = std::move(ObjOrErr.get());
68 auto *Ret = new OwningBinary(std::move(Obj), std::move(Buf));
69 return wrap(Ret);
6770 }
6871
6972 void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile) {
7174 }
7275
7376 // ObjectFile Section iterators
74 LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile) {
75 section_iterator SI = unwrap(ObjectFile)->section_begin();
77 LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef OF) {
78 OwningBinary *OB = unwrap(OF);
79 section_iterator SI = OB->getBinary()->section_begin();
7680 return wrap(new section_iterator(SI));
7781 }
7882
8084 delete unwrap(SI);
8185 }
8286
83 LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile,
84 LLVMSectionIteratorRef SI) {
85 return (*unwrap(SI) == unwrap(ObjectFile)->section_end()) ? 1 : 0;
87 LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef OF,
88 LLVMSectionIteratorRef SI) {
89 OwningBinary *OB = unwrap(OF);
90 return (*unwrap(SI) == OB->getBinary()->section_end()) ? 1 : 0;
8691 }
8792
8893 void LLVMMoveToNextSection(LLVMSectionIteratorRef SI) {
96101 }
97102
98103 // ObjectFile Symbol iterators
99 LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile) {
100 symbol_iterator SI = unwrap(ObjectFile)->symbol_begin();
104 LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef OF) {
105 OwningBinary *OB = unwrap(OF);
106 symbol_iterator SI = OB->getBinary()->symbol_begin();
101107 return wrap(new symbol_iterator(SI));
102108 }
103109
105111 delete unwrap(SI);
106112 }
107113
108 LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile,
109 LLVMSymbolIteratorRef SI) {
110 return (*unwrap(SI) == unwrap(ObjectFile)->symbol_end()) ? 1 : 0;
114 LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef OF,
115 LLVMSymbolIteratorRef SI) {
116 OwningBinary *OB = unwrap(OF);
117 return (*unwrap(SI) == OB->getBinary()->symbol_end()) ? 1 : 0;
111118 }
112119
113120 void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI) {
2424
2525 void ObjectFile::anchor() { }
2626
27 ObjectFile::ObjectFile(unsigned int Type, std::unique_ptr Source)
28 : SymbolicFile(Type, std::move(Source)) {}
27 ObjectFile::ObjectFile(unsigned int Type, MemoryBufferRef Source)
28 : SymbolicFile(Type, Source) {}
2929
3030 std::error_code ObjectFile::printSymbolName(raw_ostream &OS,
3131 DataRefImpl Symb) const {
4747 }
4848
4949 ErrorOr>
50 ObjectFile::createObjectFile(std::unique_ptr &Object,
51 sys::fs::file_magic Type) {
50 ObjectFile::createObjectFile(MemoryBufferRef Object, sys::fs::file_magic Type) {
51 StringRef Data = Object.getBuffer();
5252 if (Type == sys::fs::file_magic::unknown)
53 Type = sys::fs::identify_magic(Object->getBuffer());
53 Type = sys::fs::identify_magic(Data);
5454
5555 switch (Type) {
5656 case sys::fs::file_magic::unknown:
7878 case sys::fs::file_magic::coff_object:
7979 case sys::fs::file_magic::coff_import_library:
8080 case sys::fs::file_magic::pecoff_executable:
81 return createCOFFObjectFile(std::move(Object));
81 return createCOFFObjectFile(Object);
8282 }
8383 llvm_unreachable("Unexpected Object File Type");
8484 }
8585
86 ErrorOr<std::unique_ptr>
86 ErrorOr<OwningBinary>
8787 ObjectFile::createObjectFile(StringRef ObjectPath) {
8888 ErrorOr> FileOrErr =
8989 MemoryBuffer::getFile(ObjectPath);
9090 if (std::error_code EC = FileOrErr.getError())
9191 return EC;
92 return createObjectFile(FileOrErr.get());
92 std::unique_ptr Buffer = std::move(FileOrErr.get());
93
94 ErrorOr> ObjOrErr =
95 createObjectFile(Buffer->getMemBufferRef());
96 if (std::error_code EC = ObjOrErr.getError())
97 return EC;
98 std::unique_ptr Obj = std::move(ObjOrErr.get());
99
100 return OwningBinary(std::move(Obj), std::move(Buffer));
93101 }
1818 using namespace llvm;
1919 using namespace object;
2020
21 SymbolicFile::SymbolicFile(unsigned int Type,
22 std::unique_ptr Source)
23 : Binary(Type, std::move(Source)) {}
21 SymbolicFile::SymbolicFile(unsigned int Type, MemoryBufferRef Source)
22 : Binary(Type, Source) {}
2423
2524 SymbolicFile::~SymbolicFile() {}
2625
27 ErrorOr>
28 SymbolicFile::createSymbolicFile(std::unique_ptr &Object,
29 sys::fs::file_magic Type,
30 LLVMContext *Context) {
26 ErrorOr> SymbolicFile::createSymbolicFile(
27 MemoryBufferRef Object, sys::fs::file_magic Type, LLVMContext *Context) {
28 StringRef Data = Object.getBuffer();
3129 if (Type == sys::fs::file_magic::unknown)
32 Type = sys::fs::identify_magic(Object->getBuffer());
30 Type = sys::fs::identify_magic(Data);
3331
3432 switch (Type) {
3533 case sys::fs::file_magic::bitcode:
3634 if (Context)
37 return IRObjectFile::createIRObjectFile(std::move(Object), *Context);
35 return IRObjectFile::createIRObjectFile(Object, *Context);
3836 // Fallthrough
3937 case sys::fs::file_magic::unknown:
4038 case sys::fs::file_magic::archive:
291291 ObjectFileCoverageMappingReader::ObjectFileCoverageMappingReader(
292292 std::unique_ptr &ObjectBuffer, sys::fs::file_magic Type)
293293 : CurrentRecord(0) {
294 auto File = llvm::object::ObjectFile::createObjectFile(ObjectBuffer, Type);
294 auto File = object::ObjectFile::createObjectFile(
295 ObjectBuffer->getMemBufferRef(), Type);
295296 if (!File)
296297 error(File.getError());
297298 else
298 Object = std::move(File.get());
299 Object = OwningBinary(std::move(File.get()),
300 std::move(ObjectBuffer));
299301 }
300302
301303 namespace {
428430 }
429431
430432 std::error_code ObjectFileCoverageMappingReader::readHeader() {
431 if (!Object)
433 ObjectFile *OF = Object.getBinary().get();
434 if (!OF)
432435 return getError();
433 auto BytesInAddress = Object->getBytesInAddress();
436 auto BytesInAddress = OF->getBytesInAddress();
434437 if (BytesInAddress != 4 && BytesInAddress != 8)
435438 return error(instrprof_error::malformed);
436439
437440 // Look for the sections that we are interested in.
438441 int FoundSectionCount = 0;
439442 SectionRef ProfileNames, CoverageMapping;
440 for (const auto &Section : Object->sections()) {
443 for (const auto &Section : OF->sections()) {
441444 StringRef Name;
442445 if (auto Err = Section.getName(Name))
443446 return Err;
415415
416416 return getMemoryBufferForStream(0, "");
417417 }
418
419 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
420 StringRef Data = getBuffer();
421 StringRef Identifier = getBufferIdentifier();
422 return MemoryBufferRef(Data, Identifier);
423 }
262262 }
263263 virtual ~LLIObjectCache() {}
264264
265 void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) override {
265 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
266266 const std::string ModuleID = M->getModuleIdentifier();
267267 std::string CacheName;
268268 if (!getCacheFilename(ModuleID, CacheName))
274274 sys::fs::create_directories(Twine(dir));
275275 }
276276 raw_fd_ostream outfile(CacheName.c_str(), errStr, sys::fs::F_None);
277 outfile.write(Obj->getBufferStart(), Obj->getBufferSize());
277 outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
278278 outfile.close();
279279 }
280280
529529 }
530530
531531 for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
532 ErrorOr<std::unique_ptr> Obj =
532 ErrorOr<object::OwningBinary> Obj =
533533 object::ObjectFile::createObjectFile(ExtraObjects[i]);
534534 if (!Obj) {
535535 Err.print(argv[0], errs());
536536 return 1;
537537 }
538 EE->addObjectFile(std::move(Obj.get()));
538 EE->addObjectFile(std::move(Obj.get().getBinary()));
539539 }
540540
541541 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
542 ErrorOr> ArBuf =
542 ErrorOr> ArBufOrErr =
543543 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
544 if (!ArBuf) {
544 if (!ArBufOrErr) {
545545 Err.print(argv[0], errs());
546546 return 1;
547547 }
548 std::unique_ptr &ArBuf = ArBufOrErr.get();
548549
549550 ErrorOr> ArOrErr =
550 object::Archive::create(std::move(ArBuf.get()));
551 object::Archive::create(ArBuf->getMemBufferRef());
551552 if (std::error_code EC = ArOrErr.getError()) {
552553 errs() << EC.message();
553554 return 1;
554555 }
555 EE->addArchive(std::move(ArOrErr.get()));
556 std::unique_ptr &Ar = ArOrErr.get();
557
558 object::OwningBinary OB(std::move(Ar), std::move(ArBuf));
559
560 EE->addArchive(std::move(OB));
556561 }
557562
558563 // If the target is Cygwin/MingW and we are generating remote code, we
685685
686686 static void
687687 writeSymbolTable(raw_fd_ostream &Out, ArrayRef Members,
688 MutableArrayRef> Buffers,
688 ArrayRef> Buffers,
689689 std::vector> &MemberOffsetRefs) {
690690 unsigned StartOffset = 0;
691691 unsigned MemberNum = 0;
696696 for (ArrayRef::iterator I = Members.begin(),
697697 E = Members.end();
698698 I != E; ++I, ++MemberNum) {
699 std::unique_ptr &MemberBuffer = Buffers[MemberNum];
699 MemoryBufferRef MemberBuffer = Buffers[MemberNum];
700700 ErrorOr> ObjOrErr =
701701 object::SymbolicFile::createSymbolicFile(
702702 MemberBuffer, sys::fs::file_magic::unknown, &Context);
724724 MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
725725 print32BE(Out, 0);
726726 }
727 MemberBuffer.reset(Obj.releaseBuffer());
728727 }
729728 Out << NameOS.str();
730729
758757
759758 std::vector > MemberOffsetRefs;
760759
761 std::vector> MemberBuffers;
762 MemberBuffers.resize(NewMembers.size());
760 std::vector> Buffers;
761 std::vector Members;
763762
764763 for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
765 std::unique_ptr &MemberBuffer = MemberBuffers[I];
766764 NewArchiveIterator &Member = NewMembers[I];
765 MemoryBufferRef MemberRef;
767766
768767 if (Member.isNewMember()) {
769768 const char *Filename = Member.getNew();
772771 ErrorOr> MemberBufferOrErr =
773772 MemoryBuffer::getOpenFile(FD, Filename, Status.getSize(), false);
774773 failIfError(MemberBufferOrErr.getError(), Filename);
775 MemberBuffer = std::move(MemberBufferOrErr.get());
774 Buffers.push_back(std::move(MemberBufferOrErr.get()));
775 MemberRef = Buffers.back()->getMemBufferRef();
776776 } else {
777777 object::Archive::child_iterator OldMember = Member.getOld();
778 ErrorOr> MemberBufferOrErr =
779 OldMember->getMemoryBuffer();
778 ErrorOr MemberBufferOrErr =
779 OldMember->getMemoryBufferRef();
780780 failIfError(MemberBufferOrErr.getError());
781 MemberBuffer = std::move(MemberBufferOrErr.get());
782 }
781 MemberRef = MemberBufferOrErr.get();
782 }
783 Members.push_back(MemberRef);
783784 }
784785
785786 if (Symtab) {
786 writeSymbolTable(Out, NewMembers, MemberBuffers, MemberOffsetRefs);
787 writeSymbolTable(Out, NewMembers, Members, MemberOffsetRefs);
787788 }
788789
789790 std::vector StringMapIndexes;
807808 }
808809 Out.seek(Pos);
809810
810 const MemoryBuffer *File = MemberBuffers[MemberNum].get();
811 MemoryBufferRef File = Members[MemberNum];
811812 if (I->isNewMember()) {
812813 const char *FileName = I->getNew();
813814 const sys::fs::file_status &Status = I->getStatus();
837838 OldMember->getSize());
838839 }
839840
840 Out << File->getBuffer();
841 Out << File.getBuffer();
841842
842843 if (Out.tell() % 2)
843844 Out << '\n';
942943 }
943944
944945 if (!EC) {
945 object::Archive Archive(std::move(Buf.get()), EC);
946 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
946947
947948 if (EC) {
948949 errs() << ToolName << ": error loading '" << ArchiveName
6565 clEnumValEnd));
6666
6767 static void DumpInput(const StringRef &Filename) {
68 ErrorOr> Buff =
68 ErrorOr> BuffOrErr =
6969 MemoryBuffer::getFileOrSTDIN(Filename);
7070
71 if (std::error_code EC = Buff.getError()) {
71 if (std::error_code EC = BuffOrErr.getError()) {
7272 errs() << Filename << ": " << EC.message() << "\n";
7373 return;
7474 }
75 std::unique_ptr Buff = std::move(BuffOrErr.get());
7576
7677 ErrorOr> ObjOrErr =
77 ObjectFile::createObjectFile(Buff.get());
78 ObjectFile::createObjectFile(Buff->getMemBufferRef());
7879 if (std::error_code EC = ObjOrErr.getError()) {
7980 errs() << Filename << ": " << EC.message() << '\n';
8081 return;
10091009
10101010 LLVMContext &Context = getGlobalContext();
10111011 ErrorOr> BinaryOrErr =
1012 createBinary(std::move(*BufferOrErr), &Context);
1012 createBinary(BufferOrErr.get()->getMemBufferRef(), &Context);
10131013 if (error(BinaryOrErr.getError(), Filename))
10141014 return;
10151015 Binary &Bin = *BinaryOrErr.get();
209209 MachOObjectFile *MachOOF);
210210
211211 void llvm::DisassembleInputMachO(StringRef Filename) {
212 ErrorOr> Buff =
212 ErrorOr> BuffOrErr =
213213 MemoryBuffer::getFileOrSTDIN(Filename);
214 if (std::error_code EC = Buff.getError()) {
214 if (std::error_code EC = BuffOrErr.getError()) {
215215 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
216216 return;
217217 }
218
219 std::unique_ptr MachOOF =
220 std::move(ObjectFile::createMachOObjectFile(Buff.get()).get());
218 std::unique_ptr Buff = std::move(BuffOrErr.get());
219
220 std::unique_ptr MachOOF = std::move(
221 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
221222
222223 DisassembleInputMachO2(Filename, MachOOF.get());
223224 }
351352 // A separate DSym file path was specified, parse it as a macho file,
352353 // get the sections and supply it to the section name parsing machinery.
353354 if (!DSYMFile.empty()) {
354 ErrorOr> Buf =
355 ErrorOr> BufOrErr =
355356 MemoryBuffer::getFileOrSTDIN(DSYMFile);
356 if (std::error_code EC = Buf.getError()) {
357 if (std::error_code EC = BufOrErr.getError()) {
357358 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
358359 return;
359360 }
360 DbgObj = ObjectFile::createMachOObjectFile(Buf.get()).get().release();
361 DbgObj =
362 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
363 .get()
364 .release();
361365 }
362366
363367 // Setup the DIContext
891891 }
892892
893893 // Attempt to open the binary.
894 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(file);
894 ErrorOr<OwningBinary> BinaryOrErr = createBinary(file);
895895 if (std::error_code EC = BinaryOrErr.getError()) {
896896 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
897897 return;
898898 }
899 Binary &Binary = *BinaryOrErr.get();
899 Binary &Binary = *BinaryOrErr.get().getBinary();
900900
901901 if (Archive *a = dyn_cast(&Binary))
902902 DumpArchive(a);
298298 }
299299
300300 // Attempt to open the binary.
301 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(File);
301 ErrorOr<OwningBinary> BinaryOrErr = createBinary(File);
302302 if (std::error_code EC = BinaryOrErr.getError()) {
303303 reportError(File, EC);
304304 return;
305305 }
306 Binary &Binary = *BinaryOrErr.get();
306 Binary &Binary = *BinaryOrErr.get().getBinary();
307307
308308 if (Archive *Arc = dyn_cast(&Binary))
309309 dumpArchive(Arc);
452452 }
453453
454454 // Attempt to open the binary.
455 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(file);
455 ErrorOr<OwningBinary> BinaryOrErr = createBinary(file);
456456 if (std::error_code EC = BinaryOrErr.getError()) {
457457 errs() << ToolName << ": " << file << ": " << EC.message() << ".\n";
458458 return;
459459 }
460 Binary &Bin = *BinaryOrErr.get();
460 Binary &Bin = *BinaryOrErr.get().getBinary();
461461
462462 if (Archive *a = dyn_cast(&Bin)) {
463463 // This is an archive. Iterate over each member and display its sizes.
299299 return I->second;
300300 Binary *Bin = nullptr;
301301 Binary *DbgBin = nullptr;
302 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(Path);
302 ErrorOr<OwningBinary> BinaryOrErr = createBinary(Path);
303303 if (!error(BinaryOrErr.getError())) {
304 std::unique_ptr &ParsedBinary = BinaryOrErr.get();
304 OwningBinary &ParsedBinary = BinaryOrErr.get();
305305 // Check if it's a universal binary.
306 Bin = ParsedBinary.get();
307 ParsedBinariesAndObjects.push_back(std::move(ParsedBinary));
306 Bin = ParsedBinary.getBinary().get();
307 addOwningBinary(std::move(ParsedBinary));
308308 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
309309 // On Darwin we may find DWARF in separate object file in
310310 // resource directory.
313313 BinaryOrErr = createBinary(ResourcePath);
314314 std::error_code EC = BinaryOrErr.getError();
315315 if (EC != errc::no_such_file_or_directory && !error(EC)) {
316 DbgBin = BinaryOrErr.get().get();
317 ParsedBinariesAndObjects.push_back(std::move(BinaryOrErr.get()));
316 OwningBinary B = std::move(BinaryOrErr.get());
317 DbgBin = B.getBinary().get();
318 addOwningBinary(std::move(B));
318319 }
319320 }
320321 // Try to locate the debug binary using .gnu_debuglink section.
326327 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
327328 BinaryOrErr = createBinary(DebugBinaryPath);
328329 if (!error(BinaryOrErr.getError())) {
329 DbgBin = BinaryOrErr.get().get();
330 ParsedBinariesAndObjects.push_back(std::move(BinaryOrErr.get()));
330 OwningBinary B = std::move(BinaryOrErr.get());
331 DbgBin = B.getBinary().get();
332 addOwningBinary(std::move(B));
331333 }
332334 }
333335 }
7474
7575 // Owns all the parsed binaries and object files.
7676 SmallVector, 4> ParsedBinariesAndObjects;
77 SmallVector, 4> MemoryBuffers;
78 void addOwningBinary(OwningBinary Bin) {
79 ParsedBinariesAndObjects.push_back(std::move(Bin.getBinary()));
80 MemoryBuffers.push_back(std::move(Bin.getBuffer()));
81 }
82
7783 // Owns module info objects.
7884 typedef std::map ModuleMapTy;
7985 ModuleMapTy Modules;
163163 }
164164
165165 // Attempt to open the binary.
166 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(File);
166 ErrorOr<OwningBinary> BinaryOrErr = createBinary(File);
167167 if (std::error_code EC = BinaryOrErr.getError()) {
168168 reportError(File, EC);
169169 return;
170170 }
171 Binary &Binary = *BinaryOrErr.get();
171 Binary &Binary = *BinaryOrErr.get().getBinary();
172172
173173 if (Archive *Arc = dyn_cast(&Binary))
174174 dumpArchive(Arc);
402402
403403 cl::ParseCommandLineOptions(argc, argv, "llvm Mach-O dumping tool\n");
404404
405 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(InputFile);
405 ErrorOr<OwningBinary> BinaryOrErr = createBinary(InputFile);
406406 if (std::error_code EC = BinaryOrErr.getError())
407407 return Error("unable to read input: '" + EC.message() + "'");
408 Binary &Binary = *BinaryOrErr.get();
408 Binary &Binary = *BinaryOrErr.get().getBinary();
409409
410410 const MachOObjectFile *InputObject = dyn_cast(&Binary);
411411 if (!InputObject)
3131 if (File != "-" && !sys::fs::exists(File))
3232 return obj2yaml_error::file_not_found;
3333
34 ErrorOr<std::unique_ptr> BinaryOrErr = createBinary(File);
34 ErrorOr<OwningBinary> BinaryOrErr = createBinary(File);
3535 if (std::error_code EC = BinaryOrErr.getError())
3636 return EC;
3737
38 Binary &Binary = *BinaryOrErr.get();
38 Binary &Binary = *BinaryOrErr.get().getBinary();
3939 // TODO: If this is an archive, then burst it and dump each entry
4040 if (ObjectFile *Obj = dyn_cast(&Binary))
4141 return dumpObject(*Obj);
2424 public:
2525 TestObjectCache() : DuplicateInserted(false) { }
2626
27 virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
27 void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
2828 // If we've seen this module before, note that.
2929 const std::string ModuleID = M->getModuleIdentifier();
3030 if (ObjMap.find(ModuleID) != ObjMap.end())
6262 }
6363
6464 private:
65 MemoryBuffer *copyBuffer(const MemoryBuffer *Buf) {
65 MemoryBuffer *copyBuffer(MemoryBufferRef Buf) {
6666 // Create a local copy of the buffer.
6767 std::unique_ptr NewBuffer(
68 MemoryBuffer::getMemBufferCopy(Buf->getBuffer()));
68 MemoryBuffer::getMemBufferCopy(Buf.getBuffer()));
6969 MemoryBuffer *Ret = NewBuffer.get();
7070 AllocatedBuffers.push_back(std::move(NewBuffer));
7171 return Ret;