Update the MemoryBuffer API to use ErrorOr.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@212405 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Rafael Espindola 2014-07-06 17:43:13 +00:00
parent 04e43e64a9
commit 7cba2a973f
35 changed files with 296 additions and 279 deletions

View File

@ -19,6 +19,7 @@
#include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/CBindingWrapping.h"
#include "llvm/Support/Compiler.h" #include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h" #include "llvm/Support/DataTypes.h"
#include "llvm/Support/ErrorOr.h"
#include <memory> #include <memory>
#include <system_error> #include <system_error>
@ -60,19 +61,17 @@ public:
return "Unknown buffer"; return "Unknown buffer";
} }
/// getFile - Open the specified file as a MemoryBuffer, returning a new /// Open the specified file as a MemoryBuffer, returning a new MemoryBuffer
/// MemoryBuffer if successful, otherwise returning null. If FileSize is /// if successful, otherwise returning null. If FileSize is specified, this
/// specified, this means that the client knows that the file exists and that /// means that the client knows that the file exists and that it has the
/// it has the specified size. /// specified size.
/// ///
/// \param IsVolatileSize Set to true to indicate that the file size may be /// \param IsVolatileSize Set to true to indicate that the file size may be
/// changing, e.g. when libclang tries to parse while the user is /// changing, e.g. when libclang tries to parse while the user is
/// editing/updating the file. /// editing/updating the file.
static std::error_code getFile(Twine Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getFile(Twine Filename, int64_t FileSize = -1,
int64_t FileSize = -1, bool RequiresNullTerminator = true, bool IsVolatileSize = false);
bool RequiresNullTerminator = true,
bool IsVolatileSize = false);
/// Given an already-open file descriptor, map some slice of it into a /// Given an already-open file descriptor, map some slice of it into a
/// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize. /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize.
@ -81,10 +80,9 @@ public:
/// \param IsVolatileSize Set to true to indicate that the file size may be /// \param IsVolatileSize Set to true to indicate that the file size may be
/// changing, e.g. when libclang tries to parse while the user is /// changing, e.g. when libclang tries to parse while the user is
/// editing/updating the file. /// editing/updating the file.
static std::error_code getOpenFileSlice(int FD, const char *Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize,
uint64_t MapSize, int64_t Offset, int64_t Offset, bool IsVolatileSize = false);
bool IsVolatileSize = false);
/// Given an already-open file descriptor, read the file and return a /// Given an already-open file descriptor, read the file and return a
/// MemoryBuffer. /// MemoryBuffer.
@ -92,11 +90,9 @@ public:
/// \param IsVolatileSize Set to true to indicate that the file size may be /// \param IsVolatileSize Set to true to indicate that the file size may be
/// changing, e.g. when libclang tries to parse while the user is /// changing, e.g. when libclang tries to parse while the user is
/// editing/updating the file. /// editing/updating the file.
static std::error_code getOpenFile(int FD, const char *Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getOpenFile(int FD, const char *Filename, uint64_t FileSize,
uint64_t FileSize, bool RequiresNullTerminator = true, bool IsVolatileSize = false);
bool RequiresNullTerminator = true,
bool IsVolatileSize = false);
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that InputData must be null terminated if RequiresNullTerminator is true. /// that InputData must be null terminated if RequiresNullTerminator is true.
@ -123,16 +119,13 @@ public:
static MemoryBuffer *getNewUninitMemBuffer(size_t Size, static MemoryBuffer *getNewUninitMemBuffer(size_t Size,
StringRef BufferName = ""); StringRef BufferName = "");
/// getSTDIN - Read all of stdin into a file buffer, and return it. /// Read all of stdin into a file buffer, and return it.
/// If an error occurs, this returns null and sets ec. static ErrorOr<std::unique_ptr<MemoryBuffer>> getSTDIN();
static std::error_code getSTDIN(std::unique_ptr<MemoryBuffer> &Result);
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin /// Open the specified file as a MemoryBuffer, or open stdin if the Filename
/// if the Filename is "-". If an error occurs, this returns null and sets /// is "-".
/// ec. static ErrorOr<std::unique_ptr<MemoryBuffer>>
static std::error_code getFileOrSTDIN(StringRef Filename, getFileOrSTDIN(StringRef Filename, int64_t FileSize = -1);
std::unique_ptr<MemoryBuffer> &Result,
int64_t FileSize = -1);
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
// Provided for performance analysis. // Provided for performance analysis.

View File

