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