1 //===- Buffer.cpp ---------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 #include "llvm-objcopy.h"
11 #include "llvm/Support/FileOutputBuffer.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/Process.h"
22 static Error
createEmptyFile(StringRef FileName
) {
23 // Create an empty tempfile and atomically swap it in place with the desired
25 Expected
<sys::fs::TempFile
> Temp
=
26 sys::fs::TempFile::create(FileName
+ ".temp-empty-%%%%%%%");
27 return Temp
? Temp
->keep(FileName
) : Temp
.takeError();
30 Error
FileBuffer::allocate(size_t Size
) {
31 // When a 0-sized file is requested, skip allocation but defer file
32 // creation/truncation until commit() to avoid side effects if something
33 // happens between allocate() and commit().
36 return Error::success();
39 Expected
<std::unique_ptr
<FileOutputBuffer
>> BufferOrErr
=
40 FileOutputBuffer::create(getName(), Size
, FileOutputBuffer::F_executable
);
41 // FileOutputBuffer::create() returns an Error that is just a wrapper around
42 // std::error_code. Wrap it in FileError to include the actual filename.
44 return createFileError(getName(), BufferOrErr
.takeError());
45 Buf
= std::move(*BufferOrErr
);
46 return Error::success();
49 Error
FileBuffer::commit() {
51 return createEmptyFile(getName());
53 assert(Buf
&& "allocate() not called before commit()!");
54 Error Err
= Buf
->commit();
55 // FileOutputBuffer::commit() returns an Error that is just a wrapper around
56 // std::error_code. Wrap it in FileError to include the actual filename.
57 return Err
? createFileError(getName(), std::move(Err
)) : std::move(Err
);
60 uint8_t *FileBuffer::getBufferStart() {
61 return reinterpret_cast<uint8_t *>(Buf
->getBufferStart());
64 Error
MemBuffer::allocate(size_t Size
) {
65 Buf
= WritableMemoryBuffer::getNewMemBuffer(Size
, getName());
66 return Error::success();
69 Error
MemBuffer::commit() { return Error::success(); }
71 uint8_t *MemBuffer::getBufferStart() {
72 return reinterpret_cast<uint8_t *>(Buf
->getBufferStart());
75 std::unique_ptr
<WritableMemoryBuffer
> MemBuffer::releaseMemoryBuffer() {
76 return std::move(Buf
);
79 } // end namespace objcopy
80 } // end namespace llvm