@ -41,14 +41,15 @@ Module *llvm::ParseAssembly(MemoryBuffer *F,
Module *llvm::ParseAssemblyFile(const std::string &Filename, SMDiagnostic &Err, Module *llvm::ParseAssemblyFile(const std::string &Filename, SMDiagnostic &Err,
LLVMContext &Context) { LLVMContext &Context) {
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, File)) { MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = FileOrErr.getError()) {
Err = SMDiagnostic(Filename, SourceMgr::DK_Error, Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
"Could not open input file: " + ec.message()); "Could not open input file: " + EC.message());
return nullptr; return nullptr;
} }
return ParseAssembly(File.release(), nullptr, Err, Context); return ParseAssembly(FileOrErr.get().release(), nullptr, Err, Context);
} }
Module *llvm::ParseAssemblyString(const char *AsmString, Module *M, Module *llvm::ParseAssemblyString(const char *AsmString, Module *M,

View File

@ -2606,29 +2606,25 @@ LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(
LLVMMemoryBufferRef *OutMemBuf, LLVMMemoryBufferRef *OutMemBuf,
char **OutMessage) { char **OutMessage) {
std::unique_ptr<MemoryBuffer> MB; ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);
std::error_code ec; if (std::error_code EC = MBOrErr.getError()) {
if (!(ec = MemoryBuffer::getFile(Path, MB))) { *OutMessage = strdup(EC.message().c_str());
*OutMemBuf = wrap(MB.release());
return 0;
}
*OutMessage = strdup(ec.message().c_str());
return 1; return 1;
} }
*OutMemBuf = wrap(MBOrErr.get().release());
return 0;
}
LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf, LLVMBool LLVMCreateMemoryBufferWithSTDIN(LLVMMemoryBufferRef *OutMemBuf,
char **OutMessage) { char **OutMessage) {
std::unique_ptr<MemoryBuffer> MB; ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getSTDIN();
std::error_code ec; if (std::error_code EC = MBOrErr.getError()) {
if (!(ec = MemoryBuffer::getSTDIN(MB))) { *OutMessage = strdup(EC.message().c_str());
*OutMemBuf = wrap(MB.release());
return 0;
}
*OutMessage = strdup(ec.message().c_str());
return 1; return 1;
} }
*OutMemBuf = wrap(MBOrErr.get().release());
return 0;
}
LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange( LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRange(
const char *InputData, const char *InputData,

View File

@ -438,12 +438,16 @@ class LineConsumer {
StringRef Remaining; StringRef Remaining;
public: public:
LineConsumer(StringRef Filename) { LineConsumer(StringRef Filename) {
if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Filename, Buffer)) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = BufferOrErr.getError()) {
errs() << Filename << ": " << EC.message() << "\n"; errs() << Filename << ": " << EC.message() << "\n";
Remaining = ""; Remaining = "";
} else } else {
Buffer = std::move(BufferOrErr.get());
Remaining = Buffer->getBuffer(); Remaining = Buffer->getBuffer();
} }
}
bool empty() { return Remaining.empty(); } bool empty() { return Remaining.empty(); }
void printNext(raw_ostream &OS, uint32_t LineNum) { void printNext(raw_ostream &OS, uint32_t LineNum) {
StringRef Line; StringRef Line;

View File

@ -51,14 +51,15 @@ static Module *getLazyIRModule(MemoryBuffer *Buffer, SMDiagnostic &Err,
Module *llvm::getLazyIRFileModule(const std::string &Filename, SMDiagnostic &Err, Module *llvm::getLazyIRFileModule(const std::string &Filename, SMDiagnostic &Err,
LLVMContext &Context) { LLVMContext &Context) {
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, File)) { MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = FileOrErr.getError()) {
Err = SMDiagnostic(Filename, SourceMgr::DK_Error, Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
"Could not open input file: " + ec.message()); "Could not open input file: " + EC.message());
return nullptr; return nullptr;
} }
return getLazyIRModule(File.release(), Err, Context); return getLazyIRModule(FileOrErr.get().release(), Err, Context);
} }
Module *llvm::ParseIR(MemoryBuffer *Buffer, SMDiagnostic &Err, Module *llvm::ParseIR(MemoryBuffer *Buffer, SMDiagnostic &Err,
@ -85,14 +86,15 @@ Module *llvm::ParseIR(MemoryBuffer *Buffer, SMDiagnostic &Err,
Module *llvm::ParseIRFile(const std::string &Filename, SMDiagnostic &Err, Module *llvm::ParseIRFile(const std::string &Filename, SMDiagnostic &Err,
LLVMContext &Context) { LLVMContext &Context) {
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, File)) { MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = FileOrErr.getError()) {
Err = SMDiagnostic(Filename, SourceMgr::DK_Error, Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
"Could not open input file: " + ec.message()); "Could not open input file: " + EC.message());
return nullptr; return nullptr;
} }
return ParseIR(File.get(), Err, Context); return ParseIR(FileOrErr.get().get(), Err, Context);
} }
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//

View File

@ -236,13 +236,14 @@ const void* LTOCodeGenerator::compile(size_t* length,
delete NativeObjectFile; delete NativeObjectFile;
// read .o file into memory buffer // read .o file into memory buffer
std::unique_ptr<MemoryBuffer> BuffPtr; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
if (std::error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) { MemoryBuffer::getFile(name, -1, false);
errMsg = ec.message(); if (std::error_code EC = BufferOrErr.getError()) {
errMsg = EC.message();
sys::fs::remove(NativeObjectPath); sys::fs::remove(NativeObjectPath);
return nullptr; return nullptr;
} }
NativeObjectFile = BuffPtr.release(); NativeObjectFile = BufferOrErr.get().release();
// remove temp files // remove temp files
sys::fs::remove(NativeObjectPath); sys::fs::remove(NativeObjectPath);

View File

@ -69,12 +69,13 @@ bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer,
LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options, LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
std::string &errMsg) { std::string &errMsg) {
std::unique_ptr<MemoryBuffer> buffer; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) { MemoryBuffer::getFile(path);
errMsg = ec.message(); if (std::error_code EC = BufferOrErr.getError()) {
errMsg = EC.message();
return nullptr; return nullptr;
} }
return makeLTOModule(std::move(buffer), options, errMsg); return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
} }
LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size, LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
@ -87,13 +88,13 @@ LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
size_t map_size, off_t offset, size_t map_size, off_t offset,
TargetOptions options, TargetOptions options,
std::string &errMsg) { std::string &errMsg) {
std::unique_ptr<MemoryBuffer> buffer; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
if (std::error_code ec = MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) { if (std::error_code EC = BufferOrErr.getError()) {
errMsg = ec.message(); errMsg = EC.message();
return nullptr; return nullptr;
} }
return makeLTOModule(std::move(buffer), options, errMsg); return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg);
} }
LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length, LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,

View File

@ -75,8 +75,9 @@ ErrorOr<Binary *> object::createBinary(std::unique_ptr<MemoryBuffer> &Buffer,
} }
ErrorOr<Binary *> object::createBinary(StringRef Path) { ErrorOr<Binary *> object::createBinary(StringRef Path) {
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Path, File)) MemoryBuffer::getFileOrSTDIN(Path);
if (std::error_code EC = FileOrErr.getError())
return EC; return EC;
return createBinary(File); return createBinary(FileOrErr.get());
} }

View File

@ -83,8 +83,9 @@ ObjectFile::createObjectFile(std::unique_ptr<MemoryBuffer> &Object,
} }
ErrorOr<ObjectFile *> ObjectFile::createObjectFile(StringRef ObjectPath) { ErrorOr<ObjectFile *> ObjectFile::createObjectFile(StringRef ObjectPath) {
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code EC = MemoryBuffer::getFile(ObjectPath, File)) MemoryBuffer::getFile(ObjectPath);
if (std::error_code EC = FileOrErr.getError())
return EC; return EC;
return createObjectFile(File); return createObjectFile(FileOrErr.get());
} }

View File

