Path: blob/main/contrib/llvm-project/llvm/lib/ObjCopy/wasm/WasmWriter.cpp
35266 views
//===- WasmWriter.cpp -----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "WasmWriter.h"9#include "llvm/BinaryFormat/Wasm.h"10#include "llvm/Support/Endian.h"11#include "llvm/Support/Errc.h"12#include "llvm/Support/LEB128.h"13#include "llvm/Support/raw_ostream.h"1415namespace llvm {16namespace objcopy {17namespace wasm {1819using namespace object;20using namespace llvm::wasm;2122Writer::SectionHeader Writer::createSectionHeader(const Section &S,23size_t &SectionSize) {24SectionHeader Header;25raw_svector_ostream OS(Header);26OS << S.SectionType;27bool HasName = S.SectionType == WASM_SEC_CUSTOM;28SectionSize = S.Contents.size();29if (HasName)30SectionSize += getULEB128Size(S.Name.size()) + S.Name.size();31// If we read this section from an object file, use its original size for the32// padding of the LEB value to avoid changing the file size. Otherwise, pad33// out to 5 bytes to make it predictable, and match the behavior of clang.34unsigned HeaderSecSizeEncodingLen =35S.HeaderSecSizeEncodingLen ? *S.HeaderSecSizeEncodingLen : 5;36encodeULEB128(SectionSize, OS, HeaderSecSizeEncodingLen);37if (HasName) {38encodeULEB128(S.Name.size(), OS);39OS << S.Name;40}41// Total section size is the content size plus 1 for the section type and42// the LEB-encoded size.43SectionSize = SectionSize + 1 + HeaderSecSizeEncodingLen;44return Header;45}4647size_t Writer::finalize() {48size_t ObjectSize = sizeof(WasmMagic) + sizeof(WasmVersion);49SectionHeaders.reserve(Obj.Sections.size());50// Finalize the headers of each section so we know the total size.51for (const Section &S : Obj.Sections) {52size_t SectionSize;53SectionHeaders.push_back(createSectionHeader(S, SectionSize));54ObjectSize += SectionSize;55}56return ObjectSize;57}5859Error Writer::write() {60size_t TotalSize = finalize();61Out.reserveExtraSpace(TotalSize);6263// Write the header.64Out.write(Obj.Header.Magic.data(), Obj.Header.Magic.size());65uint32_t Version;66support::endian::write32le(&Version, Obj.Header.Version);67Out.write(reinterpret_cast<const char *>(&Version), sizeof(Version));6869// Write each section.70for (size_t I = 0, S = SectionHeaders.size(); I < S; ++I) {71Out.write(SectionHeaders[I].data(), SectionHeaders[I].size());72Out.write(reinterpret_cast<const char *>(Obj.Sections[I].Contents.data()),73Obj.Sections[I].Contents.size());74}7576return Error::success();77}7879} // end namespace wasm80} // end namespace objcopy81} // end namespace llvm828384