1//===- WasmObjcopy.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 "llvm/ObjCopy/wasm/WasmObjcopy.h"
10#include "WasmObject.h"
11#include "WasmReader.h"
12#include "WasmWriter.h"
13#include "llvm/ObjCopy/CommonConfig.h"
14#include "llvm/Support/Errc.h"
15#include "llvm/Support/FileOutputBuffer.h"
16
17namespace llvm {
18namespace objcopy {
19namespace wasm {
20
21using namespace object;
22using SectionPred = std::function<bool(const Section &Sec)>;
23
24static bool isDebugSection(const Section &Sec) {
25 return Sec.Name.starts_with(Prefix: ".debug") || Sec.Name.starts_with(Prefix: "reloc..debug");
26}
27
28static bool isEngineInterpretedSection(const Section &Sec) {
29 return Sec.SectionType != llvm::wasm::WASM_SEC_CUSTOM ||
30 Sec.Name.starts_with(Prefix: "metadata.code.");
31}
32
33static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
34 StringRef InputFilename, Object &Obj) {
35 for (const Section &Sec : Obj.Sections) {
36 if (Sec.Name == SecName) {
37 ArrayRef<uint8_t> Contents = Sec.Contents;
38 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
39 FileOutputBuffer::create(FilePath: Filename, Size: Contents.size());
40 if (!BufferOrErr)
41 return createFileError(F: Filename, E: BufferOrErr.takeError());
42 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
43 llvm::copy(Range&: Contents, Out: Buf->getBufferStart());
44 if (Error E = Buf->commit())
45 return createFileError(F: Filename, E: std::move(E));
46 return Error::success();
47 }
48 }
49 return createFileError(F: Filename, EC: errc::invalid_argument,
50 Fmt: "section '%s' not found", Vals: SecName.str().c_str());
51}
52
53static void removeSections(const CommonConfig &Config, Object &Obj) {
54 SectionPred RemovePred = [](const Section &) { return false; };
55
56 // Explicitly-requested sections.
57 if (!Config.ToRemove.empty()) {
58 RemovePred = [&Config](const Section &Sec) {
59 return Config.ToRemove.matches(S: Sec.Name);
60 };
61 }
62
63 if (Config.StripDebug) {
64 RemovePred = [RemovePred](const Section &Sec) {
65 return RemovePred(Sec) || isDebugSection(Sec);
66 };
67 }
68
69 if (Config.StripAll) {
70 RemovePred = [RemovePred](const Section &Sec) {
71 return RemovePred(Sec) || !isEngineInterpretedSection(Sec);
72 };
73 }
74
75 if (Config.OnlyKeepDebug) {
76 RemovePred = [&Config](const Section &Sec) {
77 // Keep debug sections, unless explicitly requested to remove.
78 // Remove everything else, including known sections.
79 return Config.ToRemove.matches(S: Sec.Name) || !isDebugSection(Sec);
80 };
81 }
82
83 if (!Config.OnlySection.empty()) {
84 RemovePred = [&Config](const Section &Sec) {
85 // Explicitly keep these sections regardless of previous removes.
86 // Remove everything else, inluding known sections.
87 return !Config.OnlySection.matches(S: Sec.Name);
88 };
89 }
90
91 if (!Config.KeepSection.empty()) {
92 RemovePred = [&Config, RemovePred](const Section &Sec) {
93 // Explicitly keep these sections regardless of previous removes.
94 if (Config.KeepSection.matches(S: Sec.Name))
95 return false;
96 // Otherwise defer to RemovePred.
97 return RemovePred(Sec);
98 };
99 }
100
101 Obj.removeSections(ToRemove: RemovePred);
102}
103
104static Error handleArgs(const CommonConfig &Config, Object &Obj) {
105 // Only support AddSection, DumpSection, RemoveSection for now.
106 for (StringRef Flag : Config.DumpSection) {
107 StringRef SecName;
108 StringRef FileName;
109 std::tie(args&: SecName, args&: FileName) = Flag.split(Separator: "=");
110 if (Error E =
111 dumpSectionToFile(SecName, Filename: FileName, InputFilename: Config.InputFilename, Obj))
112 return E;
113 }
114
115 removeSections(Config, Obj);
116
117 for (const NewSectionInfo &NewSection : Config.AddSection) {
118 Section Sec;
119 Sec.SectionType = llvm::wasm::WASM_SEC_CUSTOM;
120 Sec.Name = NewSection.SectionName;
121
122 llvm::StringRef InputData =
123 llvm::StringRef(NewSection.SectionData->getBufferStart(),
124 NewSection.SectionData->getBufferSize());
125 std::unique_ptr<MemoryBuffer> BufferCopy = MemoryBuffer::getMemBufferCopy(
126 InputData, BufferName: NewSection.SectionData->getBufferIdentifier());
127 Sec.Contents = ArrayRef<uint8_t>(
128 reinterpret_cast<const uint8_t *>(BufferCopy->getBufferStart()),
129 BufferCopy->getBufferSize());
130
131 Obj.addSectionWithOwnedContents(NewSection: Sec, Content: std::move(BufferCopy));
132 }
133
134 return Error::success();
135}
136
137Error executeObjcopyOnBinary(const CommonConfig &Config, const WasmConfig &,
138 object::WasmObjectFile &In, raw_ostream &Out) {
139 Reader TheReader(In);
140 Expected<std::unique_ptr<Object>> ObjOrErr = TheReader.create();
141 if (!ObjOrErr)
142 return createFileError(F: Config.InputFilename, E: ObjOrErr.takeError());
143 Object *Obj = ObjOrErr->get();
144 assert(Obj && "Unable to deserialize Wasm object");
145 if (Error E = handleArgs(Config, Obj&: *Obj))
146 return E;
147 Writer TheWriter(*Obj, Out);
148 if (Error E = TheWriter.write())
149 return createFileError(F: Config.OutputFilename, E: std::move(E));
150 return Error::success();
151}
152
153} // end namespace wasm
154} // end namespace objcopy
155} // end namespace llvm
156