@ -23,8 +23,11 @@ using namespace llvm;
static std::error_code static std::error_code
setupMemoryBuffer(std::string Path, std::unique_ptr<MemoryBuffer> &Buffer) { setupMemoryBuffer(std::string Path, std::unique_ptr<MemoryBuffer> &Buffer) {
if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(Path, Buffer)) ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
MemoryBuffer::getFileOrSTDIN(Path);
if (std::error_code EC = BufferOrErr.getError())
return EC; return EC;
Buffer = std::move(BufferOrErr.get());
// Sanity check the file. // Sanity check the file.
if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max()) if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())

View File

@ -631,9 +631,11 @@ void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
static bool ExpandResponseFile(const char *FName, StringSaver &Saver, static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
TokenizerCallback Tokenizer, TokenizerCallback Tokenizer,
SmallVectorImpl<const char *> &NewArgv) { SmallVectorImpl<const char *> &NewArgv) {
std::unique_ptr<MemoryBuffer> MemBuf; ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
if (MemoryBuffer::getFile(FName, MemBuf)) MemoryBuffer::getFile(FName);
if (!MemBufOrErr)
return false; return false;
std::unique_ptr<MemoryBuffer> MemBuf = std::move(MemBufOrErr.get());
StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize()); StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
// If we have a UTF-16 byte order mark, convert to UTF-8 for parsing. // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.

View File

@ -176,18 +176,21 @@ int llvm::DiffFilesWithTolerance(StringRef NameA,
std::string *Error) { std::string *Error) {
// Now its safe to mmap the files into memory because both files // Now its safe to mmap the files into memory because both files
// have a non-zero size. // have a non-zero size.
std::unique_ptr<MemoryBuffer> F1; ErrorOr<std::unique_ptr<MemoryBuffer>> F1OrErr = MemoryBuffer::getFile(NameA);
if (std::error_code ec = MemoryBuffer::getFile(NameA, F1)) { if (std::error_code EC = F1OrErr.getError()) {
if (Error) if (Error)
*Error = ec.message(); *Error = EC.message();
return 2; return 2;
} }
std::unique_ptr<MemoryBuffer> F2; std::unique_ptr<MemoryBuffer> F1 = std::move(F1OrErr.get());
if (std::error_code ec = MemoryBuffer::getFile(NameB, F2)) {
ErrorOr<std::unique_ptr<MemoryBuffer>> F2OrErr = MemoryBuffer::getFile(NameB);
if (std::error_code EC = F2OrErr.getError()) {
if (Error) if (Error)
*Error = ec.message(); *Error = EC.message();
return 2; return 2;
} }
std::unique_ptr<MemoryBuffer> F2 = std::move(F2OrErr.get());
// Okay, now that we opened the files, scan them for the first difference. // Okay, now that we opened the files, scan them for the first difference.
const char *File1Start = F1->getBufferStart(); const char *File1Start = F1->getBufferStart();

View File

@ -33,11 +33,13 @@ Optional<std::pair<std::string, int> >
LockFileManager::readLockFile(StringRef LockFileName) { LockFileManager::readLockFile(StringRef LockFileName) {
// Read the owning host and PID out of the lock file. If it appears that the // Read the owning host and PID out of the lock file. If it appears that the
// owning process is dead, the lock file is invalid. // owning process is dead, the lock file is invalid.
std::unique_ptr<MemoryBuffer> MB; ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
if (MemoryBuffer::getFile(LockFileName, MB)) { MemoryBuffer::getFile(LockFileName);
if (!MBOrErr) {
sys::fs::remove(LockFileName); sys::fs::remove(LockFileName);
return None; return None;
} }
std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
StringRef Hostname; StringRef Hostname;
StringRef PIDStr; StringRef PIDStr;

View File

@ -152,18 +152,11 @@ MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
return SB; return SB;
} }
ErrorOr<std::unique_ptr<MemoryBuffer>>
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin MemoryBuffer::getFileOrSTDIN(StringRef Filename, int64_t FileSize) {
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
std::error_code
MemoryBuffer::getFileOrSTDIN(StringRef Filename,
std::unique_ptr<MemoryBuffer> &Result,
int64_t FileSize) {
if (Filename == "-") if (Filename == "-")
return getSTDIN(Result); return getSTDIN();
return getFile(Filename, Result, FileSize); return getFile(Filename, FileSize);
} }
@ -212,9 +205,8 @@ public:
}; };
} }
static std::error_code static ErrorOr<std::unique_ptr<MemoryBuffer>>
getMemoryBufferForStream(int FD, StringRef BufferName, getMemoryBufferForStream(int FD, StringRef BufferName) {
std::unique_ptr<MemoryBuffer> &Result) {
const ssize_t ChunkSize = 4096*4; const ssize_t ChunkSize = 4096*4;
SmallString<ChunkSize> Buffer; SmallString<ChunkSize> Buffer;
ssize_t ReadBytes; ssize_t ReadBytes;
@ -229,48 +221,43 @@ getMemoryBufferForStream(int FD, StringRef BufferName,
Buffer.set_size(Buffer.size() + ReadBytes); Buffer.set_size(Buffer.size() + ReadBytes);
} while (ReadBytes != 0); } while (ReadBytes != 0);
Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName)); std::unique_ptr<MemoryBuffer> Ret(
return std::error_code(); MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
return std::move(Ret);
} }
static std::error_code getFileAux(const char *Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator,
int64_t FileSize, bool RequiresNullTerminator,
bool IsVolatileSize); bool IsVolatileSize);
std::error_code MemoryBuffer::getFile(Twine Filename, ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, MemoryBuffer::getFile(Twine Filename, int64_t FileSize,
int64_t FileSize, bool RequiresNullTerminator, bool IsVolatileSize) {
bool RequiresNullTerminator,
bool IsVolatileSize) {
// Ensure the path is null terminated. // Ensure the path is null terminated.
SmallString<256> PathBuf; SmallString<256> PathBuf;
StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf); StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
return getFileAux(NullTerminatedName.data(), Result, FileSize, return getFileAux(NullTerminatedName.data(), FileSize, RequiresNullTerminator,
RequiresNullTerminator, IsVolatileSize); IsVolatileSize);
} }
static std::error_code getOpenFileImpl(int FD, const char *Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize,
uint64_t FileSize, uint64_t MapSize, uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
int64_t Offset,
bool RequiresNullTerminator,
bool IsVolatileSize); bool IsVolatileSize);
static std::error_code getFileAux(const char *Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator,
int64_t FileSize, bool RequiresNullTerminator,
bool IsVolatileSize) { bool IsVolatileSize) {
int FD; int FD;
std::error_code EC = sys::fs::openFileForRead(Filename, FD); std::error_code EC = sys::fs::openFileForRead(Filename, FD);
if (EC) if (EC)
return EC; return EC;
std::error_code ret = ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0, getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
RequiresNullTerminator, IsVolatileSize); RequiresNullTerminator, IsVolatileSize);
close(FD); close(FD);
return ret; return Ret;
} }
static bool shouldUseMmap(int FD, static bool shouldUseMmap(int FD,
@ -321,11 +308,9 @@ static bool shouldUseMmap(int FD,
return true; return true;
} }
static std::error_code getOpenFileImpl(int FD, const char *Filename, static ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize,
uint64_t FileSize, uint64_t MapSize, uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
int64_t Offset,
bool RequiresNullTerminator,
bool IsVolatileSize) { bool IsVolatileSize) {
static int PageSize = sys::process::get_self()->page_size(); static int PageSize = sys::process::get_self()->page_size();
@ -345,7 +330,7 @@ static std::error_code getOpenFileImpl(int FD, const char *Filename,
sys::fs::file_type Type = Status.type(); sys::fs::file_type Type = Status.type();
if (Type != sys::fs::file_type::regular_file && if (Type != sys::fs::file_type::regular_file &&
Type != sys::fs::file_type::block_file) Type != sys::fs::file_type::block_file)
return getMemoryBufferForStream(FD, Filename, Result); return getMemoryBufferForStream(FD, Filename);
FileSize = Status.getSize(); FileSize = Status.getSize();
} }
@ -355,10 +340,11 @@ static std::error_code getOpenFileImpl(int FD, const char *Filename,
if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
PageSize, IsVolatileSize)) { PageSize, IsVolatileSize)) {
std::error_code EC; std::error_code EC;
Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile( std::unique_ptr<MemoryBuffer> Result(
RequiresNullTerminator, FD, MapSize, Offset, EC)); new (NamedBufferAlloc(Filename))
MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
if (!EC) if (!EC)
return std::error_code(); return std::move(Result);
} }
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
@ -397,36 +383,29 @@ static std::error_code getOpenFileImpl(int FD, const char *Filename,
BufPtr += NumRead; BufPtr += NumRead;
} }
Result.swap(SB); return std::move(SB);
return std::error_code();
} }
std::error_code MemoryBuffer::getOpenFile(int FD, const char *Filename, ErrorOr<std::unique_ptr<MemoryBuffer>>
std::unique_ptr<MemoryBuffer> &Result, MemoryBuffer::getOpenFile(int FD, const char *Filename, uint64_t FileSize,
uint64_t FileSize, bool RequiresNullTerminator, bool IsVolatileSize) {
bool RequiresNullTerminator, return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
bool IsVolatileSize) {
return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
RequiresNullTerminator, IsVolatileSize); RequiresNullTerminator, IsVolatileSize);
} }
std::error_code MemoryBuffer::getOpenFileSlice( ErrorOr<std::unique_ptr<MemoryBuffer>>
int FD, const char *Filename, std::unique_ptr<MemoryBuffer> &Result, MemoryBuffer::getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize,
uint64_t MapSize, int64_t Offset, bool IsVolatileSize) { int64_t Offset, bool IsVolatileSize) {
return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false, return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false,
IsVolatileSize); IsVolatileSize);
} }
//===----------------------------------------------------------------------===// ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
std::error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
// Read in all of the data from stdin, we cannot mmap stdin. // Read in all of the data from stdin, we cannot mmap stdin.
// //
// FIXME: That isn't necessarily true, we should try to mmap stdin and // FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails. // fallback if it fails.
sys::ChangeStdinToBinary(); sys::ChangeStdinToBinary();
return getMemoryBufferForStream(0, "<stdin>", Result); return getMemoryBufferForStream(0, "<stdin>");
} }

