blob: c2743748fa1339d22341adb91ddc7c0ea8a09041 [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 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() ||
Fangrui Songb14e9e32020-03-24 15:38:48 +0800174 Config.ExtractDWO || Config.LocalizeHidden || Config.PreserveDates ||
175 Config.StripAllGNU || Config.StripDWO || Config.StripNonAlloc ||
176 Config.StripSections || Config.Weaken || Config.DecompressDebugSections ||
177 Config.StripNonAlloc || Config.StripSections || Config.StripUnneeded ||
Alexander Shaposhnikovf79b81f2020-02-26 11:32:44 -0800178 Config.DiscardMode == DiscardType::Locals ||
179 !Config.SymbolsToAdd.empty() || Config.EntryExpr) {
Seiya Nuta4bc71012019-05-29 22:21:12 +0000180 return createStringError(llvm::errc::invalid_argument,
181 "option not supported by llvm-objcopy for MachO");
182 }
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700183
184 if (Error E = removeSections(Config, Obj))
185 return E;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900186
187 // Mark symbols to determine which symbols are still needed.
188 if (Config.StripAll)
189 markSymbols(Config, Obj);
190
Fangrui Song28a5dc72019-11-13 13:10:15 -0800191 updateAndRemoveSymbols(Config, Obj);
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900192
193 if (Config.StripAll)
194 for (LoadCommand &LC : Obj.LoadCommands)
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -0800195 for (std::unique_ptr<Section> &Sec : LC.Sections)
196 Sec->Relocations.clear();
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900197
Seiya Nutad72a8a42019-11-25 12:29:58 +0900198 for (const StringRef &Flag : Config.DumpSection) {
199 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
200 StringRef SecName = SecPair.first;
201 StringRef File = SecPair.second;
202 if (Error E = dumpSectionToFile(SecName, File, Obj))
203 return E;
204 }
205
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900206 for (const auto &Flag : Config.AddSection) {
207 std::pair<StringRef, StringRef> SecPair = Flag.split("=");
208 StringRef SecName = SecPair.first;
209 StringRef File = SecPair.second;
210 if (Error E = isValidMachOCannonicalName(SecName))
211 return E;
212 if (Error E = addSection(SecName, File, Obj))
213 return E;
214 }
215
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800216 for (StringRef RPath : Config.RPathToAdd) {
217 for (LoadCommand &LC : Obj.LoadCommands) {
218 if (LC.MachOLoadCommand.load_command_data.cmd == MachO::LC_RPATH &&
219 RPath == StringRef(reinterpret_cast<char *>(LC.Payload.data()),
220 LC.Payload.size())
221 .trim(0)) {
222 return createStringError(errc::invalid_argument,
223 "rpath " + RPath +
224 " would create a duplicate load command");
225 }
226 }
227 Obj.addLoadCommand(buildRPathLoadCommand(RPath));
228 }
Seiya Nuta4bc71012019-05-29 22:21:12 +0000229 return Error::success();
230}
231
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000232Error executeObjcopyOnBinary(const CopyConfig &Config,
233 object::MachOObjectFile &In, Buffer &Out) {
234 MachOReader Reader(In);
235 std::unique_ptr<Object> O = Reader.create();
Seiya Nuta4bc71012019-05-29 22:21:12 +0000236 if (!O)
237 return createFileError(
238 Config.InputFilename,
239 createStringError(object_error::parse_failed,
240 "unable to deserialize MachO object"));
241
242 if (Error E = handleArgs(Config, *O))
243 return createFileError(Config.InputFilename, std::move(E));
244
Seiya Nuta552bcb82019-08-19 21:05:31 +0000245 // TODO: Support 16KB pages which are employed in iOS arm64 binaries:
246 // https://github.com/llvm/llvm-project/commit/1bebb2832ee312d3b0316dacff457a7a29435edb
247 const uint64_t PageSize = 4096;
248
249 MachOWriter Writer(*O, In.is64Bit(), In.isLittleEndian(), PageSize, Out);
Seiya Nutab728e532019-06-08 01:22:54 +0000250 if (auto E = Writer.finalize())
251 return E;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000252 return Writer.write();
253}
254
255} // end namespace macho
256} // end namespace objcopy
257} // end namespace llvm