llvm.org GIT mirror llvm / 7cba2a9
Update the MemoryBuffer API to use ErrorOr. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@212405 91177308-0d34-0410-b5e6-96231b3b80d8 Rafael Espindola 5 years ago
35 changed file(s) with 310 addition(s) and 293 deletion(s). Raw diff Collapse all Expand all
1818 #include "llvm/Support/CBindingWrapping.h"
1919 #include "llvm/Support/Compiler.h"
2020 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorOr.h"
2122 #include
2223 #include
2324
5960 return "Unknown buffer";
6061 }
6162
62 /// getFile - Open the specified file as a MemoryBuffer, returning a new
63 /// MemoryBuffer if successful, otherwise returning null. If FileSize is
64 /// specified, this means that the client knows that the file exists and that
65 /// it has the specified size.
63 /// Open the specified file as a MemoryBuffer, returning a new MemoryBuffer
64 /// if successful, otherwise returning null. If FileSize is specified, this
65 /// means that the client knows that the file exists and that it has the
66 /// specified size.
6667 ///
6768 /// \param IsVolatileSize Set to true to indicate that the file size may be
6869 /// changing, e.g. when libclang tries to parse while the user is
6970 /// editing/updating the file.
70 static std::error_code getFile(Twine Filename,
71 std::unique_ptr &Result,
72 int64_t FileSize = -1,
73 bool RequiresNullTerminator = true,
74 bool IsVolatileSize = false);
71 static ErrorOr>
72 getFile(Twine Filename, int64_t FileSize = -1,
73 bool RequiresNullTerminator = true, bool IsVolatileSize = false);
7574
7675 /// Given an already-open file descriptor, map some slice of it into a
7776 /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize.
8079 /// \param IsVolatileSize Set to true to indicate that the file size may be
8180 /// changing, e.g. when libclang tries to parse while the user is
8281 /// editing/updating the file.
83 static std::error_code getOpenFileSlice(int FD, const char *Filename,
84 std::unique_ptr &Result,
85 uint64_t MapSize, int64_t Offset,
86 bool IsVolatileSize = false);
82 static ErrorOr>
83 getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize,
84 int64_t Offset, bool IsVolatileSize = false);
8785
8886 /// Given an already-open file descriptor, read the file and return a
8987 /// MemoryBuffer.
9189 /// \param IsVolatileSize Set to true to indicate that the file size may be
9290 /// changing, e.g. when libclang tries to parse while the user is
9391 /// editing/updating the file.
94 static std::error_code getOpenFile(int FD, const char *Filename,
95 std::unique_ptr &Result,
96 uint64_t FileSize,
97 bool RequiresNullTerminator = true,
98 bool IsVolatileSize = false);
92 static ErrorOr>
93 getOpenFile(int FD, const char *Filename, uint64_t FileSize,
94 bool RequiresNullTerminator = true, bool IsVolatileSize = false);
9995
10096 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
10197 /// that InputData must be null terminated if RequiresNullTerminator is true.
122118 static MemoryBuffer *getNewUninitMemBuffer(size_t Size,
123119 StringRef BufferName = "");
124120
125 /// getSTDIN - Read all of stdin into a file buffer, and return it.
126 /// If an error occurs, this returns null and sets ec.
127 static std::error_code getSTDIN(std::unique_ptr &Result);
121 /// Read all of stdin into a file buffer, and return it.
122 static ErrorOr> getSTDIN();
128123
129 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
130 /// if the Filename is "-". If an error occurs, this returns null and sets
131 /// ec.
132 static std::error_code getFileOrSTDIN(StringRef Filename,
133 std::unique_ptr &Result,
134 int64_t FileSize = -1);
124 /// Open the specified file as a MemoryBuffer, or open stdin if the Filename
125 /// is "-".
126 static ErrorOr>
127 getFileOrSTDIN(StringRef Filename, int64_t FileSize = -1);
135128
136129 //===--------------------------------------------------------------------===//
137130 // Provided for performance analysis.
4040
4141 Module *llvm::ParseAssemblyFile(const std::string &Filename, SMDiagnostic &Err,
4242 LLVMContext &Context) {
43 std::unique_ptr File;
44 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, File)) {
43 ErrorOr> FileOrErr =
44 MemoryBuffer::getFileOrSTDIN(Filename);
45 if (std::error_code EC = FileOrErr.getError()) {
4546 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
46 "Could not open input file: " + ec.message());
47 "Could not open input file: " + EC.message());
4748 return nullptr;
4849 }
4950
50 return ParseAssembly(File.release(), nullptr, Err, Context);
51 return ParseAssembly(FileOrErr.get().release(), nullptr, Err, Context);
5152 }
5253
5354 Module *llvm::ParseAssemblyString(const char *AsmString, Module *M,
26052605 LLVMMemoryBufferRef *OutMemBuf,
26062606 char **OutMessage) {
26072607
2608 std::unique_ptr MB;
2609 std::error_code ec;
2610 if (!(ec = MemoryBuffer::getFile(Path, MB))) {
2611 *OutMemBuf = wrap(MB.release());
2612 return 0;
2608 ErrorOr> MBOrErr = MemoryBuffer::getFile(Path);
2609 if (std::error_code EC = MBOrErr.getError()) {
2610 *OutMessage = strdup(EC.message().c_str());
2611 return 1;
26132612 }
2614
2615 *OutMessage = strdup(ec.message().c_str());
2616 return 1;
2613 *OutMemBuf = wrap(MBOrErr.get().release());
2614 return 0;
26172615 }
26182616
26192617 LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
26202618 char **OutMessage) {
2621 std::unique_ptr MB;
2622 std::error_code ec;
2623 if (!(ec = MemoryBuffer::getSTDIN(MB))) {
2624 *OutMemBuf = wrap(MB.release());
2625 return 0;
2619 ErrorOr> MBOrErr = MemoryBuffer::getSTDIN();
2620 if (std::error_code EC = MBOrErr.getError()) {
2621 *OutMessage = strdup(EC.message().c_str());
2622 return 1;
26262623 }
2627
2628 *OutMessage = strdup(ec.message().c_str());
2629 return 1;
2624 *OutMemBuf = wrap(MBOrErr.get().release());
2625 return 0;
26302626 }
26312627
26322628 LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(
437437 StringRef Remaining;
438438 public:
439439 LineConsumer(StringRef Filename) {
440 if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Filename, Buffer)) {
440 ErrorOr> BufferOrErr =
441 MemoryBuffer::getFileOrSTDIN(Filename);
442 if (std::error_code EC = BufferOrErr.getError()) {
441443 errs() << Filename << ": " << EC.message() << "\n";
442444 Remaining = "";
443 } else
445 } else {
446 Buffer = std::move(BufferOrErr.get());
444447 Remaining = Buffer->getBuffer();
448 }
445449 }
446450 bool empty() { return Remaining.empty(); }
447451 void printNext(raw_ostream &OS, uint32_t LineNum) {
5050
5151 Module *llvm::getLazyIRFileModule(const std::string &Filename, SMDiagnostic &Err,
5252 LLVMContext &Context) {
53 std::unique_ptr File;
54 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, File)) {
53 ErrorOr> FileOrErr =
54 MemoryBuffer::getFileOrSTDIN(Filename);
55 if (std::error_code EC = FileOrErr.getError()) {
5556 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
56 "Could not open input file: " + ec.message());
57 "Could not open input file: " + EC.message());
5758 return nullptr;
5859 }
5960
60 return getLazyIRModule(File.release(), Err, Context);
61 return getLazyIRModule(FileOrErr.get().release(), Err, Context);
6162 }
6263
6364 Module *llvm::ParseIR(MemoryBuffer *Buffer, SMDiagnostic &Err,
8485
8586 Module *llvm::ParseIRFile(const std::string &Filename, SMDiagnostic &Err,
8687 LLVMContext &Context) {
87 std::unique_ptr File;
88 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, File)) {
88 ErrorOr> FileOrErr =
89 MemoryBuffer::getFileOrSTDIN(Filename);
90 if (std::error_code EC = FileOrErr.getError()) {
8991 Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
90 "Could not open input file: " + ec.message());
92 "Could not open input file: " + EC.message());
9193 return nullptr;
9294 }
9395
94 return ParseIR(File.get(), Err, Context);
96 return ParseIR(FileOrErr.get().get(), Err, Context);
9597 }
9698
9799 //===----------------------------------------------------------------------===//
235235 delete NativeObjectFile;
236236
237237 // read .o file into memory buffer
238 std::unique_ptr BuffPtr;
239 if (std::error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
240 errMsg = ec.message();
238 ErrorOr> BufferOrErr =
239 MemoryBuffer::getFile(name, -1, false);
240 if (std::error_code EC = BufferOrErr.getError()) {
241 errMsg = EC.message();
241242 sys::fs::remove(NativeObjectPath);
242243 return nullptr;
243244 }
244 NativeObjectFile = BuffPtr.release();
245 NativeObjectFile = BufferOrErr.get().release();
245246
246247 // remove temp files
247248 sys::fs::remove(NativeObjectPath);
6868
6969 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
7070 std::string &errMsg) {
71 std::unique_ptr buffer;
72 if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
73 errMsg = ec.message();
71 ErrorOr> BufferOrErr =
72 MemoryBuffer::getFile(path);
73 if (std::error_code EC = BufferOrErr.getError()) {
74 errMsg = EC.message();
7475 return nullptr;
7576 }
76 return makeLTOModule(std::move(buffer), options, errMsg);
77 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
7778 }
7879
7980 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
8687 size_t map_size, off_t offset,
8788 TargetOptions options,
8889 std::string &errMsg) {
89 std::unique_ptr buffer;
90 if (std::error_code ec =
91 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
92 errMsg = ec.message();
90 ErrorOr> BufferOrErr =
91 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
92 if (std::error_code EC = BufferOrErr.getError()) {
93 errMsg = EC.message();
9394 return nullptr;
9495 }
95 return makeLTOModule(std::move(buffer), options, errMsg);
96 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
9697 }
9798
9899 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
7474 }
7575
7676 ErrorOr object::createBinary(StringRef Path) {
77 std::unique_ptr File;
78 if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Path, File))
77 ErrorOr> FileOrErr =
78 MemoryBuffer::getFileOrSTDIN(Path);
79 if (std::error_code EC = FileOrErr.getError())
7980 return EC;
80 return createBinary(File);
81 return createBinary(FileOrErr.get());
8182 }
8282 }
8383
8484 ErrorOr ObjectFile::createObjectFile(StringRef ObjectPath) {
85 std::unique_ptr File;
86 if (std::error_code EC = MemoryBuffer::getFile(ObjectPath, File))
85 ErrorOr> FileOrErr =
86 MemoryBuffer::getFile(ObjectPath);
87 if (std::error_code EC = FileOrErr.getError())
8788 return EC;
88 return createObjectFile(File);
89 return createObjectFile(FileOrErr.get());
8990 }
2222
2323 static std::error_code
2424 setupMemoryBuffer(std::string Path, std::unique_ptr &Buffer) {
25 if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Path, Buffer))
25 ErrorOr> BufferOrErr =
26 MemoryBuffer::getFileOrSTDIN(Path);
27 if (std::error_code EC = BufferOrErr.getError())
2628 return EC;
29 Buffer = std::move(BufferOrErr.get());
2730
2831 // Sanity check the file.
2932 if (Buffer->getBufferSize() > std::numeric_limits::max())
630630 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
631631 TokenizerCallback Tokenizer,
632632 SmallVectorImpl &NewArgv) {
633 std::unique_ptr MemBuf;
634 if (MemoryBuffer::getFile(FName, MemBuf))
633 ErrorOr> MemBufOrErr =
634 MemoryBuffer::getFile(FName);
635 if (!MemBufOrErr)
635636 return false;
637 std::unique_ptr MemBuf = std::move(MemBufOrErr.get());
636638 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
637639
638640 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
175175 std::string *Error) {
176176 // Now its safe to mmap the files into memory because both files
177177 // have a non-zero size.
178 std::unique_ptr F1;
179 if (std::error_code ec = MemoryBuffer::getFile(NameA, F1)) {
178 ErrorOr> F1OrErr = MemoryBuffer::getFile(NameA);
179 if (std::error_code EC = F1OrErr.getError()) {
180180 if (Error)
181 *Error = ec.message();
181 *Error = EC.message();
182182 return 2;
183183 }
184 std::unique_ptr F2;
185 if (std::error_code ec = MemoryBuffer::getFile(NameB, F2)) {
184 std::unique_ptr F1 = std::move(F1OrErr.get());
185
186 ErrorOr> F2OrErr = MemoryBuffer::getFile(NameB);
187 if (std::error_code EC = F2OrErr.getError()) {
186188 if (Error)
187 *Error = ec.message();
189 *Error = EC.message();
188190 return 2;
189191 }
192 std::unique_ptr F2 = std::move(F2OrErr.get());
190193
191194 // Okay, now that we opened the files, scan them for the first difference.
192195 const char *File1Start = F1->getBufferStart();
3232 LockFileManager::readLockFile(StringRef LockFileName) {
3333 // Read the owning host and PID out of the lock file. If it appears that the
3434 // owning process is dead, the lock file is invalid.
35 std::unique_ptr MB;
36 if (MemoryBuffer::getFile(LockFileName, MB)) {
35 ErrorOr> MBOrErr =
36 MemoryBuffer::getFile(LockFileName);
37 if (!MBOrErr) {
3738 sys::fs::remove(LockFileName);
3839 return None;
3940 }
41 std::unique_ptr MB = std::move(MBOrErr.get());
4042
4143 StringRef Hostname;
4244 StringRef PIDStr;
151151 return SB;
152152 }
153153
154
155 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
156 /// if the Filename is "-". If an error occurs, this returns null and fills
157 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
158 /// returns an empty buffer.
159 std::error_code
160 MemoryBuffer::getFileOrSTDIN(StringRef Filename,
161 std::unique_ptr &Result,
162 int64_t FileSize) {
154 ErrorOr>
155 MemoryBuffer::getFileOrSTDIN(StringRef Filename, int64_t FileSize) {
163156 if (Filename == "-")
164 return getSTDIN(Result);
165 return getFile(Filename, Result, FileSize);
157 return getSTDIN();
158 return getFile(Filename, FileSize);
166159 }
167160
168161
211204 };
212205 }
213206
214 static std::error_code
215 getMemoryBufferForStream(int FD, StringRef BufferName,
216 std::unique_ptr &Result) {
207 static ErrorOr>
208 getMemoryBufferForStream(int FD, StringRef BufferName) {
217209 const ssize_t ChunkSize = 4096*4;
218210 SmallString Buffer;
219211 ssize_t ReadBytes;
228220 Buffer.set_size(Buffer.size() + ReadBytes);
229221 } while (ReadBytes != 0);
230222
231 Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
232 return std::error_code();
233 }
234
235 static std::error_code getFileAux(const char *Filename,
236 std::unique_ptr &Result,
237 int64_t FileSize, bool RequiresNullTerminator,
238 bool IsVolatileSize);
239
240 std::error_code MemoryBuffer::getFile(Twine Filename,
241 std::unique_ptr &Result,
242 int64_t FileSize,
243 bool RequiresNullTerminator,
244 bool IsVolatileSize) {
223 std::unique_ptr Ret(
224 MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
225 return std::move(Ret);
226 }
227
228 static ErrorOr>
229 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator,
230 bool IsVolatileSize);
231
232 ErrorOr>
233 MemoryBuffer::getFile(Twine Filename, int64_t FileSize,
234 bool RequiresNullTerminator, bool IsVolatileSize) {
245235 // Ensure the path is null terminated.
246236 SmallString<256> PathBuf;
247237 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
248 return getFileAux(NullTerminatedName.data(), Result, FileSize,
249 RequiresNullTerminator, IsVolatileSize);
250 }
251
252 static std::error_code getOpenFileImpl(int FD, const char *Filename,
253 std::unique_ptr &Result,
254 uint64_t FileSize, uint64_t MapSize,
255 int64_t Offset,
256 bool RequiresNullTerminator,
257 bool IsVolatileSize);
258
259 static std::error_code getFileAux(const char *Filename,
260 std::unique_ptr &Result,
261 int64_t FileSize, bool RequiresNullTerminator,
262 bool IsVolatileSize) {
238 return getFileAux(NullTerminatedName.data(), FileSize, RequiresNullTerminator,
239 IsVolatileSize);
240 }
241
242 static ErrorOr>
243 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize,
244 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
245 bool IsVolatileSize);
246
247 static ErrorOr>
248 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator,
249 bool IsVolatileSize) {
263250 int FD;
264251 std::error_code EC = sys::fs::openFileForRead(Filename, FD);
265252 if (EC)
266253 return EC;
267254
268 std::error_code ret =
269 getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
255 ErrorOr> Ret =
256 getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
270257 RequiresNullTerminator, IsVolatileSize);
271258 close(FD);
272 return ret;
259 return Ret;
273260 }
274261
275262 static bool shouldUseMmap(int FD,
320307 return true;
321308 }
322309
323 static std::error_code getOpenFileImpl(int FD, const char *Filename,
324 std::unique_ptr &Result,
325 uint64_t FileSize, uint64_t MapSize,
326 int64_t Offset,
327 bool RequiresNullTerminator,
328 bool IsVolatileSize) {
310 static ErrorOr>
311 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize,
312 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
313 bool IsVolatileSize) {
329314 static int PageSize = sys::process::get_self()->page_size();
330315
331316 // Default is to map the full file.
344329 sys::fs::file_type Type = Status.type();
345330 if (Type != sys::fs::file_type::regular_file &&
346331 Type != sys::fs::file_type::block_file)
347 return getMemoryBufferForStream(FD, Filename, Result);
332 return getMemoryBufferForStream(FD, Filename);
348333
349334 FileSize = Status.getSize();
350335 }
354339 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
355340 PageSize, IsVolatileSize)) {
356341 std::error_code EC;
357 Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
358 RequiresNullTerminator, FD, MapSize, Offset, EC));
342 std::unique_ptr Result(
343 new (NamedBufferAlloc(Filename))
344 MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
359345 if (!EC)
360 return std::error_code();
346 return std::move(Result);
361347 }
362348
363349 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
396382 BufPtr += NumRead;
397383 }
398384
399 Result.swap(SB);
400 return std::error_code();
401 }
402
403 std::error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
404 std::unique_ptr &Result,
405 uint64_t FileSize,
406 bool RequiresNullTerminator,
407 bool IsVolatileSize) {
408 return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
385 return std::move(SB);
386 }
387
388 ErrorOr>
389 MemoryBuffer::getOpenFile(int FD, const char *Filename, uint64_t FileSize,
390 bool RequiresNullTerminator, bool IsVolatileSize) {
391 return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
409392 RequiresNullTerminator, IsVolatileSize);
410393 }
411394
412 std::error_code MemoryBuffer::getOpenFileSlice(
413 int FD, const char *Filename, std::unique_ptr &Result,
414 uint64_t MapSize, int64_t Offset, bool IsVolatileSize) {
415 return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
395 ErrorOr>
396 MemoryBuffer::getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize,
397 int64_t Offset, bool IsVolatileSize) {
398 return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false,
416399 IsVolatileSize);
417400 }
418401
419 //===----------------------------------------------------------------------===//
420 // MemoryBuffer::getSTDIN implementation.
421 //===----------------------------------------------------------------------===//
422
423 std::error_code MemoryBuffer::getSTDIN(std::unique_ptr &Result) {
402 ErrorOr> MemoryBuffer::getSTDIN() {
424403 // Read in all of the data from stdin, we cannot mmap stdin.
425404 //
426405 // FIXME: That isn't necessarily true, we should try to mmap stdin and
427406 // fallback if it fails.
428407 sys::ChangeStdinToBinary();
429408
430 return getMemoryBufferForStream(0, "", Result);
431 }
409 return getMemoryBufferForStream(0, "");
410 }
5151 size_t SourceMgr::AddIncludeFile(const std::string &Filename,
5252 SMLoc IncludeLoc,
5353 std::string &IncludedFile) {
54 std::unique_ptr NewBuf;
5554 IncludedFile = Filename;
56 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
55 ErrorOr> NewBufOrErr =
56 MemoryBuffer::getFile(IncludedFile.c_str());
5757
5858 // If the file didn't exist directly, see if it's in an include path.
59 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) {
60 IncludedFile = IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
61 MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf);
62 }
63
64 if (!NewBuf)
59 for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr;
60 ++i) {
61 IncludedFile =
62 IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
63 NewBufOrErr = MemoryBuffer::getFile(IncludedFile.c_str());
64 }
65
66 if (!NewBufOrErr)
6567 return 0;
6668
67 return AddNewSourceBuffer(NewBuf.release(), IncludeLoc);
69 return AddNewSourceBuffer(NewBufOrErr.get().release(), IncludeLoc);
6870 }
6971
7072 unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
8080 RecordKeeper Records;
8181
8282 // Parse the input file.
83 std::unique_ptr File;
84 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
85 errs() << "Could not open input file '" << InputFilename << "': "
86 << ec.message() <<"\n";
83 ErrorOr> FileOrErr =
84 MemoryBuffer::getFileOrSTDIN(InputFilename);
85 if (std::error_code EC = FileOrErr.getError()) {
86 errs() << "Could not open input file '" << InputFilename
87 << "': " << EC.message() << "\n";
8788 return 1;
8889 }
89 MemoryBuffer *F = File.release();
90 MemoryBuffer *F = FileOrErr.get().release();
9091
9192 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
9293 SrcMgr.AddNewSourceBuffer(F, SMLoc());
449449 ///
450450 /// \returns true if the file was loaded successfully, false otherwise.
451451 bool SampleModuleProfile::loadText() {
452 std::unique_ptr Buffer;
453 std::error_code EC = MemoryBuffer::getFile(Filename, Buffer);
454 if (EC) {
452 ErrorOr> BufferOrErr =
453 MemoryBuffer::getFile(Filename);
454 if (std::error_code EC = BufferOrErr.getError()) {
455455 std::string Msg(EC.message());
456456 M.getContext().diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
457457 return false;
458458 }
459 std::unique_ptr Buffer = std::move(BufferOrErr.get());
459460 line_iterator LineIt(*Buffer, '#');
460461
461462 // Read the profile of each function. Since each function may be
5353 const StringRef Path, std::string &Error) {
5454 if (Path.empty())
5555 return new SpecialCaseList();
56 std::unique_ptr File;
57 if (std::error_code EC = MemoryBuffer::getFile(Path, File)) {
56 ErrorOr> FileOrErr =
57 MemoryBuffer::getFile(Path);
58 if (std::error_code EC = FileOrErr.getError()) {
5859 Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str();
5960 return nullptr;
6061 }
61 return create(File.get(), Error);
62 return create(FileOrErr.get().get(), Error);
6263 }
6364
6465 SpecialCaseList *SpecialCaseList::create(
279279 if (file->offset) {
280280 offset = file->offset;
281281 }
282 if (std::error_code ec = MemoryBuffer::getOpenFileSlice(
283 file->fd, file->name, buffer, file->filesize, offset)) {
284 (*message)(LDPL_ERROR, ec.message().c_str());
282 ErrorOr> BufferOrErr =
283 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
284 offset);
285 if (std::error_code EC = BufferOrErr.getError()) {
286 (*message)(LDPL_ERROR, EC.message().c_str());
285287 return LDPS_ERR;
286288 }
289 buffer = std::move(BufferOrErr.get());
287290 view = buffer->getBufferStart();
288291 }
289292
284284 if (!getCacheFilename(ModuleID, CacheName))
285285 return nullptr;
286286 // Load the object from the cache filename
287 std::unique_ptr IRObjectBuffer;
288 MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false);
287 ErrorOr> IRObjectBuffer =
288 MemoryBuffer::getFile(CacheName.c_str(), -1, false);
289289 // If the file isn't there, that's OK.
290290 if (!IRObjectBuffer)
291291 return nullptr;
293293 // because the file has probably just been mmapped. Instead we make
294294 // a copy. The filed-based buffer will be released when it goes
295295 // out of scope.
296 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
296 return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
297297 }
298298
299299 private:
537537 }
538538
539539 for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
540 std::unique_ptr ArBuf;
541 std::error_code ec;
542 ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf);
543 if (ec) {
540 ErrorOr> ArBuf =
541 MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
542 if (!ArBuf) {
544543 Err.print(argv[0], errs());
545544 return 1;
546545 }
547 object::Archive *Ar = new object::Archive(std::move(ArBuf), ec);
548 if (ec || !Ar) {
546 std::error_code EC;
547 object::Archive *Ar = new object::Archive(std::move(ArBuf.get()), EC);
548 if (EC || !Ar) {
549549 Err.print(argv[0], errs());
550550 return 1;
551551 }
769769 const char *Filename = Member.getNew();
770770 int FD = Member.getFD();
771771 const sys::fs::file_status &Status = Member.getStatus();
772 failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer,
773 Status.getSize(), false),
774 Filename);
775
772 ErrorOr> MemberBufferOrErr =
773 MemoryBuffer::getOpenFile(FD, Filename, Status.getSize(), false);
774 failIfError(MemberBufferOrErr.getError(), Filename);
775 MemberBuffer = std::move(MemberBufferOrErr.get());
776776 } else {
777777 object::Archive::child_iterator OldMember = Member.getOld();
778778 ErrorOr> MemberBufferOrErr =
933933
934934 static int performOperation(ArchiveOperation Operation) {
935935 // Create or open the archive object.
936 std::unique_ptr Buf;
937 std::error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
936 ErrorOr> Buf =
937 MemoryBuffer::getFile(ArchiveName, -1, false);
938 std::error_code EC = Buf.getError();
938939 if (EC && EC != errc::no_such_file_or_directory) {
939940 errs() << ToolName << ": error opening '" << ArchiveName
940941 << "': " << EC.message() << "!\n";
942943 }
943944
944945 if (!EC) {
945 object::Archive Archive(std::move(Buf), EC);
946 object::Archive Archive(std::move(Buf.get()), EC);
946947
947948 if (EC) {
948949 errs() << ToolName << ": error loading '" << ArchiveName
477477 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
478478 static int AnalyzeBitcode() {
479479 // Read the input file.
480 std::unique_ptr MemBuf;
481
482 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, MemBuf))
483 return Error("Error reading '" + InputFilename + "': " + ec.message());
480 ErrorOr> MemBufOrErr =
481 MemoryBuffer::getFileOrSTDIN(InputFilename);
482 if (std::error_code EC = MemBufOrErr.getError())
483 return Error("Error reading '" + InputFilename + "': " + EC.message());
484 std::unique_ptr MemBuf = std::move(MemBufOrErr.get());
484485
485486 if (MemBuf->getBufferSize() & 3)
486487 return Error("Bitcode stream should be a multiple of 4 bytes in length");
9696 : InputGCDA;
9797 GCOVFile GF;
9898
99 std::unique_ptr GCNO_Buff;
100 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(GCNO, GCNO_Buff)) {
101 errs() << GCNO << ": " << ec.message() << "\n";
99 ErrorOr> GCNO_Buff =
100 MemoryBuffer::getFileOrSTDIN(GCNO);
101 if (std::error_code EC = GCNO_Buff.getError()) {
102 errs() << GCNO << ": " << EC.message() << "\n";
102103 return;
103104 }
104 GCOVBuffer GCNO_GB(GCNO_Buff.get());
105 GCOVBuffer GCNO_GB(GCNO_Buff.get().get());
105106 if (!GF.readGCNO(GCNO_GB)) {
106107 errs() << "Invalid .gcno File!\n";
107108 return;
108109 }
109110
110 std::unique_ptr GCDA_Buff;
111 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(GCDA, GCDA_Buff)) {
112 if (ec != errc::no_such_file_or_directory) {
113 errs() << GCDA << ": " << ec.message() << "\n";
111 ErrorOr> GCDA_Buff =
112 MemoryBuffer::getFileOrSTDIN(GCDA);
113 if (std::error_code EC = GCDA_Buff.getError()) {
114 if (EC != errc::no_such_file_or_directory) {
115 errs() << GCDA << ": " << EC.message() << "\n";
114116 return;
115117 }
116118 // Clear the filename to make it clear we didn't read anything.
117119 GCDA = "-";
118120 } else {
119 GCOVBuffer GCDA_GB(GCDA_Buff.get());
121 GCOVBuffer GCDA_GB(GCDA_Buff.get().get());
120122 if (!GF.readGCDA(GCDA_GB)) {
121123 errs() << "Invalid .gcda File!\n";
122124 return;
6565 clEnumValEnd));
6666
6767 static void DumpInput(const StringRef &Filename) {
68 std::unique_ptr Buff;
68 ErrorOr> Buff =
69 MemoryBuffer::getFileOrSTDIN(Filename);
6970
70 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
71 errs() << Filename << ": " << ec.message() << "\n";
71 if (std::error_code EC = Buff.getError()) {
72 errs() << Filename << ": " << EC.message() << "\n";
7273 return;
7374 }
7475
75 ErrorOr ObjOrErr(ObjectFile::createObjectFile(Buff));
76 ErrorOr ObjOrErr(ObjectFile::createObjectFile(Buff.get()));
7677 if (std::error_code EC = ObjOrErr.getError()) {
7778 errs() << Filename << ": " << EC.message() << '\n';
7879 return;
366366 if (!TheTarget)
367367 return 1;
368368
369 std::unique_ptr BufferPtr;
370 if (std::error_code ec =
371 MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
372 errs() << ProgName << ": " << ec.message() << '\n';
369 ErrorOr> BufferPtr =
370 MemoryBuffer::getFileOrSTDIN(InputFilename);
371 if (std::error_code EC = BufferPtr.getError()) {
372 errs() << ProgName << ": " << EC.message() << '\n';
373373 return 1;
374374 }
375 MemoryBuffer *Buffer = BufferPtr.release();
375 MemoryBuffer *Buffer = BufferPtr->release();
376376
377377 SourceMgr SrcMgr;
378378
134134 }
135135
136136 static void parseMCMarkup(StringRef Filename) {
137 std::unique_ptr BufferPtr;
138 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, BufferPtr)) {
139 errs() << ToolName << ": " << ec.message() << '\n';
140 return;
141 }
142 MemoryBuffer *Buffer = BufferPtr.release();
137 ErrorOr> BufferPtr =
138 MemoryBuffer::getFileOrSTDIN(Filename);
139 if (std::error_code EC = BufferPtr.getError()) {
140 errs() << ToolName << ": " << EC.message() << '\n';
141 return;
142 }
143 MemoryBuffer *Buffer = BufferPtr->release();
143144
144145 SourceMgr SrcMgr;
145146
804804 }
805805
806806 static void dumpSymbolNamesFromFile(std::string &Filename) {
807 std::unique_ptr Buffer;
808 if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
807 ErrorOr> BufferOrErr =
808 MemoryBuffer::getFileOrSTDIN(Filename);
809 if (error(BufferOrErr.getError(), Filename))
809810 return;
811 std::unique_ptr Buffer = std::move(BufferOrErr.get());
810812
811813 LLVMContext &Context = getGlobalContext();
812814 ErrorOr BinaryOrErr = createBinary(Buffer, &Context);
194194 MachOObjectFile *MachOOF);
195195
196196 void llvm::DisassembleInputMachO(StringRef Filename) {
197 std::unique_ptr Buff;
198
199 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
200 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n";
197 ErrorOr> Buff =
198 MemoryBuffer::getFileOrSTDIN(Filename);
199 if (std::error_code EC = Buff.getError()) {
200 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
201201 return;
202202 }
203203
204204 std::unique_ptr MachOOF(static_cast(
205 ObjectFile::createMachOObjectFile(Buff).get()));
205 ObjectFile::createMachOObjectFile(Buff.get()).get()));
206206
207207 DisassembleInputMachO2(Filename, MachOOF.get());
208208 }
287287 // A separate DSym file path was specified, parse it as a macho file,
288288 // get the sections and supply it to the section name parsing machinery.
289289 if (!DSYMFile.empty()) {
290 std::unique_ptr Buf;
291 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile, Buf)) {
292 errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n';
290 ErrorOr> Buf =
291 MemoryBuffer::getFileOrSTDIN(DSYMFile);
292 if (std::error_code EC = Buf.getError()) {
293 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
293294 return;
294295 }
295 DbgObj = ObjectFile::createMachOObjectFile(Buf).get();
296 DbgObj = ObjectFile::createMachOObjectFile(Buf.get()).get();
296297 }
297298
298299 // Setup the DIContext
174174 RuntimeDyld Dyld(&MemMgr);
175175
176176 // Load the input memory buffer.
177 std::unique_ptr InputBuffer;
177
178 ErrorOr> InputBuffer =
179 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
180 if (std::error_code EC = InputBuffer.getError())
181 return Error("unable to read input: '" + EC.message() + "'");
182
178183 std::unique_ptr LoadedObject;
179 if (std::error_code ec =
180 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
181 return Error("unable to read input: '" + ec.message() + "'");
182
183184 // Load the object file
184 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
185 LoadedObject.reset(
186 Dyld.loadObject(new ObjectBuffer(InputBuffer.get().release())));
185187 if (!LoadedObject) {
186188 return Error(Dyld.getErrorString());
187189 }
235237 InputFileList.push_back("-");
236238 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
237239 // Load the input memory buffer.
238 std::unique_ptr InputBuffer;
240 ErrorOr> InputBuffer =
241 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
242 if (std::error_code EC = InputBuffer.getError())
243 return Error("unable to read input: '" + EC.message() + "'");
239244 std::unique_ptr LoadedObject;
240 if (std::error_code ec =
241 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
242 return Error("unable to read input: '" + ec.message() + "'");
243
244245 // Load the object file
245 LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
246 LoadedObject.reset(
247 Dyld.loadObject(new ObjectBuffer(InputBuffer.get().release())));
246248 if (!LoadedObject) {
247249 return Error(Dyld.getErrorString());
248250 }
284286
285287 static int checkAllExpressions(RuntimeDyldChecker &Checker) {
286288 for (const auto& CheckerFileName : CheckFiles) {
287 std::unique_ptr CheckerFileBuf;
288 if (std::error_code EC =
289 MemoryBuffer::getFileOrSTDIN(CheckerFileName, CheckerFileBuf))
289 ErrorOr> CheckerFileBuf =
290 MemoryBuffer::getFileOrSTDIN(CheckerFileName);
291 if (std::error_code EC = CheckerFileBuf.getError())
290292 return Error("unable to read input '" + CheckerFileName + "': " +
291293 EC.message());
292294
293 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:", CheckerFileBuf.get()))
295 if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
296 CheckerFileBuf.get().get()))
294297 return Error("some checks in '" + CheckerFileName + "' failed");
295298 }
296299 return 0;
349352 InputFileList.push_back("-");
350353 for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
351354 // Load the input memory buffer.
352 std::unique_ptr InputBuffer;
355 ErrorOr> InputBuffer =
356 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
357 if (std::error_code EC = InputBuffer.getError())
358 return Error("unable to read input: '" + EC.message() + "'");
359
353360 std::unique_ptr LoadedObject;
354 if (std::error_code ec =
355 MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
356 return Error("unable to read input: '" + ec.message() + "'");
357
358361 // Load the object file
359362 LoadedObject.reset(
360 Dyld.loadObject(new ObjectBuffer(InputBuffer.release())));
363 Dyld.loadObject(new ObjectBuffer(InputBuffer.get().release())));
361364 if (!LoadedObject) {
362365 return Error(Dyld.getErrorString());
363366 }
219219 }
220220
221221 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
222 std::unique_ptr MB;
223 if (MemoryBuffer::getFileOrSTDIN(Path, MB))
224 return false;
225 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
222 ErrorOr> MB =
223 MemoryBuffer::getFileOrSTDIN(Path);
224 if (!MB)
225 return false;
226 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
226227 }
227228
228229 static bool findDebugBinary(const std::string &OrigPath,
8787
8888 bool lto_module_is_object_file_for_target(const char* path,
8989 const char* target_triplet_prefix) {
90 std::unique_ptr buffer;
91 if (MemoryBuffer::getFile(path, buffer))
90 ErrorOr> Buffer = MemoryBuffer::getFile(path);
91 if (!Buffer)
9292 return false;
93 return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix);
93 return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix);
9494 }
9595
9696 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {
9090 return 1;
9191 }
9292
93 std::unique_ptr Buf;
94 if (MemoryBuffer::getFileOrSTDIN(Input, Buf))
93 ErrorOr> Buf =
94 MemoryBuffer::getFileOrSTDIN(Input);
95 if (!Buf)
9596 return 1;
9697
9798 ConvertFuncPtr Convert = nullptr;
104105 return 1;
105106 }
106107
107 yaml::Input YIn(Buf->getBuffer());
108 yaml::Input YIn(Buf.get()->getBuffer());
108109
109110 int Res = convertYAML(YIn, Out->os(), Convert);
110111 if (Res == 0)
7676 }
7777 OF.close();
7878
79 OwningBuffer MB;
80 std::error_code EC = MemoryBuffer::getFile(TestPath.c_str(), MB);
79 ErrorOr MB = MemoryBuffer::getFile(TestPath.c_str());
80 std::error_code EC = MB.getError();
8181 ASSERT_FALSE(EC);
8282
83 const char *BufData = MB->getBufferStart();
83 const char *BufData = MB.get()->getBufferStart();
8484 EXPECT_EQ('f', BufData[4095]);
8585 EXPECT_EQ('\0', BufData[4096]);
8686 }
145145 EXPECT_FALSE(sys::fs::openFileForRead(TestPath.c_str(), TestFD));
146146 }
147147
148 OwningBuffer Buf;
149 std::error_code EC =
150 MemoryBuffer::getOpenFileSlice(TestFD, TestPath.c_str(), Buf,
148 ErrorOr Buf =
149 MemoryBuffer::getOpenFileSlice(TestFD, TestPath.c_str(),
151150 40000, // Size
152151 80000 // Offset
153152 );
153
154 std::error_code EC = Buf.getError();
154155 EXPECT_FALSE(EC);
155156
156 StringRef BufData = Buf->getBuffer();
157 StringRef BufData = Buf.get()->getBuffer();
157158 EXPECT_EQ(BufData.size(), 40000U);
158159 EXPECT_EQ(BufData[0], '0');
159160 EXPECT_EQ(BufData[9], '9');
819819 /// Returns true in case of an error, false otherwise.
820820 static bool ReadCheckFile(SourceMgr &SM,
821821 std::vector &CheckStrings) {
822 std::unique_ptr File;
823 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) {
824 errs() << "Could not open check file '" << CheckFilename << "': "
825 << ec.message() << '\n';
822 ErrorOr> FileOrErr =
823 MemoryBuffer::getFileOrSTDIN(CheckFilename);
824 if (std::error_code EC = FileOrErr.getError()) {
825 errs() << "Could not open check file '" << CheckFilename
826 << "': " << EC.message() << '\n';
826827 return true;
827828 }
828829
829830 // If we want to canonicalize whitespace, strip excess whitespace from the
830831 // buffer containing the CHECK lines. Remove DOS style line endings.
831 MemoryBuffer *F =
832 CanonicalizeInputFile(File.release(), NoCanonicalizeWhiteSpace);
832 MemoryBuffer *F = CanonicalizeInputFile(FileOrErr.get().release(),
833 NoCanonicalizeWhiteSpace);
833834
834835 SM.AddNewSourceBuffer(F, SMLoc());
835836
12221223 return 2;
12231224
12241225 // Open the file to check and add it to SourceMgr.
1225 std::unique_ptr File;
1226 if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, File)) {
1227 errs() << "Could not open input file '" << InputFilename << "': "
1228 << ec.message() << '\n';
1226 ErrorOr> FileOrErr =
1227 MemoryBuffer::getFileOrSTDIN(InputFilename);
1228 if (std::error_code EC = FileOrErr.getError()) {
1229 errs() << "Could not open input file '" << InputFilename
1230 << "': " << EC.message() << '\n';
12291231 return 2;
12301232 }
1233 std::unique_ptr File = std::move(FileOrErr.get());
12311234
12321235 if (File->getBufferSize() == 0) {
12331236 errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
187187 int main(int argc, char **argv) {
188188 llvm::cl::ParseCommandLineOptions(argc, argv);
189189 if (Input.getNumOccurrences()) {
190 std::unique_ptr Buf;
191 if (MemoryBuffer::getFileOrSTDIN(Input, Buf))
190 ErrorOr> BufOrErr =
191 MemoryBuffer::getFileOrSTDIN(Input);
192 if (!BufOrErr)
192193 return 1;
194 std::unique_ptr Buf = std::move(BufOrErr.get());
193195
194196 llvm::SourceMgr sm;
195197 if (DumpTokens) {