View File

@ -52,20 +52,22 @@ SourceMgr::~SourceMgr() {
size_t SourceMgr::AddIncludeFile(const std::string &Filename, size_t SourceMgr::AddIncludeFile(const std::string &Filename,
SMLoc IncludeLoc, SMLoc IncludeLoc,
std::string &IncludedFile) { std::string &IncludedFile) {
std::unique_ptr<MemoryBuffer> NewBuf;
IncludedFile = Filename; IncludedFile = Filename;
MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf); ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
MemoryBuffer::getFile(IncludedFile.c_str());
// If the file didn't exist directly, see if it's in an include path. // If the file didn't exist directly, see if it's in an include path.
for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBuf; ++i) { for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr;
IncludedFile = IncludeDirectories[i] + sys::path::get_separator().data() + Filename; ++i) {
MemoryBuffer::getFile(IncludedFile.c_str(), NewBuf); IncludedFile =
IncludeDirectories[i] + sys::path::get_separator().data() + Filename;
NewBufOrErr = MemoryBuffer::getFile(IncludedFile.c_str());
} }
if (!NewBuf) if (!NewBufOrErr)
return 0; return 0;
return AddNewSourceBuffer(NewBuf.release(), IncludeLoc); return AddNewSourceBuffer(NewBufOrErr.get().release(), IncludeLoc);
} }
unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const { unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {

View File

@ -81,13 +81,14 @@ int TableGenMain(char *argv0, TableGenMainFn *MainFn) {
RecordKeeper Records; RecordKeeper Records;
// Parse the input file. // Parse the input file.
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, File)) { MemoryBuffer::getFileOrSTDIN(InputFilename);
errs() << "Could not open input file '" << InputFilename << "': " if (std::error_code EC = FileOrErr.getError()) {
<< ec.message() <<"\n"; errs() << "Could not open input file '" << InputFilename
<< "': " << EC.message() << "\n";
return 1; return 1;
} }
MemoryBuffer *F = File.release(); MemoryBuffer *F = FileOrErr.get().release();
// Tell SrcMgr about this buffer, which is what TGParser will pick up. // Tell SrcMgr about this buffer, which is what TGParser will pick up.
SrcMgr.AddNewSourceBuffer(F, SMLoc()); SrcMgr.AddNewSourceBuffer(F, SMLoc());

View File

@ -450,13 +450,14 @@ void SampleModuleProfile::dump() {
/// ///
/// \returns true if the file was loaded successfully, false otherwise. /// \returns true if the file was loaded successfully, false otherwise.
bool SampleModuleProfile::loadText() { bool SampleModuleProfile::loadText() {
std::unique_ptr<MemoryBuffer> Buffer; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
std::error_code EC = MemoryBuffer::getFile(Filename, Buffer); MemoryBuffer::getFile(Filename);
if (EC) { if (std::error_code EC = BufferOrErr.getError()) {
std::string Msg(EC.message()); std::string Msg(EC.message());
M.getContext().diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg)); M.getContext().diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
return false; return false;
} }
std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
line_iterator LineIt(*Buffer, '#'); line_iterator LineIt(*Buffer, '#');
// Read the profile of each function. Since each function may be // Read the profile of each function. Since each function may be

View File

@ -54,12 +54,13 @@ SpecialCaseList *SpecialCaseList::create(
const StringRef Path, std::string &Error) { const StringRef Path, std::string &Error) {
if (Path.empty()) if (Path.empty())
return new SpecialCaseList(); return new SpecialCaseList();
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code EC = MemoryBuffer::getFile(Path, File)) { MemoryBuffer::getFile(Path);
if (std::error_code EC = FileOrErr.getError()) {
Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str(); Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str();
return nullptr; return nullptr;
} }
return create(File.get(), Error); return create(FileOrErr.get().get(), Error);
} }
SpecialCaseList *SpecialCaseList::create( SpecialCaseList *SpecialCaseList::create(

View File

@ -280,11 +280,14 @@ static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
if (file->offset) { if (file->offset) {
offset = file->offset; offset = file->offset;
} }
if (std::error_code ec = MemoryBuffer::getOpenFileSlice( ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
file->fd, file->name, buffer, file->filesize, offset)) { MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
(*message)(LDPL_ERROR, ec.message().c_str()); offset);
if (std::error_code EC = BufferOrErr.getError()) {
(*message)(LDPL_ERROR, EC.message().c_str());
return LDPS_ERR; return LDPS_ERR;
} }
buffer = std::move(BufferOrErr.get());
view = buffer->getBufferStart(); view = buffer->getBufferStart();
} }

