blob: 8f159ca1163298b5f5965a5f0dfc58ed95df9a12 [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;
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -080069 if (Config.StripAll)
70 return true;
71 if (Config.DiscardMode == DiscardType::All && !(N->n_type & MachO::N_EXT))
72 return true;
73 return false;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090074 };
75
76 Obj.SymTable.removeSymbols(RemovePred);
77}
78
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080079static LoadCommand buildRPathLoadCommand(StringRef Path) {
80 LoadCommand LC;
81 MachO::rpath_command RPathLC;
82 RPathLC.cmd = MachO::LC_RPATH;
83 RPathLC.path = sizeof(MachO::rpath_command);
84 RPathLC.cmdsize = alignTo(sizeof(MachO::rpath_command) + Path.size(), 8);
85 LC.MachOLoadCommand.rpath_command_data = RPathLC;
86 LC.Payload.assign(RPathLC.cmdsize - sizeof(MachO::rpath_command), 0);
87 std::copy(Path.begin(), Path.end(), LC.Payload.begin());
88 return LC;
89}
90
Seiya Nutad72a8a42019-11-25 12:29:58 +090091static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
92 Object &Obj) {
93 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080094 for (const std::unique_ptr<Section> &Sec : LC.Sections) {
95 if (Sec->CanonicalName == SecName) {
Seiya Nutad72a8a42019-11-25 12:29:58 +090096 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080097 FileOutputBuffer::create(Filename, Sec->Content.size());
Seiya Nutad72a8a42019-11-25 12:29:58 +090098 if (!BufferOrErr)
99 return BufferOrErr.takeError();
100 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800101 llvm::copy(Sec->Content, Buf->getBufferStart());
Seiya Nutad72a8a42019-11-25 12:29:58 +0900102
103 if (Error E = Buf->commit())
104 return E;
105 return Error::success();
106 }
107 }
108
109 return createStringError(object_error::parse_failed, "section '%s' not found",
110 SecName.str().c_str());
111}
112
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900113static Error addSection(StringRef SecName, StringRef Filename, Object &Obj) {
114 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
115 MemoryBuffer::getFile(Filename);
116 if (!BufOrErr)
117 return createFileError(Filename, errorCodeToError(BufOrErr.getError()));
118 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
119
120 std::pair<StringRef, StringRef> Pair = SecName.split(',');
121 StringRef TargetSegName = Pair.first;
122 Section Sec(TargetSegName, Pair.second);
123 Sec.Content = Obj.NewSectionsContents.save(Buf->getBuffer());
124
125 // Add the a section into an existing segment.
126 for (LoadCommand &LC : Obj.LoadCommands) {
127 Optional<StringRef> SegName = LC.getSegmentName();
128 if (SegName && SegName == TargetSegName) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800129 LC.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900130 return Error::success();
131 }
132 }
133
134 // There's no segment named TargetSegName. Create a new load command and
135 // Insert a new section into it.
136 LoadCommand &NewSegment = Obj.addSegment(TargetSegName);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800137 NewSegment.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900138 return Error::success();
139}
140
141// isValidMachOCannonicalName returns success if Name is a MachO cannonical name
142// ("<segment>,<section>") and lengths of both segment and section names are
143// valid.
144Error isValidMachOCannonicalName(StringRef Name) {
145 if (Name.count(',') != 1)
146 return createStringError(errc::invalid_argument,
147 "invalid section name '%s' (should be formatted "
148 "as '<segment name>,<section name>')",
149 Name.str().c_str());
150
151 std::pair<StringRef, StringRef> Pair = Name.split(',');
152 if (Pair.first.size() > 16)
153 return createStringError(errc::invalid_argument,
154 "too long segment name: '%s'",
155 Pair.first.str().c_str());
156 if (Pair.second.size() > 16)
157 return createStringError(errc::invalid_argument,
158 "too long section name: '%s'",
159 Pair.second.str().c_str());
160 return Error::success();
161}
162
Seiya Nuta4bc71012019-05-29 22:21:12 +0000163static Error handleArgs(const CopyConfig &Config, Object &Obj) {
164 if (Config.AllowBrokenLinks || !Config.BuildIdLinkDir.empty() ||
165 Config.BuildIdLinkInput || Config.BuildIdLinkOutput ||
166 !Config.SplitDWO.empty() || !Config.SymbolsPrefix.empty() ||
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900167 !Config.AllocSectionsPrefix.empty() || !Config.KeepSection.empty() ||
168 Config.NewSymbolVisibility || !Config.SymbolsToGlobalize.empty() ||
169 !Config.SymbolsToKeep.empty() || !Config.SymbolsToLocalize.empty() ||
170 !Config.SymbolsToWeaken.empty() || !Config.SymbolsToKeepGlobal.empty() ||
171 !Config.SectionsToRename.empty() ||
Seiya Nuta4bc71012019-05-29 22:21:12 +0000172 !Config.UnneededSymbolsToRemove.empty() ||
Fangrui Song671fb342019-10-02 12:41:25 +0000173 !Config.SetSectionAlignment.empty() || !Config.SetSectionFlags.empty() ||
Seiya Nutabc118302019-11-15 12:37:55 +0900174 Config.ExtractDWO || Config.KeepFileSymbols || Config.LocalizeHidden ||
175 Config.PreserveDates || Config.StripAllGNU || Config.StripDWO ||
176 Config.StripNonAlloc || Config.StripSections || Config.Weaken ||
Fangrui Song30ccee72019-11-18 15:25:04 -0800177 Config.DecompressDebugSections || Config.StripNonAlloc ||
178 Config.StripSections || Config.StripUnneeded ||
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -0800179 Config.DiscardMode == DiscardType::Locals ||
180 !Config.SymbolsToAdd.empty() || Config.EntryExpr) {
Seiya Nuta4bc71012019-05-29 22:21:12 +0000181 return createStringError(llvm::errc::invalid_argument,
182 "option not supported by llvm-objcopy for MachO");
183 }
Seiya Nuta7f19dd12019-10-28 15:40:37 +0900184 removeSections(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900185
186 // Mark symbols to determine which symbols are still needed.
187 if (Config.StripAll)
188 markSymbols(Config, Obj);
189
Fangrui Song28a5dc72019-11-13 13:10:15 -0800190 updateAndRemoveSymbols(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900191
192 if (Config.StripAll)
193 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800194 for (std::unique_ptr<Section> &Sec : LC.Sections)
195 Sec->Relocations.clear();
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900196
Seiya Nutad72a8a42019-11-25 12:29:58 +0900197 for (const StringRef &Flag : Config.DumpSection) {
198 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
199 StringRef SecName = SecPair.first;
200 StringRef File = SecPair.second;
201 if (Error E = dumpSectionToFile(SecName, File, Obj))
202 return E;
203 }
204
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900205 for (const auto &Flag : Config.AddSection) {
206 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
207 StringRef SecName = SecPair.first;
208 StringRef File = SecPair.second;
209 if (Error E = isValidMachOCannonicalName(SecName))
210 return E;
211 if (Error E = addSection(SecName, File, Obj))
212 return E;
213 }
214
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800215 for (StringRef RPath : Config.RPathToAdd) {
216 for (LoadCommand &LC : Obj.LoadCommands) {
217 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH &&
218 RPath == StringRef(reinterpret_cast<char *>(LC.Payload.data()),
219 LC.Payload.size())
220 .trim(0)) {
221 return createStringError(errc::invalid_argument,
222 "rpath " + RPath +
223 " would create a duplicate load command");
224 }
225 }
226 Obj.addLoadCommand(buildRPathLoadCommand(RPath));
227 }
Seiya Nuta4bc71012019-05-29 22:21:12 +0000228 return Error::success();
229}
230
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000231Error executeObjcopyOnBinary(const CopyConfig &Config,
232 object::MachOObjectFile &In, Buffer &Out) {
233 MachOReader Reader(In);
234 std::unique_ptr<Object> O = Reader.create();
Seiya Nuta4bc71012019-05-29 22:21:12 +0000235 if (!O)
236 return createFileError(
237 Config.InputFilename,
238 createStringError(object_error::parse_failed,
239 "unable to deserialize MachO object"));
240
241 if (Error E = handleArgs(Config, *O))
242 return createFileError(Config.InputFilename, std::move(E));
243
Seiya Nuta552bcb82019-08-19 21:05:31 +0000244 // TODO: Support 16KB pages which are employed in iOS arm64 binaries:
245 // https://github.com/llvm/llvm-project/commit/1bebb2832ee312d3b0316dacff457a7a29435edb
246 const uint64_t PageSize = 4096;
247
248 MachOWriter Writer(*O, In.is64Bit(), In.isLittleEndian(), PageSize, Out);
Seiya Nutab728e532019-06-08 01:22:54 +0000249 if (auto E = Writer.finalize())
250 return E;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000251 return Writer.write();
252}
253
254} // end namespace macho
255} // end namespace objcopy
256} // end namespace llvm