blob: 24b1a9edfd2fe85ba99db1545ffac7e9c4c37630 [file] [log] [blame]
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +00001//===- MachOObjcopy.cpp -----------------------------------------*- C++ -*-===//
2//
Chandler Carruth127252b2019-02-11 08:25:19 +00003// 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
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "MachOObjcopy.h"
10#include "../CopyConfig.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000011#include "MachOReader.h"
12#include "MachOWriter.h"
Seiya Nuta4bc71012019-05-29 22:21:12 +000013#include "llvm/Support/Errc.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000014#include "llvm/Support/Error.h"
15
16namespace llvm {
17namespace objcopy {
18namespace macho {
19
Seiya Nuta4bc71012019-05-29 22:21:12 +000020using namespace object;
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080021using SectionPred = std::function<bool(const std::unique_ptr<Section> &Sec)>;
Seiya Nuta7f19dd12019-10-28 15:40:37 +090022
23static void removeSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080024 SectionPred RemovePred = [](const std::unique_ptr<Section> &) { return false; };
Seiya Nuta7f19dd12019-10-28 15:40:37 +090025
Seiya Nutabc118302019-11-15 12:37:55 +090026 if (!Config.ToRemove.empty()) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080027 RemovePred = [&Config, RemovePred](const std::unique_ptr<Section> &Sec) {
28 return Config.ToRemove.matches(Sec->CanonicalName);
Seiya Nutabc118302019-11-15 12:37:55 +090029 };
30 }
31
Fangrui Song30ccee72019-11-18 15:25:04 -080032 if (Config.StripAll || Config.StripDebug) {
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090033 // Remove all debug sections.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080034 RemovePred = [RemovePred](const std::unique_ptr<Section> &Sec) {
35 if (Sec->Segname == "__DWARF")
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090036 return true;
37
38 return RemovePred(Sec);
39 };
40 }
41
Seiya Nuta7f19dd12019-10-28 15:40:37 +090042 if (!Config.OnlySection.empty()) {
Seiya Nutabc118302019-11-15 12:37:55 +090043 // Overwrite RemovePred because --only-section takes priority.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080044 RemovePred = [&Config](const std::unique_ptr<Section> &Sec) {
45 return !Config.OnlySection.matches(Sec->CanonicalName);
Seiya Nuta7f19dd12019-10-28 15:40:37 +090046 };
47 }
48
49 return Obj.removeSections(RemovePred);
50}
Seiya Nuta4bc71012019-05-29 22:21:12 +000051
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090052static void markSymbols(const CopyConfig &Config, Object &Obj) {
53 // Symbols referenced from the indirect symbol table must not be removed.
54 for (IndirectSymbolEntry &ISE : Obj.IndirectSymTable.Symbols)
55 if (ISE.Symbol)
56 (*ISE.Symbol)->Referenced = true;
57}
58
Fangrui Song28a5dc72019-11-13 13:10:15 -080059static void updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
60 for (SymbolEntry &Sym : Obj.SymTable) {
61 auto I = Config.SymbolsToRename.find(Sym.Name);
62 if (I != Config.SymbolsToRename.end())
Benjamin Krameradcd0262020-01-28 20:23:46 +010063 Sym.Name = std::string(I->getValue());
Fangrui Song28a5dc72019-11-13 13:10:15 -080064 }
65
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090066 auto RemovePred = [Config](const std::unique_ptr<SymbolEntry> &N) {
67 if (N->Referenced)
68 return false;
69 return Config.StripAll;
70 };
71
72 Obj.SymTable.removeSymbols(RemovePred);
73}
74
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080075static LoadCommand buildRPathLoadCommand(StringRef Path) {
76 LoadCommand LC;
77 MachO::rpath_command RPathLC;
78 RPathLC.cmd = MachO::LC_RPATH;
79 RPathLC.path = sizeof(MachO::rpath_command);
80 RPathLC.cmdsize = alignTo(sizeof(MachO::rpath_command) + Path.size(), 8);
81 LC.MachOLoadCommand.rpath_command_data = RPathLC;
82 LC.Payload.assign(RPathLC.cmdsize - sizeof(MachO::rpath_command), 0);
83 std::copy(Path.begin(), Path.end(), LC.Payload.begin());
84 return LC;
85}
86
Seiya Nutad72a8a42019-11-25 12:29:58 +090087static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
88 Object &Obj) {
89 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080090 for (const std::unique_ptr<Section> &Sec : LC.Sections) {
91 if (Sec->CanonicalName == SecName) {
Seiya Nutad72a8a42019-11-25 12:29:58 +090092 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080093 FileOutputBuffer::create(Filename, Sec->Content.size());
Seiya Nutad72a8a42019-11-25 12:29:58 +090094 if (!BufferOrErr)
95 return BufferOrErr.takeError();
96 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080097 llvm::copy(Sec->Content, Buf->getBufferStart());
Seiya Nutad72a8a42019-11-25 12:29:58 +090098
99 if (Error E = Buf->commit())
100 return E;
101 return Error::success();
102 }
103 }
104
105 return createStringError(object_error::parse_failed, "section '%s' not found",
106 SecName.str().c_str());
107}
108
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900109static Error addSection(StringRef SecName, StringRef Filename, Object &Obj) {
110 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
111 MemoryBuffer::getFile(Filename);
112 if (!BufOrErr)
113 return createFileError(Filename, errorCodeToError(BufOrErr.getError()));
114 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
115
116 std::pair<StringRef, StringRef> Pair = SecName.split(',');
117 StringRef TargetSegName = Pair.first;
118 Section Sec(TargetSegName, Pair.second);
119 Sec.Content = Obj.NewSectionsContents.save(Buf->getBuffer());
120
121 // Add the a section into an existing segment.
122 for (LoadCommand &LC : Obj.LoadCommands) {
123 Optional<StringRef> SegName = LC.getSegmentName();
124 if (SegName && SegName == TargetSegName) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800125 LC.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900126 return Error::success();
127 }
128 }
129
130 // There's no segment named TargetSegName. Create a new load command and
131 // Insert a new section into it.
132 LoadCommand &NewSegment = Obj.addSegment(TargetSegName);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800133 NewSegment.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900134 return Error::success();
135}
136
137// isValidMachOCannonicalName returns success if Name is a MachO cannonical name
138// ("<segment>,<section>") and lengths of both segment and section names are
139// valid.
140Error isValidMachOCannonicalName(StringRef Name) {
141 if (Name.count(',') != 1)
142 return createStringError(errc::invalid_argument,
143 "invalid section name '%s' (should be formatted "
144 "as '<segment name>,<section name>')",
145 Name.str().c_str());
146
147 std::pair<StringRef, StringRef> Pair = Name.split(',');
148 if (Pair.first.size() > 16)
149 return createStringError(errc::invalid_argument,
150 "too long segment name: '%s'",
151 Pair.first.str().c_str());
152 if (Pair.second.size() > 16)
153 return createStringError(errc::invalid_argument,
154 "too long section name: '%s'",
155 Pair.second.str().c_str());
156 return Error::success();
157}
158
Seiya Nuta4bc71012019-05-29 22:21:12 +0000159static Error handleArgs(const CopyConfig &Config, Object &Obj) {
160 if (Config.AllowBrokenLinks || !Config.BuildIdLinkDir.empty() ||
161 Config.BuildIdLinkInput || Config.BuildIdLinkOutput ||
162 !Config.SplitDWO.empty() || !Config.SymbolsPrefix.empty() ||
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900163 !Config.AllocSectionsPrefix.empty() || !Config.KeepSection.empty() ||
164 Config.NewSymbolVisibility || !Config.SymbolsToGlobalize.empty() ||
165 !Config.SymbolsToKeep.empty() || !Config.SymbolsToLocalize.empty() ||
166 !Config.SymbolsToWeaken.empty() || !Config.SymbolsToKeepGlobal.empty() ||
167 !Config.SectionsToRename.empty() ||
Seiya Nuta4bc71012019-05-29 22:21:12 +0000168 !Config.UnneededSymbolsToRemove.empty() ||
Fangrui Song671fb342019-10-02 12:41:25 +0000169 !Config.SetSectionAlignment.empty() || !Config.SetSectionFlags.empty() ||
Seiya Nutabc118302019-11-15 12:37:55 +0900170 Config.ExtractDWO || Config.KeepFileSymbols || Config.LocalizeHidden ||
171 Config.PreserveDates || Config.StripAllGNU || Config.StripDWO ||
172 Config.StripNonAlloc || Config.StripSections || Config.Weaken ||
Fangrui Song30ccee72019-11-18 15:25:04 -0800173 Config.DecompressDebugSections || Config.StripNonAlloc ||
174 Config.StripSections || Config.StripUnneeded ||
Fangrui Song671fb342019-10-02 12:41:25 +0000175 Config.DiscardMode != DiscardType::None || !Config.SymbolsToAdd.empty() ||
176 Config.EntryExpr) {
Seiya Nuta4bc71012019-05-29 22:21:12 +0000177 return createStringError(llvm::errc::invalid_argument,
178 "option not supported by llvm-objcopy for MachO");
179 }
Seiya Nuta7f19dd12019-10-28 15:40:37 +0900180 removeSections(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900181
182 // Mark symbols to determine which symbols are still needed.
183 if (Config.StripAll)
184 markSymbols(Config, Obj);
185
Fangrui Song28a5dc72019-11-13 13:10:15 -0800186 updateAndRemoveSymbols(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900187
188 if (Config.StripAll)
189 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800190 for (std::unique_ptr<Section> &Sec : LC.Sections)
191 Sec->Relocations.clear();
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900192
Seiya Nutad72a8a42019-11-25 12:29:58 +0900193 for (const StringRef &Flag : Config.DumpSection) {
194 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
195 StringRef SecName = SecPair.first;
196 StringRef File = SecPair.second;
197 if (Error E = dumpSectionToFile(SecName, File, Obj))
198 return E;
199 }
200
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900201 for (const auto &Flag : Config.AddSection) {
202 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
203 StringRef SecName = SecPair.first;
204 StringRef File = SecPair.second;
205 if (Error E = isValidMachOCannonicalName(SecName))
206 return E;
207 if (Error E = addSection(SecName, File, Obj))
208 return E;
209 }
210
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800211 for (StringRef RPath : Config.RPathToAdd) {
212 for (LoadCommand &LC : Obj.LoadCommands) {
213 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH &&
214 RPath == StringRef(reinterpret_cast<char *>(LC.Payload.data()),
215 LC.Payload.size())
216 .trim(0)) {
217 return createStringError(errc::invalid_argument,
218 "rpath " + RPath +
219 " would create a duplicate load command");
220 }
221 }
222 Obj.addLoadCommand(buildRPathLoadCommand(RPath));
223 }
Seiya Nuta4bc71012019-05-29 22:21:12 +0000224 return Error::success();
225}
226
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000227Error executeObjcopyOnBinary(const CopyConfig &Config,
228 object::MachOObjectFile &In, Buffer &Out) {
229 MachOReader Reader(In);
230 std::unique_ptr<Object> O = Reader.create();
Seiya Nuta4bc71012019-05-29 22:21:12 +0000231 if (!O)
232 return createFileError(
233 Config.InputFilename,
234 createStringError(object_error::parse_failed,
235 "unable to deserialize MachO object"));
236
237 if (Error E = handleArgs(Config, *O))
238 return createFileError(Config.InputFilename, std::move(E));
239
Seiya Nuta552bcb82019-08-19 21:05:31 +0000240 // TODO: Support 16KB pages which are employed in iOS arm64 binaries:
241 // https://github.com/llvm/llvm-project/commit/1bebb2832ee312d3b0316dacff457a7a29435edb
242 const uint64_t PageSize = 4096;
243
244 MachOWriter Writer(*O, In.is64Bit(), In.isLittleEndian(), PageSize, Out);
Seiya Nutab728e532019-06-08 01:22:54 +0000245 if (auto E = Writer.finalize())
246 return E;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000247 return Writer.write();
248}
249
250} // end namespace macho
251} // end namespace objcopy
252} // end namespace llvm