View File

@ -285,8 +285,8 @@ public:
if (!getCacheFilename(ModuleID, CacheName)) if (!getCacheFilename(ModuleID, CacheName))
return nullptr; return nullptr;
// Load the object from the cache filename // Load the object from the cache filename
std::unique_ptr<MemoryBuffer> IRObjectBuffer; ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
MemoryBuffer::getFile(CacheName.c_str(), IRObjectBuffer, -1, false); MemoryBuffer::getFile(CacheName.c_str(), -1, false);
// If the file isn't there, that's OK. // If the file isn't there, that's OK.
if (!IRObjectBuffer) if (!IRObjectBuffer)
return nullptr; return nullptr;
@ -294,7 +294,7 @@ public:
// because the file has probably just been mmapped. Instead we make // because the file has probably just been mmapped. Instead we make
// a copy. The filed-based buffer will be released when it goes // a copy. The filed-based buffer will be released when it goes
// out of scope. // out of scope.
return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer()); return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
} }
private: private:
@ -538,15 +538,15 @@ int main(int argc, char **argv, char * const *envp) {
} }
for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) { for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
std::unique_ptr<MemoryBuffer> ArBuf; ErrorOr<std::unique_ptr<MemoryBuffer>> ArBuf =
std::error_code ec; MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
ec = MemoryBuffer::getFileOrSTDIN(ExtraArchives[i], ArBuf); if (!ArBuf) {
if (ec) {
Err.print(argv[0], errs()); Err.print(argv[0], errs());
return 1; return 1;
} }
object::Archive *Ar = new object::Archive(std::move(ArBuf), ec); std::error_code EC;
if (ec || !Ar) { object::Archive *Ar = new object::Archive(std::move(ArBuf.get()), EC);
if (EC || !Ar) {
Err.print(argv[0], errs()); Err.print(argv[0], errs());
return 1; return 1;
} }

View File

@ -770,10 +770,10 @@ static void performWriteOperation(ArchiveOperation Operation,
const char *Filename = Member.getNew(); const char *Filename = Member.getNew();
int FD = Member.getFD(); int FD = Member.getFD();
const sys::fs::file_status &Status = Member.getStatus(); const sys::fs::file_status &Status = Member.getStatus();
failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer, ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
Status.getSize(), false), MemoryBuffer::getOpenFile(FD, Filename, Status.getSize(), false);
Filename); failIfError(MemberBufferOrErr.getError(), Filename);
MemberBuffer = std::move(MemberBufferOrErr.get());
} else { } else {
object::Archive::child_iterator OldMember = Member.getOld(); object::Archive::child_iterator OldMember = Member.getOld();
ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr = ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
@ -934,8 +934,9 @@ int ar_main(char **argv) {
static int performOperation(ArchiveOperation Operation) { static int performOperation(ArchiveOperation Operation) {
// Create or open the archive object. // Create or open the archive object.
std::unique_ptr<MemoryBuffer> Buf; ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
std::error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false); MemoryBuffer::getFile(ArchiveName, -1, false);
std::error_code EC = Buf.getError();
if (EC && EC != errc::no_such_file_or_directory) { if (EC && EC != errc::no_such_file_or_directory) {
errs() << ToolName << ": error opening '" << ArchiveName errs() << ToolName << ": error opening '" << ArchiveName
<< "': " << EC.message() << "!\n"; << "': " << EC.message() << "!\n";
@ -943,7 +944,7 @@ static int performOperation(ArchiveOperation Operation) {
} }
if (!EC) { if (!EC) {
object::Archive Archive(std::move(Buf), EC); object::Archive Archive(std::move(Buf.get()), EC);
if (EC) { if (EC) {
errs() << ToolName << ": error loading '" << ArchiveName errs() << ToolName << ": error loading '" << ArchiveName

View File

@ -478,10 +478,11 @@ static void PrintSize(uint64_t Bits) {
/// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename. /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
static int AnalyzeBitcode() { static int AnalyzeBitcode() {
// Read the input file. // Read the input file.
std::unique_ptr<MemoryBuffer> MemBuf; ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, MemBuf)) if (std::error_code EC = MemBufOrErr.getError())
return Error("Error reading '" + InputFilename + "': " + ec.message()); return Error("Error reading '" + InputFilename + "': " + EC.message());
std::unique_ptr<MemoryBuffer> MemBuf = std::move(MemBufOrErr.get());
if (MemBuf->getBufferSize() & 3) if (MemBuf->getBufferSize() & 3)
return Error("Bitcode stream should be a multiple of 4 bytes in length"); return Error("Bitcode stream should be a multiple of 4 bytes in length");

View File

@ -97,27 +97,29 @@ void reportCoverage(StringRef SourceFile) {
: InputGCDA; : InputGCDA;
GCOVFile GF; GCOVFile GF;
std::unique_ptr<MemoryBuffer> GCNO_Buff; ErrorOr<std::unique_ptr<MemoryBuffer>> GCNO_Buff =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(GCNO, GCNO_Buff)) { MemoryBuffer::getFileOrSTDIN(GCNO);
errs() << GCNO << ": " << ec.message() << "\n"; if (std::error_code EC = GCNO_Buff.getError()) {
errs() << GCNO << ": " << EC.message() << "\n";
return; return;
} }
GCOVBuffer GCNO_GB(GCNO_Buff.get()); GCOVBuffer GCNO_GB(GCNO_Buff.get().get());
if (!GF.readGCNO(GCNO_GB)) { if (!GF.readGCNO(GCNO_GB)) {
errs() << "Invalid .gcno File!\n"; errs() << "Invalid .gcno File!\n";
return; return;
} }
std::unique_ptr<MemoryBuffer> GCDA_Buff; ErrorOr<std::unique_ptr<MemoryBuffer>> GCDA_Buff =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(GCDA, GCDA_Buff)) { MemoryBuffer::getFileOrSTDIN(GCDA);
if (ec != errc::no_such_file_or_directory) { if (std::error_code EC = GCDA_Buff.getError()) {
errs() << GCDA << ": " << ec.message() << "\n"; if (EC != errc::no_such_file_or_directory) {
errs() << GCDA << ": " << EC.message() << "\n";
return; return;
} }
// Clear the filename to make it clear we didn't read anything. // Clear the filename to make it clear we didn't read anything.
GCDA = "-"; GCDA = "-";
} else { } else {
GCOVBuffer GCDA_GB(GCDA_Buff.get()); GCOVBuffer GCDA_GB(GCDA_Buff.get().get());
if (!GF.readGCDA(GCDA_GB)) { if (!GF.readGCDA(GCDA_GB)) {
errs() << "Invalid .gcda File!\n"; errs() << "Invalid .gcda File!\n";
return; return;

View File

@ -66,14 +66,15 @@ DumpType("debug-dump", cl::init(DIDT_All),
clEnumValEnd)); clEnumValEnd));
static void DumpInput(const StringRef &Filename) { static void DumpInput(const StringRef &Filename) {
std::unique_ptr<MemoryBuffer> Buff; ErrorOr<std::unique_ptr<MemoryBuffer>> Buff =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) { if (std::error_code EC = Buff.getError()) {
errs() << Filename << ": " << ec.message() << "\n"; errs() << Filename << ": " << EC.message() << "\n";
return; return;
} }
ErrorOr<ObjectFile *> ObjOrErr(ObjectFile::createObjectFile(Buff)); ErrorOr<ObjectFile *> ObjOrErr(ObjectFile::createObjectFile(Buff.get()));
if (std::error_code EC = ObjOrErr.getError()) { if (std::error_code EC = ObjOrErr.getError()) {
errs() << Filename << ": " << EC.message() << '\n'; errs() << Filename << ": " << EC.message() << '\n';
return; return;

View File

@ -367,13 +367,13 @@ int main(int argc, char **argv) {
if (!TheTarget) if (!TheTarget)
return 1; return 1;
std::unique_ptr<MemoryBuffer> BufferPtr; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename);
MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) { if (std::error_code EC = BufferPtr.getError()) {
errs() << ProgName << ": " << ec.message() << '\n'; errs() << ProgName << ": " << EC.message() << '\n';
return 1; return 1;
} }
MemoryBuffer *Buffer = BufferPtr.release(); MemoryBuffer *Buffer = BufferPtr->release();
SourceMgr SrcMgr; SourceMgr SrcMgr;

View File

@ -135,12 +135,13 @@ MarkupTag MarkupParser::parseTag() {
} }
static void parseMCMarkup(StringRef Filename) { static void parseMCMarkup(StringRef Filename) {
std::unique_ptr<MemoryBuffer> BufferPtr; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, BufferPtr)) { MemoryBuffer::getFileOrSTDIN(Filename);
errs() << ToolName << ": " << ec.message() << '\n'; if (std::error_code EC = BufferPtr.getError()) {
errs() << ToolName << ": " << EC.message() << '\n';
return; return;
} }
MemoryBuffer *Buffer = BufferPtr.release(); MemoryBuffer *Buffer = BufferPtr->release();
SourceMgr SrcMgr; SourceMgr SrcMgr;

View File

@ -805,9 +805,11 @@ static bool checkMachOAndArchFlags(SymbolicFile *O, std::string &Filename) {
} }
static void dumpSymbolNamesFromFile(std::string &Filename) { static void dumpSymbolNamesFromFile(std::string &Filename) {
std::unique_ptr<MemoryBuffer> Buffer; ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename)) MemoryBuffer::getFileOrSTDIN(Filename);
if (error(BufferOrErr.getError(), Filename))
return; return;
std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
LLVMContext &Context = getGlobalContext(); LLVMContext &Context = getGlobalContext();
ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer, &Context); ErrorOr<Binary *> BinaryOrErr = createBinary(Buffer, &Context);

View File

@ -195,15 +195,15 @@ static void DisassembleInputMachO2(StringRef Filename,
MachOObjectFile *MachOOF); MachOObjectFile *MachOOF);
void llvm::DisassembleInputMachO(StringRef Filename) { void llvm::DisassembleInputMachO(StringRef Filename) {
std::unique_ptr<MemoryBuffer> Buff; ErrorOr<std::unique_ptr<MemoryBuffer>> Buff =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) { if (std::error_code EC = Buff.getError()) {
errs() << "llvm-objdump: " << Filename << ": " << ec.message() << "\n"; errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
return; return;
} }
std::unique_ptr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile *>( std::unique_ptr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile *>(
ObjectFile::createMachOObjectFile(Buff).get())); ObjectFile::createMachOObjectFile(Buff.get()).get()));
DisassembleInputMachO2(Filename, MachOOF.get()); DisassembleInputMachO2(Filename, MachOOF.get());
} }
@ -288,12 +288,13 @@ static void DisassembleInputMachO2(StringRef Filename,
// A separate DSym file path was specified, parse it as a macho file, // A separate DSym file path was specified, parse it as a macho file,
// get the sections and supply it to the section name parsing machinery. // get the sections and supply it to the section name parsing machinery.
if (!DSYMFile.empty()) { if (!DSYMFile.empty()) {
std::unique_ptr<MemoryBuffer> Buf; ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(DSYMFile, Buf)) { MemoryBuffer::getFileOrSTDIN(DSYMFile);
errs() << "llvm-objdump: " << Filename << ": " << ec.message() << '\n'; if (std::error_code EC = Buf.getError()) {
errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
return; return;
} }
DbgObj = ObjectFile::createMachOObjectFile(Buf).get(); DbgObj = ObjectFile::createMachOObjectFile(Buf.get()).get();
} }
// Setup the DIContext // Setup the DIContext

View File

@ -175,14 +175,16 @@ static int printLineInfoForInput() {
RuntimeDyld Dyld(&MemMgr); RuntimeDyld Dyld(&MemMgr);
// Load the input memory buffer. // Load the input memory buffer.
std::unique_ptr<MemoryBuffer> InputBuffer;
std::unique_ptr<ObjectImage> LoadedObject;
if (std::error_code ec =
MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
return Error("unable to read input: '" + ec.message() + "'");
ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
if (std::error_code EC = InputBuffer.getError())
return Error("unable to read input: '" + EC.message() + "'");
std::unique_ptr<ObjectImage> LoadedObject;
// Load the object file // Load the object file
LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release()))); LoadedObject.reset(
Dyld.loadObject(new ObjectBuffer(InputBuffer.get().release())));
if (!LoadedObject) { if (!LoadedObject) {
return Error(Dyld.getErrorString()); return Error(Dyld.getErrorString());
} }
@ -236,14 +238,14 @@ static int executeInput() {
InputFileList.push_back("-"); InputFileList.push_back("-");
for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) { for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
// Load the input memory buffer. // Load the input memory buffer.
std::unique_ptr<MemoryBuffer> InputBuffer; ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
if (std::error_code EC = InputBuffer.getError())
return Error("unable to read input: '" + EC.message() + "'");
std::unique_ptr<ObjectImage> LoadedObject; std::unique_ptr<ObjectImage> LoadedObject;
if (std::error_code ec =
MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer))
return Error("unable to read input: '" + ec.message() + "'");
// Load the object file // Load the object file
LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.release()))); LoadedObject.reset(
Dyld.loadObject(new ObjectBuffer(InputBuffer.get().release())));
if (!LoadedObject) { if (!LoadedObject) {
return Error(Dyld.getErrorString()); return Error(Dyld.getErrorString());
} }
@ -285,13 +287,14 @@ static int executeInput() {
static int checkAllExpressions(RuntimeDyldChecker &Checker) { static int checkAllExpressions(RuntimeDyldChecker &Checker) {
for (const auto& CheckerFileName : CheckFiles) { for (const auto& CheckerFileName : CheckFiles) {
std::unique_ptr<MemoryBuffer> CheckerFileBuf; ErrorOr<std::unique_ptr<MemoryBuffer>> CheckerFileBuf =
if (std::error_code EC = MemoryBuffer::getFileOrSTDIN(CheckerFileName);
MemoryBuffer::getFileOrSTDIN(CheckerFileName, CheckerFileBuf)) if (std::error_code EC = CheckerFileBuf.getError())
return Error("unable to read input '" + CheckerFileName + "': " + return Error("unable to read input '" + CheckerFileName + "': " +
EC.message()); EC.message());
if (!Checker.checkAllRulesInBuffer("# rtdyld-check:", CheckerFileBuf.get())) if (!Checker.checkAllRulesInBuffer("# rtdyld-check:",
CheckerFileBuf.get().get()))
return Error("some checks in '" + CheckerFileName + "' failed"); return Error("some checks in '" + CheckerFileName + "' failed");
} }
return 0; return 0;
@ -350,15 +353,15 @@ static int linkAndVerify() {
InputFileList.push_back("-"); InputFileList.push_back("-");
for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) { for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
// Load the input memory buffer. // Load the input memory buffer.
std::unique_ptr<MemoryBuffer> InputBuffer; ErrorOr<std::unique_ptr<MemoryBuffer>> InputBuffer =
std::unique_ptr<ObjectImage> LoadedObject; MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
if (std::error_code ec = if (std::error_code EC = InputBuffer.getError())
MemoryBuffer::getFileOrSTDIN(InputFileList[i], InputBuffer)) return Error("unable to read input: '" + EC.message() + "'");
return Error("unable to read input: '" + ec.message() + "'");
std::unique_ptr<ObjectImage> LoadedObject;
// Load the object file // Load the object file
LoadedObject.reset( LoadedObject.reset(
Dyld.loadObject(new ObjectBuffer(InputBuffer.release()))); Dyld.loadObject(new ObjectBuffer(InputBuffer.get().release())));
if (!LoadedObject) { if (!LoadedObject) {
return Error(Dyld.getErrorString()); return Error(Dyld.getErrorString());
} }

View File

@ -220,10 +220,11 @@ static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
} }
static bool checkFileCRC(StringRef Path, uint32_t CRCHash) { static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
std::unique_ptr<MemoryBuffer> MB; ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
if (MemoryBuffer::getFileOrSTDIN(Path, MB)) MemoryBuffer::getFileOrSTDIN(Path);
if (!MB)
return false; return false;
return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer()); return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
} }
static bool findDebugBinary(const std::string &OrigPath, static bool findDebugBinary(const std::string &OrigPath,

View File

@ -88,10 +88,10 @@ bool lto_module_is_object_file(const char* path) {
bool lto_module_is_object_file_for_target(const char* path, bool lto_module_is_object_file_for_target(const char* path,
const char* target_triplet_prefix) { const char* target_triplet_prefix) {
std::unique_ptr<MemoryBuffer> buffer; ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path);
if (MemoryBuffer::getFile(path, buffer)) if (!Buffer)
return false; return false;
return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix); return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix);
} }
bool lto_module_is_object_file_in_memory(const void* mem, size_t length) { bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {

View File

@ -91,8 +91,9 @@ int main(int argc, char **argv) {
return 1; return 1;
} }
std::unique_ptr<MemoryBuffer> Buf; ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
if (MemoryBuffer::getFileOrSTDIN(Input, Buf)) MemoryBuffer::getFileOrSTDIN(Input);
if (!Buf)
return 1; return 1;
ConvertFuncPtr Convert = nullptr; ConvertFuncPtr Convert = nullptr;
@ -105,7 +106,7 @@ int main(int argc, char **argv) {
return 1; return 1;
} }
yaml::Input YIn(Buf->getBuffer()); yaml::Input YIn(Buf.get()->getBuffer());
int Res = convertYAML(YIn, Out->os(), Convert); int Res = convertYAML(YIn, Out->os(), Convert);
if (Res == 0) if (Res == 0)

