1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "Writer.h"
10 #include "llvm/BinaryFormat/Wasm.h"
11 #include "llvm/Support/Endian.h"
12 #include "llvm/Support/LEB128.h"
13 #include "llvm/Support/raw_ostream.h"
14
15 namespace llvm {
16 namespace objcopy {
17 namespace wasm {
18
19 using namespace object;
20 using namespace llvm::wasm;
21
createSectionHeader(const Section & S,size_t & SectionSize)22 Writer::SectionHeader Writer::createSectionHeader(const Section &S,
23 size_t &SectionSize) {
24 SectionHeader Header;
25 raw_svector_ostream OS(Header);
26 OS << S.SectionType;
27 bool HasName = S.SectionType == WASM_SEC_CUSTOM;
28 SectionSize = S.Contents.size();
29 if (HasName)
30 SectionSize += getULEB128Size(S.Name.size()) + S.Name.size();
31 // Pad the LEB value out to 5 bytes to make it a predictable size, and
32 // match the behavior of clang.
33 encodeULEB128(SectionSize, OS, 5);
34 if (HasName) {
35 encodeULEB128(S.Name.size(), OS);
36 OS << S.Name;
37 }
38 // Total section size is the content size plus 1 for the section type and
39 // 5 for the LEB-encoded size.
40 SectionSize = SectionSize + 1 + 5;
41 return Header;
42 }
43
finalize()44 size_t Writer::finalize() {
45 size_t ObjectSize = sizeof(WasmMagic) + sizeof(WasmVersion);
46 SectionHeaders.reserve(Obj.Sections.size());
47 // Finalize the headers of each section so we know the total size.
48 for (const Section &S : Obj.Sections) {
49 size_t SectionSize;
50 SectionHeaders.push_back(createSectionHeader(S, SectionSize));
51 ObjectSize += SectionSize;
52 }
53 return ObjectSize;
54 }
55
write()56 Error Writer::write() {
57 size_t FileSize = finalize();
58 if (Error E = Buf.allocate(FileSize))
59 return E;
60
61 // Write the header.
62 uint8_t *Ptr = Buf.getBufferStart();
63 Ptr = std::copy(Obj.Header.Magic.begin(), Obj.Header.Magic.end(), Ptr);
64 support::endian::write32le(Ptr, Obj.Header.Version);
65 Ptr += sizeof(Obj.Header.Version);
66
67 // Write each section.
68 for (size_t I = 0, S = SectionHeaders.size(); I < S; ++I) {
69 Ptr = std::copy(SectionHeaders[I].begin(), SectionHeaders[I].end(), Ptr);
70 ArrayRef<uint8_t> Contents = Obj.Sections[I].Contents;
71 Ptr = std::copy(Contents.begin(), Contents.end(), Ptr);
72 }
73 return Buf.commit();
74 }
75
76 } // end namespace wasm
77 } // end namespace objcopy
78 } // end namespace llvm
79