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/CommandLine.h" 33 #include "llvm/Support/Error.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/ErrorOr.h" 36 #include "llvm/Support/InitLLVM.h" 37 #include "llvm/Support/Memory.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Support/Process.h" 40 #include "llvm/Support/StringSaver.h" 41 #include "llvm/Support/WithColor.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <algorithm> 44 #include <cassert> 45 #include <cstdlib> 46 #include <memory> 47 #include <string> 48 #include <system_error> 49 #include <utility> 50 51 namespace llvm { 52 namespace objcopy { 53 54 // The name this program was invoked as. 55 StringRef ToolName; 56 57 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) { 58 WithColor::error(errs(), ToolName) << Message << "\n"; 59 exit(1); 60 } 61 62 LLVM_ATTRIBUTE_NORETURN void error(Error E) { 63 assert(E); 64 std::string Buf; 65 raw_string_ostream OS(Buf); 66 logAllUnhandledErrors(std::move(E), OS); 67 OS.flush(); 68 WithColor::error(errs(), ToolName) << Buf; 69 exit(1); 70 } 71 72 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) { 73 assert(EC); 74 error(createFileError(File, EC)); 75 } 76 77 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) { 78 assert(E); 79 std::string Buf; 80 raw_string_ostream OS(Buf); 81 logAllUnhandledErrors(std::move(E), OS); 82 OS.flush(); 83 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf; 84 exit(1); 85 } 86 87 ErrorSuccess reportWarning(Error E) { 88 assert(E); 89 WithColor::warning(errs(), ToolName) << toString(std::move(E)) << '\n'; 90 return Error::success(); 91 } 92 93 } // end namespace objcopy 94 } // end namespace llvm 95 96 using namespace llvm; 97 using namespace llvm::object; 98 using namespace llvm::objcopy; 99 100 // For regular archives this function simply calls llvm::writeArchive, 101 // For thin archives it writes the archive file itself as well as its members. 102 static Error deepWriteArchive(StringRef ArcName, 103 ArrayRef<NewArchiveMember> NewMembers, 104 bool WriteSymtab, object::Archive::Kind Kind, 105 bool Deterministic, bool Thin) { 106 if (Error E = writeArchive(ArcName, NewMembers, WriteSymtab, Kind, 107 Deterministic, Thin)) 108 return createFileError(ArcName, std::move(E)); 109 110 if (!Thin) 111 return Error::success(); 112 113 for (const NewArchiveMember &Member : NewMembers) { 114 // Internally, FileBuffer will use the buffer created by 115 // FileOutputBuffer::create, for regular files (that is the case for 116 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer. 117 // OnDiskBuffer uses a temporary file and then renames it. So in reality 118 // there is no inefficiency / duplicated in-memory buffers in this case. For 119 // now in-memory buffers can not be completely avoided since 120 // NewArchiveMember still requires them even though writeArchive does not 121 // write them on disk. 122 FileBuffer FB(Member.MemberName); 123 if (Error E = FB.allocate(Member.Buf->getBufferSize())) 124 return E; 125 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(), 126 FB.getBufferStart()); 127 if (Error E = FB.commit()) 128 return E; 129 } 130 return Error::success(); 131 } 132 133 /// The function executeObjcopyOnIHex does the dispatch based on the format 134 /// of the output specified by the command line options. 135 static Error executeObjcopyOnIHex(const CopyConfig &Config, MemoryBuffer &In, 136 Buffer &Out) { 137 // TODO: support output formats other than ELF. 138 return elf::executeObjcopyOnIHex(Config, In, Out); 139 } 140 141 /// The function executeObjcopyOnRawBinary does the dispatch based on the format 142 /// of the output specified by the command line options. 143 static Error executeObjcopyOnRawBinary(const CopyConfig &Config, 144 MemoryBuffer &In, Buffer &Out) { 145 switch (Config.OutputFormat) { 146 case FileFormat::ELF: 147 // FIXME: Currently, we call elf::executeObjcopyOnRawBinary even if the 148 // output format is binary/ihex or it's not given. This behavior differs from 149 // GNU objcopy. See https://bugs.llvm.org/show_bug.cgi?id=42171 for details. 150 case FileFormat::Binary: 151 case FileFormat::IHex: 152 case FileFormat::Unspecified: 153 return elf::executeObjcopyOnRawBinary(Config, In, Out); 154 } 155 156 llvm_unreachable("unsupported output format"); 157 } 158 159 /// The function executeObjcopyOnBinary does the dispatch based on the format 160 /// of the input binary (ELF, MachO or COFF). 161 static Error executeObjcopyOnBinary(const CopyConfig &Config, 162 object::Binary &In, Buffer &Out) { 163 if (auto *ELFBinary = dyn_cast<object::ELFObjectFileBase>(&In)) 164 return elf::executeObjcopyOnBinary(Config, *ELFBinary, Out); 165 else if (auto *COFFBinary = dyn_cast<object::COFFObjectFile>(&In)) 166 return coff::executeObjcopyOnBinary(Config, *COFFBinary, Out); 167 else if (auto *MachOBinary = dyn_cast<object::MachOObjectFile>(&In)) 168 return macho::executeObjcopyOnBinary(Config, *MachOBinary, Out); 169 else 170 return createStringError(object_error::invalid_file_type, 171 "unsupported object file format"); 172 } 173 174 static Error executeObjcopyOnArchive(const CopyConfig &Config, 175 const Archive &Ar) { 176 std::vector<NewArchiveMember> NewArchiveMembers; 177 Error Err = Error::success(); 178 for (const Archive::Child &Child : Ar.children(Err)) { 179 Expected<StringRef> ChildNameOrErr = Child.getName(); 180 if (!ChildNameOrErr) 181 return createFileError(Ar.getFileName(), ChildNameOrErr.takeError()); 182 183 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 184 if (!ChildOrErr) 185 return createFileError(Ar.getFileName() + "(" + *ChildNameOrErr + ")", 186 ChildOrErr.takeError()); 187 188 MemBuffer MB(ChildNameOrErr.get()); 189 if (Error E = executeObjcopyOnBinary(Config, *ChildOrErr->get(), MB)) 190 return E; 191 192 Expected<NewArchiveMember> Member = 193 NewArchiveMember::getOldMember(Child, Config.DeterministicArchives); 194 if (!Member) 195 return createFileError(Ar.getFileName(), Member.takeError()); 196 Member->Buf = MB.releaseMemoryBuffer(); 197 Member->MemberName = Member->Buf->getBufferIdentifier(); 198 NewArchiveMembers.push_back(std::move(*Member)); 199 } 200 if (Err) 201 return createFileError(Config.InputFilename, std::move(Err)); 202 203 return deepWriteArchive(Config.OutputFilename, NewArchiveMembers, 204 Ar.hasSymbolTable(), Ar.kind(), 205 Config.DeterministicArchives, Ar.isThin()); 206 } 207 208 static Error restoreStatOnFile(StringRef Filename, 209 const sys::fs::file_status &Stat, 210 bool PreserveDates) { 211 int FD; 212 213 // Writing to stdout should not be treated as an error here, just 214 // do not set access/modification times or permissions. 215 if (Filename == "-") 216 return Error::success(); 217 218 if (auto EC = 219 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting)) 220 return createFileError(Filename, EC); 221 222 if (PreserveDates) 223 if (auto EC = sys::fs::setLastAccessAndModificationTime( 224 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime())) 225 return createFileError(Filename, EC); 226 227 sys::fs::file_status OStat; 228 if (std::error_code EC = sys::fs::status(FD, OStat)) 229 return createFileError(Filename, EC); 230 if (OStat.type() == sys::fs::file_type::regular_file) 231 #ifdef _WIN32 232 if (auto EC = sys::fs::setPermissions( 233 Filename, static_cast<sys::fs::perms>(Stat.permissions() & 234 ~sys::fs::getUmask()))) 235 #else 236 if (auto EC = sys::fs::setPermissions( 237 FD, static_cast<sys::fs::perms>(Stat.permissions() & 238 ~sys::fs::getUmask()))) 239 #endif 240 return createFileError(Filename, EC); 241 242 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) 243 return createFileError(Filename, EC); 244 245 return Error::success(); 246 } 247 248 /// The function executeObjcopy does the higher level dispatch based on the type 249 /// of input (raw binary, archive or single object file) and takes care of the 250 /// format-agnostic modifications, i.e. preserving dates. 251 static Error executeObjcopy(const CopyConfig &Config) { 252 sys::fs::file_status Stat; 253 if (Config.InputFilename != "-") { 254 if (auto EC = sys::fs::status(Config.InputFilename, Stat)) 255 return createFileError(Config.InputFilename, EC); 256 } else { 257 Stat.permissions(static_cast<sys::fs::perms>(0777)); 258 } 259 260 typedef Error (*ProcessRawFn)(const CopyConfig &, MemoryBuffer &, Buffer &); 261 ProcessRawFn ProcessRaw; 262 switch (Config.InputFormat) { 263 case FileFormat::Binary: 264 ProcessRaw = executeObjcopyOnRawBinary; 265 break; 266 case FileFormat::IHex: 267 ProcessRaw = executeObjcopyOnIHex; 268 break; 269 default: 270 ProcessRaw = nullptr; 271 } 272 273 if (ProcessRaw) { 274 auto BufOrErr = MemoryBuffer::getFileOrSTDIN(Config.InputFilename); 275 if (!BufOrErr) 276 return createFileError(Config.InputFilename, BufOrErr.getError()); 277 FileBuffer FB(Config.OutputFilename); 278 if (Error E = ProcessRaw(Config, *BufOrErr->get(), FB)) 279 return E; 280 } else { 281 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr = 282 createBinary(Config.InputFilename); 283 if (!BinaryOrErr) 284 return createFileError(Config.InputFilename, BinaryOrErr.takeError()); 285 286 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) { 287 if (Error E = executeObjcopyOnArchive(Config, *Ar)) 288 return E; 289 } else { 290 FileBuffer FB(Config.OutputFilename); 291 if (Error E = executeObjcopyOnBinary(Config, 292 *BinaryOrErr.get().getBinary(), FB)) 293 return E; 294 } 295 } 296 297 if (Error E = 298 restoreStatOnFile(Config.OutputFilename, Stat, Config.PreserveDates)) 299 return E; 300 301 if (!Config.SplitDWO.empty()) { 302 Stat.permissions(static_cast<sys::fs::perms>(0666)); 303 if (Error E = 304 restoreStatOnFile(Config.SplitDWO, Stat, Config.PreserveDates)) 305 return E; 306 } 307 308 return Error::success(); 309 } 310 311 int main(int argc, char **argv) { 312 InitLLVM X(argc, argv); 313 ToolName = argv[0]; 314 bool IsStrip = sys::path::stem(ToolName).contains("strip"); 315 316 // Expand response files. 317 // TODO: Move these lines, which are copied from lib/Support/CommandLine.cpp, 318 // into a separate function in the CommandLine library and call that function 319 // here. This is duplicated code. 320 SmallVector<const char *, 20> NewArgv(argv, argv + argc); 321 BumpPtrAllocator A; 322 StringSaver Saver(A); 323 cl::ExpandResponseFiles(Saver, 324 Triple(sys::getProcessTriple()).isOSWindows() 325 ? cl::TokenizeWindowsCommandLine 326 : cl::TokenizeGNUCommandLine, 327 NewArgv); 328 329 auto Args = makeArrayRef(NewArgv).drop_front(); 330 331 Expected<DriverConfig> DriverConfig = 332 IsStrip ? parseStripOptions(Args, reportWarning) 333 : parseObjcopyOptions(Args); 334 if (!DriverConfig) { 335 logAllUnhandledErrors(DriverConfig.takeError(), 336 WithColor::error(errs(), ToolName)); 337 return 1; 338 } 339 for (const CopyConfig &CopyConfig : DriverConfig->CopyConfigs) { 340 if (Error E = executeObjcopy(CopyConfig)) { 341 logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName)); 342 return 1; 343 } 344 } 345 346 return 0; 347 } 348