View File

@ -77,11 +77,11 @@ TEST_F(MemoryBufferTest, NullTerminator4K) {
} }
OF.close(); OF.close();
OwningBuffer MB; ErrorOr<OwningBuffer> MB = MemoryBuffer::getFile(TestPath.c_str());
std::error_code EC = MemoryBuffer::getFile(TestPath.c_str(), MB); std::error_code EC = MB.getError();
ASSERT_FALSE(EC); ASSERT_FALSE(EC);
const char *BufData = MB->getBufferStart(); const char *BufData = MB.get()->getBufferStart();
EXPECT_EQ('f', BufData[4095]); EXPECT_EQ('f', BufData[4095]);
EXPECT_EQ('\0', BufData[4096]); EXPECT_EQ('\0', BufData[4096]);
} }
@ -146,15 +146,16 @@ void MemoryBufferTest::testGetOpenFileSlice(bool Reopen) {
EXPECT_FALSE(sys::fs::openFileForRead(TestPath.c_str(), TestFD)); EXPECT_FALSE(sys::fs::openFileForRead(TestPath.c_str(), TestFD));
} }
OwningBuffer Buf; ErrorOr<OwningBuffer> Buf =
std::error_code EC = MemoryBuffer::getOpenFileSlice(TestFD, TestPath.c_str(),
MemoryBuffer::getOpenFileSlice(TestFD, TestPath.c_str(), Buf,
40000, // Size 40000, // Size
80000 // Offset 80000 // Offset
); );
std::error_code EC = Buf.getError();
EXPECT_FALSE(EC); EXPECT_FALSE(EC);
StringRef BufData = Buf->getBuffer(); StringRef BufData = Buf.get()->getBuffer();
EXPECT_EQ(BufData.size(), 40000U); EXPECT_EQ(BufData.size(), 40000U);
EXPECT_EQ(BufData[0], '0'); EXPECT_EQ(BufData[0], '0');
EXPECT_EQ(BufData[9], '9'); EXPECT_EQ(BufData[9], '9');

