blob: 17d84549544bdaa66df929f477b62b2af872cfa3 [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
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -070023static Error removeSections(const CopyConfig &Config, Object &Obj) {
Alexander Shaposhnikova7abe8d2020-05-17 20:46:17 -070024 SectionPred RemovePred = [](const std::unique_ptr<Section> &) {
25 return false;
26 };
Seiya Nuta7f19dd12019-10-28 15:40:37 +090027
Seiya Nutabc118302019-11-15 12:37:55 +090028 if (!Config.ToRemove.empty()) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080029 RemovePred = [&Config, RemovePred](const std::unique_ptr<Section> &Sec) {
30 return Config.ToRemove.matches(Sec->CanonicalName);
Seiya Nutabc118302019-11-15 12:37:55 +090031 };
32 }
33
Fangrui Song30ccee72019-11-18 15:25:04 -080034 if (Config.StripAll || Config.StripDebug) {
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090035 // Remove all debug sections.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080036 RemovePred = [RemovePred](const std::unique_ptr<Section> &Sec) {
37 if (Sec->Segname == "__DWARF")
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090038 return true;
39
40 return RemovePred(Sec);
41 };
42 }
43
Seiya Nuta7f19dd12019-10-28 15:40:37 +090044 if (!Config.OnlySection.empty()) {
Seiya Nutabc118302019-11-15 12:37:55 +090045 // Overwrite RemovePred because --only-section takes priority.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080046 RemovePred = [&Config](const std::unique_ptr<Section> &Sec) {
47 return !Config.OnlySection.matches(Sec->CanonicalName);
Seiya Nuta7f19dd12019-10-28 15:40:37 +090048 };
49 }
50
51 return Obj.removeSections(RemovePred);
52}
Seiya Nuta4bc71012019-05-29 22:21:12 +000053
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090054static void markSymbols(const CopyConfig &Config, Object &Obj) {
55 // Symbols referenced from the indirect symbol table must not be removed.
56 for (IndirectSymbolEntry &ISE : Obj.IndirectSymTable.Symbols)
57 if (ISE.Symbol)
58 (*ISE.Symbol)->Referenced = true;
59}
60
Fangrui Song28a5dc72019-11-13 13:10:15 -080061static void updateAndRemoveSymbols(const CopyConfig &Config, Object &Obj) {
62 for (SymbolEntry &Sym : Obj.SymTable) {
63 auto I = Config.SymbolsToRename.find(Sym.Name);
64 if (I != Config.SymbolsToRename.end())
Benjamin Krameradcd0262020-01-28 20:23:46 +010065 Sym.Name = std::string(I->getValue());
Fangrui Song28a5dc72019-11-13 13:10:15 -080066 }
67
Alexander Shaposhnikov842a8cc2020-05-26 16:49:56 -070068 auto RemovePred = [Config, &Obj](const std::unique_ptr<SymbolEntry> &N) {
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090069 if (N->Referenced)
70 return false;
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -080071 if (Config.StripAll)
72 return true;
73 if (Config.DiscardMode == DiscardType::All && !(N->n_type & MachO::N_EXT))
74 return true;
Alexander Shaposhnikov842a8cc2020-05-26 16:49:56 -070075 // This behavior is consistent with cctools' strip.
76 if (Config.StripSwiftSymbols && (Obj.Header.Flags & MachO::MH_DYLDLINK) &&
77 Obj.SwiftVersion && *Obj.SwiftVersion && N->isSwiftSymbol())
78 return true;
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -080079 return false;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +090080 };
81
82 Obj.SymTable.removeSymbols(RemovePred);
83}
84
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080085static LoadCommand buildRPathLoadCommand(StringRef Path) {
86 LoadCommand LC;
87 MachO::rpath_command RPathLC;
88 RPathLC.cmd = MachO::LC_RPATH;
89 RPathLC.path = sizeof(MachO::rpath_command);
Alexander Shaposhnikovc966ed82020-06-11 19:55:04 -070090 RPathLC.cmdsize = alignTo(sizeof(MachO::rpath_command) + Path.size() + 1, 8);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -080091 LC.MachOLoadCommand.rpath_command_data = RPathLC;
92 LC.Payload.assign(RPathLC.cmdsize - sizeof(MachO::rpath_command), 0);
93 std::copy(Path.begin(), Path.end(), LC.Payload.begin());
94 return LC;
95}
96
Seiya Nutad72a8a42019-11-25 12:29:58 +090097static Error dumpSectionToFile(StringRef SecName, StringRef Filename,
98 Object &Obj) {
99 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800100 for (const std::unique_ptr<Section> &Sec : LC.Sections) {
101 if (Sec->CanonicalName == SecName) {
Seiya Nutad72a8a42019-11-25 12:29:58 +0900102 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800103 FileOutputBuffer::create(Filename, Sec->Content.size());
Seiya Nutad72a8a42019-11-25 12:29:58 +0900104 if (!BufferOrErr)
105 return BufferOrErr.takeError();
106 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800107 llvm::copy(Sec->Content, Buf->getBufferStart());
Seiya Nutad72a8a42019-11-25 12:29:58 +0900108
109 if (Error E = Buf->commit())
110 return E;
111 return Error::success();
112 }
113 }
114
115 return createStringError(object_error::parse_failed, "section '%s' not found",
116 SecName.str().c_str());
117}
118
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900119static Error addSection(StringRef SecName, StringRef Filename, Object &Obj) {
120 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
121 MemoryBuffer::getFile(Filename);
122 if (!BufOrErr)
123 return createFileError(Filename, errorCodeToError(BufOrErr.getError()));
124 std::unique_ptr<MemoryBuffer> Buf = std::move(*BufOrErr);
125
126 std::pair<StringRef, StringRef> Pair = SecName.split(',');
127 StringRef TargetSegName = Pair.first;
128 Section Sec(TargetSegName, Pair.second);
129 Sec.Content = Obj.NewSectionsContents.save(Buf->getBuffer());
130
131 // Add the a section into an existing segment.
132 for (LoadCommand &LC : Obj.LoadCommands) {
133 Optional<StringRef> SegName = LC.getSegmentName();
134 if (SegName && SegName == TargetSegName) {
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800135 LC.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900136 return Error::success();
137 }
138 }
139
140 // There's no segment named TargetSegName. Create a new load command and
141 // Insert a new section into it.
142 LoadCommand &NewSegment = Obj.addSegment(TargetSegName);
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800143 NewSegment.Sections.push_back(std::make_unique<Section>(Sec));
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900144 return Error::success();
145}
146
147// isValidMachOCannonicalName returns success if Name is a MachO cannonical name
148// ("<segment>,<section>") and lengths of both segment and section names are
149// valid.
150Error isValidMachOCannonicalName(StringRef Name) {
151 if (Name.count(',') != 1)
152 return createStringError(errc::invalid_argument,
153 "invalid section name '%s' (should be formatted "
154 "as '<segment name>,<section name>')",
155 Name.str().c_str());
156
157 std::pair<StringRef, StringRef> Pair = Name.split(',');
158 if (Pair.first.size() > 16)
159 return createStringError(errc::invalid_argument,
160 "too long segment name: '%s'",
161 Pair.first.str().c_str());
162 if (Pair.second.size() > 16)
163 return createStringError(errc::invalid_argument,
164 "too long section name: '%s'",
165 Pair.second.str().c_str());
166 return Error::success();
167}
168
Seiya Nuta4bc71012019-05-29 22:21:12 +0000169static Error handleArgs(const CopyConfig &Config, Object &Obj) {
170 if (Config.AllowBrokenLinks || !Config.BuildIdLinkDir.empty() ||
171 Config.BuildIdLinkInput || Config.BuildIdLinkOutput ||
172 !Config.SplitDWO.empty() || !Config.SymbolsPrefix.empty() ||
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900173 !Config.AllocSectionsPrefix.empty() || !Config.KeepSection.empty() ||
174 Config.NewSymbolVisibility || !Config.SymbolsToGlobalize.empty() ||
175 !Config.SymbolsToKeep.empty() || !Config.SymbolsToLocalize.empty() ||
176 !Config.SymbolsToWeaken.empty() || !Config.SymbolsToKeepGlobal.empty() ||
177 !Config.SectionsToRename.empty() ||
Seiya Nuta4bc71012019-05-29 22:21:12 +0000178 !Config.UnneededSymbolsToRemove.empty() ||
Fangrui Song671fb342019-10-02 12:41:25 +0000179 !Config.SetSectionAlignment.empty() || !Config.SetSectionFlags.empty() ||
Fangrui Songb14e9e32020-03-24 15:38:48 +0800180 Config.ExtractDWO || Config.LocalizeHidden || Config.PreserveDates ||
181 Config.StripAllGNU || Config.StripDWO || Config.StripNonAlloc ||
182 Config.StripSections || Config.Weaken || Config.DecompressDebugSections ||
183 Config.StripNonAlloc || Config.StripSections || Config.StripUnneeded ||
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -0800184 Config.DiscardMode == DiscardType::Locals ||
185 !Config.SymbolsToAdd.empty() || Config.EntryExpr) {
Seiya Nuta4bc71012019-05-29 22:21:12 +0000186 return createStringError(llvm::errc::invalid_argument,
187 "option not supported by llvm-objcopy for MachO");
188 }
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700189
Sameer Arora12e5b022020-06-05 10:47:05 -0700190 // Dump sections before add/remove for compatibility with GNU objcopy.
191 for (StringRef Flag : Config.DumpSection) {
192 StringRef SectionName;
193 StringRef FileName;
194 std::tie(SectionName, FileName) = Flag.split('=');
195 if (Error E = dumpSectionToFile(SectionName, FileName, Obj))
196 return E;
197 }
198
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700199 if (Error E = removeSections(Config, Obj))
200 return E;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900201
202 // Mark symbols to determine which symbols are still needed.
203 if (Config.StripAll)
204 markSymbols(Config, Obj);
205
Fangrui Song28a5dc72019-11-13 13:10:15 -0800206 updateAndRemoveSymbols(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900207
208 if (Config.StripAll)
209 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800210 for (std::unique_ptr<Section> &Sec : LC.Sections)
211 Sec->Relocations.clear();
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900212
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900213 for (const auto &Flag : Config.AddSection) {
214 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
215 StringRef SecName = SecPair.first;
216 StringRef File = SecPair.second;
217 if (Error E = isValidMachOCannonicalName(SecName))
218 return E;
219 if (Error E = addSection(SecName, File, Obj))
220 return E;
221 }
222
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800223 for (StringRef RPath : Config.RPathToAdd) {
224 for (LoadCommand &LC : Obj.LoadCommands) {
225 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH &&
226 RPath == StringRef(reinterpret_cast<char *>(LC.Payload.data()),
227 LC.Payload.size())
228 .trim(0)) {
229 return createStringError(errc::invalid_argument,
230 "rpath " + RPath +
231 " would create a duplicate load command");
232 }
233 }
234 Obj.addLoadCommand(buildRPathLoadCommand(RPath));
235 }
Seiya Nuta4bc71012019-05-29 22:21:12 +0000236 return Error::success();
237}
238
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000239Error executeObjcopyOnBinary(const CopyConfig &Config,
240 object::MachOObjectFile &In, Buffer &Out) {
241 MachOReader Reader(In);
242 std::unique_ptr<Object> O = Reader.create();
Seiya Nuta4bc71012019-05-29 22:21:12 +0000243 if (!O)
244 return createFileError(
245 Config.InputFilename,
246 createStringError(object_error::parse_failed,
247 "unable to deserialize MachO object"));
248
249 if (Error E = handleArgs(Config, *O))
250 return createFileError(Config.InputFilename, std::move(E));
251
Seiya Nuta552bcb82019-08-19 21:05:31 +0000252 // TODO: Support 16KB pages which are employed in iOS arm64 binaries:
253 // https://github.com/llvm/llvm-project/commit/1bebb2832ee312d3b0316dacff457a7a29435edb
254 const uint64_t PageSize = 4096;
255
256 MachOWriter Writer(*O, In.is64Bit(), In.isLittleEndian(), PageSize, Out);
Seiya Nutab728e532019-06-08 01:22:54 +0000257 if (auto E = Writer.finalize())
258 return E;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000259 return Writer.write();
260}
261
262} // end namespace macho
263} // end namespace objcopy
264} // end namespace llvm