1 //===- llvm-objcopy.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.h"
10 #include "Buffer.h"
11 #include "CopyConfig.h"
12 #include "ELF/ELFObjcopy.h"
13 #include "COFF/COFFObjcopy.h"
14 #include "MachO/MachOObjcopy.h"
15 
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ArchiveWriter.h"
22 #include "llvm/Object/Binary.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Object/ELFObjectFile.h"
25 #include "llvm/Object/ELFTypes.h"
26 #include "llvm/Object/Error.h"
27 #include "llvm/Object/MachO.h"
28 #include "llvm/Option/Arg.h"
29 #include "llvm/Option/ArgList.h"
30 #include "llvm/Option/Option.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ErrorOr.h"
35 #include "llvm/Support/InitLLVM.h"
36 #include "llvm/Support/Memory.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/WithColor.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <algorithm>
42 #include <cassert>
43 #include <cstdlib>
44 #include <memory>
45 #include <string>
46 #include <system_error>
47 #include <utility>
48 
49 namespace llvm {
50 namespace objcopy {
51 
52 // The name this program was invoked as.
53 StringRef ToolName;
54 
55 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
56   WithColor::error(errs(), ToolName) << Message << "\n";
57   exit(1);
58 }
59 
60 LLVM_ATTRIBUTE_NORETURN void error(Error E) {
61   assert(E);
62   std::string Buf;
63   raw_string_ostream OS(Buf);
64   logAllUnhandledErrors(std::move(E), OS);
65   OS.flush();
66   WithColor::error(errs(), ToolName) << Buf;
67   exit(1);
68 }
69 
70 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
71   assert(EC);
72   error(createFileError(File, EC));
73 }
74 
75 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
76   assert(E);
77   std::string Buf;
78   raw_string_ostream OS(Buf);
79   logAllUnhandledErrors(std::move(E), OS);
80   OS.flush();
81   WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
82   exit(1);
83 }
84 
85 ErrorSuccess reportWarning(Error E) {
86   assert(E);
87   WithColor::warning(errs(), ToolName) << toString(std::move(E));
88   return Error::success();
89 }
90 
91 } // end namespace objcopy
92 } // end namespace llvm
93 
94 using namespace llvm;
95 using namespace llvm::object;
96 using namespace llvm::objcopy;
97 
98 // For regular archives this function simply calls llvm::writeArchive,
99 // For thin archives it writes the archive file itself as well as its members.
100 static Error deepWriteArchive(StringRef ArcName,
101                               ArrayRef<NewArchiveMember> NewMembers,
102                               bool WriteSymtab, object::Archive::Kind Kind,
103                               bool Deterministic, bool Thin) {
104   if (Error E = writeArchive(ArcName, NewMembers, WriteSymtab, Kind,
105                              Deterministic, Thin))
106     return createFileError(ArcName, std::move(E));
107 
108   if (!Thin)
109     return Error::success();
110 
111   for (const NewArchiveMember &Member : NewMembers) {
112     // Internally, FileBuffer will use the buffer created by
113     // FileOutputBuffer::create, for regular files (that is the case for
114     // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer.
115     // OnDiskBuffer uses a temporary file and then renames it. So in reality
116     // there is no inefficiency / duplicated in-memory buffers in this case. For
117     // now in-memory buffers can not be completely avoided since
118     // NewArchiveMember still requires them even though writeArchive does not
119     // write them on disk.
120     FileBuffer FB(Member.MemberName);
121     if (Error E = FB.allocate(Member.Buf->getBufferSize()))
122       return E;
123     std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(),
124               FB.getBufferStart());
125     if (Error E = FB.commit())
126       return E;
127   }
128   return Error::success();
129 }
130 
131 /// The function executeObjcopyOnIHex does the dispatch based on the format
132 /// of the output specified by the command line options.
133 static Error executeObjcopyOnIHex(const CopyConfig &Config, MemoryBuffer &In,
134                                   Buffer &Out) {
135   // TODO: support output formats other than ELF.
136   return elf::executeObjcopyOnIHex(Config, In, Out);
137 }
138 
139 /// The function executeObjcopyOnRawBinary does the dispatch based on the format
140 /// of the output specified by the command line options.
141 static Error executeObjcopyOnRawBinary(const CopyConfig &Config,
142                                        MemoryBuffer &In, Buffer &Out) {
143   // TODO: llvm-objcopy should parse CopyConfig.OutputFormat to recognize
144   // formats other than ELF / "binary" and invoke
145   // elf::executeObjcopyOnRawBinary, macho::executeObjcopyOnRawBinary or
146   // coff::executeObjcopyOnRawBinary accordingly.
147   return elf::executeObjcopyOnRawBinary(Config, In, Out);
148 }
149 
150 /// The function executeObjcopyOnBinary does the dispatch based on the format
151 /// of the input binary (ELF, MachO or COFF).
152 static Error executeObjcopyOnBinary(const CopyConfig &Config,
153                                     object::Binary &In, Buffer &Out) {
154   if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In))
155     return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out);
156   else if (auto *COFFBinary = dyn_cast<object::COFFObjectFile>(&In))
157     return coff::executeObjcopyOnBinary(Config, *COFFBinary, Out);
158   else if (auto *MachOBinary = dyn_cast<object::MachOObjectFile>(&In))
159     return macho::executeObjcopyOnBinary(Config, *MachOBinary, Out);
160   else
161     return createStringError(object_error::invalid_file_type,
162                              "unsupported object file format");
163 }
164 
165 static Error executeObjcopyOnArchive(const CopyConfig &Config,
166                                      const Archive &Ar) {
167   std::vector<NewArchiveMember> NewArchiveMembers;
168   Error Err = Error::success();
169   for (const Archive::Child &Child : Ar.children(Err)) {
170     Expected<StringRef> ChildNameOrErr = Child.getName();
171     if (!ChildNameOrErr)
172       return createFileError(Ar.getFileName(), ChildNameOrErr.takeError());
173 
174     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
175     if (!ChildOrErr)
176       return createFileError(Ar.getFileName() + "(" + *ChildNameOrErr + ")",
177                              ChildOrErr.takeError());
178 
179     MemBuffer MB(ChildNameOrErr.get());
180     if (Error E = executeObjcopyOnBinary(Config, *ChildOrErr->get(), MB))
181       return E;
182 
183     Expected<NewArchiveMember> Member =
184         NewArchiveMember::getOldMember(Child, Config.DeterministicArchives);
185     if (!Member)
186       return createFileError(Ar.getFileName(), Member.takeError());
187     Member->Buf = MB.releaseMemoryBuffer();
188     Member->MemberName = Member->Buf->getBufferIdentifier();
189     NewArchiveMembers.push_back(std::move(*Member));
190   }
191   if (Err)
192     return createFileError(Config.InputFilename, std::move(Err));
193 
194   return deepWriteArchive(Config.OutputFilename, NewArchiveMembers,
195                           Ar.hasSymbolTable(), Ar.kind(),
196                           Config.DeterministicArchives, Ar.isThin());
197 }
198 
199 static Error restoreDateOnFile(StringRef Filename,
200                                const sys::fs::file_status &Stat) {
201   int FD;
202 
203   if (auto EC =
204           sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
205     return createFileError(Filename, EC);
206 
207   if (auto EC = sys::fs::setLastAccessAndModificationTime(
208           FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
209     return createFileError(Filename, EC);
210 
211   if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
212     return createFileError(Filename, EC);
213 
214   return Error::success();
215 }
216 
217 /// The function executeObjcopy does the higher level dispatch based on the type
218 /// of input (raw binary, archive or single object file) and takes care of the
219 /// format-agnostic modifications, i.e. preserving dates.
220 static Error executeObjcopy(const CopyConfig &Config) {
221   sys::fs::file_status Stat;
222   if (Config.PreserveDates)
223     if (auto EC = sys::fs::status(Config.InputFilename, Stat))
224       return createFileError(Config.InputFilename, EC);
225 
226   typedef Error (*ProcessRawFn)(const CopyConfig &, MemoryBuffer &, Buffer &);
227   auto ProcessRaw = StringSwitch<ProcessRawFn>(Config.InputFormat)
228                         .Case("binary", executeObjcopyOnRawBinary)
229                         .Case("ihex", executeObjcopyOnIHex)
230                         .Default(nullptr);
231 
232   if (ProcessRaw) {
233     auto BufOrErr = MemoryBuffer::getFileOrSTDIN(Config.InputFilename);
234     if (!BufOrErr)
235       return createFileError(Config.InputFilename, BufOrErr.getError());
236     FileBuffer FB(Config.OutputFilename);
237     if (Error E = ProcessRaw(Config, *BufOrErr->get(), FB))
238       return E;
239   } else {
240     Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
241         createBinary(Config.InputFilename);
242     if (!BinaryOrErr)
243       return createFileError(Config.InputFilename, BinaryOrErr.takeError());
244 
245     if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) {
246       if (Error E = executeObjcopyOnArchive(Config, *Ar))
247         return E;
248     } else {
249       FileBuffer FB(Config.OutputFilename);
250       if (Error E = executeObjcopyOnBinary(Config,
251                                            *BinaryOrErr.get().getBinary(), FB))
252         return E;
253     }
254   }
255 
256   if (Config.PreserveDates) {
257     if (Error E = restoreDateOnFile(Config.OutputFilename, Stat))
258       return E;
259     if (!Config.SplitDWO.empty())
260       if (Error E = restoreDateOnFile(Config.SplitDWO, Stat))
261         return E;
262   }
263 
264   return Error::success();
265 }
266 
267 int main(int argc, char **argv) {
268   InitLLVM X(argc, argv);
269   ToolName = argv[0];
270   bool IsStrip = sys::path::stem(ToolName).contains("strip");
271   Expected<DriverConfig> DriverConfig =
272       IsStrip ? parseStripOptions(makeArrayRef(argv + 1, argc), reportWarning)
273               : parseObjcopyOptions(makeArrayRef(argv + 1, argc));
274   if (!DriverConfig) {
275     logAllUnhandledErrors(DriverConfig.takeError(),
276                           WithColor::error(errs(), ToolName));
277     return 1;
278   }
279   for (const CopyConfig &CopyConfig : DriverConfig->CopyConfigs) {
280     if (Error E = executeObjcopy(CopyConfig)) {
281       logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
282       return 1;
283     }
284   }
285 
286   return 0;
287 }
288