View File

@ -820,17 +820,18 @@ static StringRef FindFirstMatchingPrefix(StringRef &Buffer,
/// Returns true in case of an error, false otherwise. /// Returns true in case of an error, false otherwise.
static bool ReadCheckFile(SourceMgr &SM, static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) { std::vector<CheckString> &CheckStrings) {
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(CheckFilename, File)) { MemoryBuffer::getFileOrSTDIN(CheckFilename);
errs() << "Could not open check file '" << CheckFilename << "': " if (std::error_code EC = FileOrErr.getError()) {
<< ec.message() << '\n'; errs() << "Could not open check file '" << CheckFilename
<< "': " << EC.message() << '\n';
return true; return true;
} }
// If we want to canonicalize whitespace, strip excess whitespace from the // If we want to canonicalize whitespace, strip excess whitespace from the
// buffer containing the CHECK lines. Remove DOS style line endings. // buffer containing the CHECK lines. Remove DOS style line endings.
MemoryBuffer *F = MemoryBuffer *F = CanonicalizeInputFile(FileOrErr.get().release(),
CanonicalizeInputFile(File.release(), NoCanonicalizeWhiteSpace); NoCanonicalizeWhiteSpace);
SM.AddNewSourceBuffer(F, SMLoc()); SM.AddNewSourceBuffer(F, SMLoc());
@ -1223,12 +1224,14 @@ int main(int argc, char **argv) {
return 2; return 2;
// Open the file to check and add it to SourceMgr. // Open the file to check and add it to SourceMgr.
std::unique_ptr<MemoryBuffer> File; ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
if (std::error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, File)) { MemoryBuffer::getFileOrSTDIN(InputFilename);
errs() << "Could not open input file '" << InputFilename << "': " if (std::error_code EC = FileOrErr.getError()) {
<< ec.message() << '\n'; errs() << "Could not open input file '" << InputFilename
<< "': " << EC.message() << '\n';
return 2; return 2;
} }
std::unique_ptr<MemoryBuffer> File = std::move(FileOrErr.get());
if (File->getBufferSize() == 0) { if (File->getBufferSize() == 0) {
errs() << "FileCheck error: '" << InputFilename << "' is empty.\n"; errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";

View File

@ -188,9 +188,11 @@ static std::string createJSONText(size_t MemoryMB, unsigned ValueSize) {
int main(int argc, char **argv) { int main(int argc, char **argv) {
llvm::cl::ParseCommandLineOptions(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv);
if (Input.getNumOccurrences()) { if (Input.getNumOccurrences()) {
std::unique_ptr<MemoryBuffer> Buf; ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
if (MemoryBuffer::getFileOrSTDIN(Input, Buf)) MemoryBuffer::getFileOrSTDIN(Input);
if (!BufOrErr)
return 1; return 1;
std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get());
llvm::SourceMgr sm; llvm::SourceMgr sm;
if (DumpTokens) { if (DumpTokens) {