1 //===- llvm-objcopy.cpp ---------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm-objcopy.h" 11 12 #include "Object.h" 13 #include "llvm/ADT/BitmaskEnum.h" 14 #include "llvm/ADT/Optional.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/BinaryFormat/ELF.h" 20 #include "llvm/Object/Archive.h" 21 #include "llvm/Object/ArchiveWriter.h" 22 #include "llvm/Object/Binary.h" 23 #include "llvm/Object/ELFObjectFile.h" 24 #include "llvm/Object/ELFTypes.h" 25 #include "llvm/Object/Error.h" 26 #include "llvm/Option/Arg.h" 27 #include "llvm/Option/ArgList.h" 28 #include "llvm/Option/Option.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Compiler.h" 32 #include "llvm/Support/Error.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/ErrorOr.h" 35 #include "llvm/Support/FileOutputBuffer.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/WithColor.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <algorithm> 43 #include <cassert> 44 #include <cstdlib> 45 #include <functional> 46 #include <iterator> 47 #include <memory> 48 #include <string> 49 #include <system_error> 50 #include <utility> 51 52 using namespace llvm; 53 using namespace llvm::objcopy; 54 using namespace object; 55 using namespace ELF; 56 57 namespace { 58 59 enum ObjcopyID { 60 OBJCOPY_INVALID = 0, // This is not an option ID. 61 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 62 HELPTEXT, METAVAR, VALUES) \ 63 OBJCOPY_##ID, 64 #include "ObjcopyOpts.inc" 65 #undef OPTION 66 }; 67 68 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE; 69 #include "ObjcopyOpts.inc" 70 #undef PREFIX 71 72 static const opt::OptTable::Info ObjcopyInfoTable[] = { 73 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 74 HELPTEXT, METAVAR, VALUES) \ 75 {OBJCOPY_##PREFIX, \ 76 NAME, \ 77 HELPTEXT, \ 78 METAVAR, \ 79 OBJCOPY_##ID, \ 80 opt::Option::KIND##Class, \ 81 PARAM, \ 82 FLAGS, \ 83 OBJCOPY_##GROUP, \ 84 OBJCOPY_##ALIAS, \ 85 ALIASARGS, \ 86 VALUES}, 87 #include "ObjcopyOpts.inc" 88 #undef OPTION 89 }; 90 91 class ObjcopyOptTable : public opt::OptTable { 92 public: 93 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {} 94 }; 95 96 enum StripID { 97 STRIP_INVALID = 0, // This is not an option ID. 98 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 99 HELPTEXT, METAVAR, VALUES) \ 100 STRIP_##ID, 101 #include "StripOpts.inc" 102 #undef OPTION 103 }; 104 105 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE; 106 #include "StripOpts.inc" 107 #undef PREFIX 108 109 static const opt::OptTable::Info StripInfoTable[] = { 110 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 111 HELPTEXT, METAVAR, VALUES) \ 112 {STRIP_##PREFIX, NAME, HELPTEXT, \ 113 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \ 114 PARAM, FLAGS, STRIP_##GROUP, \ 115 STRIP_##ALIAS, ALIASARGS, VALUES}, 116 #include "StripOpts.inc" 117 #undef OPTION 118 }; 119 120 class StripOptTable : public opt::OptTable { 121 public: 122 StripOptTable() : OptTable(StripInfoTable, true) {} 123 }; 124 125 struct SectionRename { 126 StringRef OriginalName; 127 StringRef NewName; 128 Optional<uint64_t> NewFlags; 129 }; 130 131 struct CopyConfig { 132 // Main input/output options 133 StringRef InputFilename; 134 StringRef InputFormat; 135 StringRef OutputFilename; 136 StringRef OutputFormat; 137 138 // Only applicable for --input-format=Binary 139 MachineInfo BinaryArch; 140 141 // Advanced options 142 StringRef AddGnuDebugLink; 143 StringRef SplitDWO; 144 StringRef SymbolsPrefix; 145 146 // Repeated options 147 std::vector<StringRef> AddSection; 148 std::vector<StringRef> DumpSection; 149 std::vector<StringRef> Keep; 150 std::vector<StringRef> OnlyKeep; 151 std::vector<StringRef> SymbolsToGlobalize; 152 std::vector<StringRef> SymbolsToKeep; 153 std::vector<StringRef> SymbolsToLocalize; 154 std::vector<StringRef> SymbolsToRemove; 155 std::vector<StringRef> SymbolsToWeaken; 156 std::vector<StringRef> ToRemove; 157 std::vector<std::string> SymbolsToKeepGlobal; 158 159 // Map options 160 StringMap<SectionRename> SectionsToRename; 161 StringMap<StringRef> SymbolsToRename; 162 163 // Boolean options 164 bool DiscardAll = false; 165 bool ExtractDWO = false; 166 bool KeepFileSymbols = false; 167 bool LocalizeHidden = false; 168 bool OnlyKeepDebug = false; 169 bool PreserveDates = false; 170 bool StripAll = false; 171 bool StripAllGNU = false; 172 bool StripDWO = false; 173 bool StripDebug = false; 174 bool StripNonAlloc = false; 175 bool StripSections = false; 176 bool StripUnneeded = false; 177 bool Weaken = false; 178 }; 179 180 using SectionPred = std::function<bool(const SectionBase &Sec)>; 181 182 enum SectionFlag { 183 SecNone = 0, 184 SecAlloc = 1 << 0, 185 SecLoad = 1 << 1, 186 SecNoload = 1 << 2, 187 SecReadonly = 1 << 3, 188 SecDebug = 1 << 4, 189 SecCode = 1 << 5, 190 SecData = 1 << 6, 191 SecRom = 1 << 7, 192 SecMerge = 1 << 8, 193 SecStrings = 1 << 9, 194 SecContents = 1 << 10, 195 SecShare = 1 << 11, 196 LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ SecShare) 197 }; 198 199 } // namespace 200 201 namespace llvm { 202 namespace objcopy { 203 204 // The name this program was invoked as. 205 StringRef ToolName; 206 207 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) { 208 WithColor::error(errs(), ToolName) << Message << ".\n"; 209 errs().flush(); 210 exit(1); 211 } 212 213 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) { 214 assert(EC); 215 WithColor::error(errs(), ToolName) 216 << "'" << File << "': " << EC.message() << ".\n"; 217 exit(1); 218 } 219 220 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) { 221 assert(E); 222 std::string Buf; 223 raw_string_ostream OS(Buf); 224 logAllUnhandledErrors(std::move(E), OS, ""); 225 OS.flush(); 226 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf; 227 exit(1); 228 } 229 230 } // end namespace objcopy 231 } // end namespace llvm 232 233 static SectionFlag parseSectionRenameFlag(StringRef SectionName) { 234 return llvm::StringSwitch<SectionFlag>(SectionName) 235 .Case("alloc", SectionFlag::SecAlloc) 236 .Case("load", SectionFlag::SecLoad) 237 .Case("noload", SectionFlag::SecNoload) 238 .Case("readonly", SectionFlag::SecReadonly) 239 .Case("debug", SectionFlag::SecDebug) 240 .Case("code", SectionFlag::SecCode) 241 .Case("data", SectionFlag::SecData) 242 .Case("rom", SectionFlag::SecRom) 243 .Case("merge", SectionFlag::SecMerge) 244 .Case("strings", SectionFlag::SecStrings) 245 .Case("contents", SectionFlag::SecContents) 246 .Case("share", SectionFlag::SecShare) 247 .Default(SectionFlag::SecNone); 248 } 249 250 static SectionRename parseRenameSectionValue(StringRef FlagValue) { 251 if (!FlagValue.contains('=')) 252 error("Bad format for --rename-section: missing '='"); 253 254 // Initial split: ".foo" = ".bar,f1,f2,..." 255 auto Old2New = FlagValue.split('='); 256 SectionRename SR; 257 SR.OriginalName = Old2New.first; 258 259 // Flags split: ".bar" "f1" "f2" ... 260 SmallVector<StringRef, 6> NameAndFlags; 261 Old2New.second.split(NameAndFlags, ','); 262 SR.NewName = NameAndFlags[0]; 263 264 if (NameAndFlags.size() > 1) { 265 SectionFlag Flags = SectionFlag::SecNone; 266 for (size_t I = 1, Size = NameAndFlags.size(); I < Size; ++I) { 267 SectionFlag Flag = parseSectionRenameFlag(NameAndFlags[I]); 268 if (Flag == SectionFlag::SecNone) 269 error("Unrecognized section flag '" + NameAndFlags[I] + 270 "'. Flags supported for GNU compatibility: alloc, load, noload, " 271 "readonly, debug, code, data, rom, share, contents, merge, " 272 "strings."); 273 Flags |= Flag; 274 } 275 276 SR.NewFlags = 0; 277 if (Flags & SectionFlag::SecAlloc) 278 *SR.NewFlags |= ELF::SHF_ALLOC; 279 if (!(Flags & SectionFlag::SecReadonly)) 280 *SR.NewFlags |= ELF::SHF_WRITE; 281 if (Flags & SectionFlag::SecCode) 282 *SR.NewFlags |= ELF::SHF_EXECINSTR; 283 if (Flags & SectionFlag::SecMerge) 284 *SR.NewFlags |= ELF::SHF_MERGE; 285 if (Flags & SectionFlag::SecStrings) 286 *SR.NewFlags |= ELF::SHF_STRINGS; 287 } 288 289 return SR; 290 } 291 292 static bool isDebugSection(const SectionBase &Sec) { 293 return Sec.Name.startswith(".debug") || Sec.Name.startswith(".zdebug") || 294 Sec.Name == ".gdb_index"; 295 } 296 297 static bool isDWOSection(const SectionBase &Sec) { 298 return Sec.Name.endswith(".dwo"); 299 } 300 301 static bool onlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) { 302 // We can't remove the section header string table. 303 if (&Sec == Obj.SectionNames) 304 return false; 305 // Short of keeping the string table we want to keep everything that is a DWO 306 // section and remove everything else. 307 return !isDWOSection(Sec); 308 } 309 310 static const StringMap<MachineInfo> ArchMap{ 311 // Name, {EMachine, 64bit, LittleEndian} 312 {"aarch64", {EM_AARCH64, true, true}}, 313 {"arm", {EM_ARM, false, true}}, 314 {"i386", {EM_386, false, true}}, 315 {"i386:x86-64", {EM_X86_64, true, true}}, 316 {"powerpc:common64", {EM_PPC64, true, true}}, 317 {"sparc", {EM_SPARC, false, true}}, 318 {"x86-64", {EM_X86_64, true, true}}, 319 }; 320 321 static const MachineInfo &getMachineInfo(StringRef Arch) { 322 auto Iter = ArchMap.find(Arch); 323 if (Iter == std::end(ArchMap)) 324 error("Invalid architecture: '" + Arch + "'"); 325 return Iter->getValue(); 326 } 327 328 static ElfType getOutputElfType(const Binary &Bin) { 329 // Infer output ELF type from the input ELF object 330 if (isa<ELFObjectFile<ELF32LE>>(Bin)) 331 return ELFT_ELF32LE; 332 if (isa<ELFObjectFile<ELF64LE>>(Bin)) 333 return ELFT_ELF64LE; 334 if (isa<ELFObjectFile<ELF32BE>>(Bin)) 335 return ELFT_ELF32BE; 336 if (isa<ELFObjectFile<ELF64BE>>(Bin)) 337 return ELFT_ELF64BE; 338 llvm_unreachable("Invalid ELFType"); 339 } 340 341 static ElfType getOutputElfType(const MachineInfo &MI) { 342 // Infer output ELF type from the binary arch specified 343 if (MI.Is64Bit) 344 return MI.IsLittleEndian ? ELFT_ELF64LE : ELFT_ELF64BE; 345 else 346 return MI.IsLittleEndian ? ELFT_ELF32LE : ELFT_ELF32BE; 347 } 348 349 static std::unique_ptr<Writer> createWriter(const CopyConfig &Config, 350 Object &Obj, Buffer &Buf, 351 ElfType OutputElfType) { 352 if (Config.OutputFormat == "binary") { 353 return llvm::make_unique<BinaryWriter>(Obj, Buf); 354 } 355 // Depending on the initial ELFT and OutputFormat we need a different Writer. 356 switch (OutputElfType) { 357 case ELFT_ELF32LE: 358 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf, 359 !Config.StripSections); 360 case ELFT_ELF64LE: 361 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf, 362 !Config.StripSections); 363 case ELFT_ELF32BE: 364 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf, 365 !Config.StripSections); 366 case ELFT_ELF64BE: 367 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf, 368 !Config.StripSections); 369 } 370 llvm_unreachable("Invalid output format"); 371 } 372 373 static void splitDWOToFile(const CopyConfig &Config, const Reader &Reader, 374 StringRef File, ElfType OutputElfType) { 375 auto DWOFile = Reader.create(); 376 DWOFile->removeSections( 377 [&](const SectionBase &Sec) { return onlyKeepDWOPred(*DWOFile, Sec); }); 378 FileBuffer FB(File); 379 auto Writer = createWriter(Config, *DWOFile, FB, OutputElfType); 380 Writer->finalize(); 381 Writer->write(); 382 } 383 384 static Error dumpSectionToFile(StringRef SecName, StringRef Filename, 385 Object &Obj) { 386 for (auto &Sec : Obj.sections()) { 387 if (Sec.Name == SecName) { 388 if (Sec.OriginalData.size() == 0) 389 return make_error<StringError>("Can't dump section \"" + SecName + 390 "\": it has no contents", 391 object_error::parse_failed); 392 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr = 393 FileOutputBuffer::create(Filename, Sec.OriginalData.size()); 394 if (!BufferOrErr) 395 return BufferOrErr.takeError(); 396 std::unique_ptr<FileOutputBuffer> Buf = std::move(*BufferOrErr); 397 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), 398 Buf->getBufferStart()); 399 if (Error E = Buf->commit()) 400 return E; 401 return Error::success(); 402 } 403 } 404 return make_error<StringError>("Section not found", 405 object_error::parse_failed); 406 } 407 408 // This function handles the high level operations of GNU objcopy including 409 // handling command line options. It's important to outline certain properties 410 // we expect to hold of the command line operations. Any operation that "keeps" 411 // should keep regardless of a remove. Additionally any removal should respect 412 // any previous removals. Lastly whether or not something is removed shouldn't 413 // depend a) on the order the options occur in or b) on some opaque priority 414 // system. The only priority is that keeps/copies overrule removes. 415 static void handleArgs(const CopyConfig &Config, Object &Obj, 416 const Reader &Reader, ElfType OutputElfType) { 417 418 if (!Config.SplitDWO.empty()) { 419 splitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType); 420 } 421 422 // TODO: update or remove symbols only if there is an option that affects 423 // them. 424 if (Obj.SymbolTable) { 425 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) { 426 if ((Config.LocalizeHidden && 427 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) || 428 (!Config.SymbolsToLocalize.empty() && 429 is_contained(Config.SymbolsToLocalize, Sym.Name))) 430 Sym.Binding = STB_LOCAL; 431 432 // Note: these two globalize flags have very similar names but different 433 // meanings: 434 // 435 // --globalize-symbol: promote a symbol to global 436 // --keep-global-symbol: all symbols except for these should be made local 437 // 438 // If --globalize-symbol is specified for a given symbol, it will be 439 // global in the output file even if it is not included via 440 // --keep-global-symbol. Because of that, make sure to check 441 // --globalize-symbol second. 442 if (!Config.SymbolsToKeepGlobal.empty() && 443 !is_contained(Config.SymbolsToKeepGlobal, Sym.Name)) 444 Sym.Binding = STB_LOCAL; 445 446 if (!Config.SymbolsToGlobalize.empty() && 447 is_contained(Config.SymbolsToGlobalize, Sym.Name)) 448 Sym.Binding = STB_GLOBAL; 449 450 if (!Config.SymbolsToWeaken.empty() && 451 is_contained(Config.SymbolsToWeaken, Sym.Name) && 452 Sym.Binding == STB_GLOBAL) 453 Sym.Binding = STB_WEAK; 454 455 if (Config.Weaken && Sym.Binding == STB_GLOBAL && 456 Sym.getShndx() != SHN_UNDEF) 457 Sym.Binding = STB_WEAK; 458 459 const auto I = Config.SymbolsToRename.find(Sym.Name); 460 if (I != Config.SymbolsToRename.end()) 461 Sym.Name = I->getValue(); 462 463 if (!Config.SymbolsPrefix.empty() && Sym.Type != STT_SECTION) 464 Sym.Name = (Config.SymbolsPrefix + Sym.Name).str(); 465 }); 466 467 // The purpose of this loop is to mark symbols referenced by sections 468 // (like GroupSection or RelocationSection). This way, we know which 469 // symbols are still 'needed' and wich are not. 470 if (Config.StripUnneeded) { 471 for (auto &Section : Obj.sections()) 472 Section.markSymbols(); 473 } 474 475 Obj.removeSymbols([&](const Symbol &Sym) { 476 if ((!Config.SymbolsToKeep.empty() && 477 is_contained(Config.SymbolsToKeep, Sym.Name)) || 478 (Config.KeepFileSymbols && Sym.Type == STT_FILE)) 479 return false; 480 481 if (Config.DiscardAll && Sym.Binding == STB_LOCAL && 482 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE && 483 Sym.Type != STT_SECTION) 484 return true; 485 486 if (Config.StripAll || Config.StripAllGNU) 487 return true; 488 489 if (!Config.SymbolsToRemove.empty() && 490 is_contained(Config.SymbolsToRemove, Sym.Name)) { 491 return true; 492 } 493 494 if (Config.StripUnneeded && !Sym.Referenced && 495 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) && 496 Sym.Type != STT_FILE && Sym.Type != STT_SECTION) 497 return true; 498 499 return false; 500 }); 501 } 502 503 SectionPred RemovePred = [](const SectionBase &) { return false; }; 504 505 // Removes: 506 if (!Config.ToRemove.empty()) { 507 RemovePred = [&Config](const SectionBase &Sec) { 508 return is_contained(Config.ToRemove, Sec.Name); 509 }; 510 } 511 512 if (Config.StripDWO || !Config.SplitDWO.empty()) 513 RemovePred = [RemovePred](const SectionBase &Sec) { 514 return isDWOSection(Sec) || RemovePred(Sec); 515 }; 516 517 if (Config.ExtractDWO) 518 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 519 return onlyKeepDWOPred(Obj, Sec) || RemovePred(Sec); 520 }; 521 522 if (Config.StripAllGNU) 523 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 524 if (RemovePred(Sec)) 525 return true; 526 if ((Sec.Flags & SHF_ALLOC) != 0) 527 return false; 528 if (&Sec == Obj.SectionNames) 529 return false; 530 switch (Sec.Type) { 531 case SHT_SYMTAB: 532 case SHT_REL: 533 case SHT_RELA: 534 case SHT_STRTAB: 535 return true; 536 } 537 return isDebugSection(Sec); 538 }; 539 540 if (Config.StripSections) { 541 RemovePred = [RemovePred](const SectionBase &Sec) { 542 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0; 543 }; 544 } 545 546 if (Config.StripDebug) { 547 RemovePred = [RemovePred](const SectionBase &Sec) { 548 return RemovePred(Sec) || isDebugSection(Sec); 549 }; 550 } 551 552 if (Config.StripNonAlloc) 553 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 554 if (RemovePred(Sec)) 555 return true; 556 if (&Sec == Obj.SectionNames) 557 return false; 558 return (Sec.Flags & SHF_ALLOC) == 0; 559 }; 560 561 if (Config.StripAll) 562 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 563 if (RemovePred(Sec)) 564 return true; 565 if (&Sec == Obj.SectionNames) 566 return false; 567 if (Sec.Name.startswith(".gnu.warning")) 568 return false; 569 return (Sec.Flags & SHF_ALLOC) == 0; 570 }; 571 572 // Explicit copies: 573 if (!Config.OnlyKeep.empty()) { 574 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) { 575 // Explicitly keep these sections regardless of previous removes. 576 if (is_contained(Config.OnlyKeep, Sec.Name)) 577 return false; 578 579 // Allow all implicit removes. 580 if (RemovePred(Sec)) 581 return true; 582 583 // Keep special sections. 584 if (Obj.SectionNames == &Sec) 585 return false; 586 if (Obj.SymbolTable == &Sec || 587 (Obj.SymbolTable && Obj.SymbolTable->getStrTab() == &Sec)) 588 return false; 589 590 // Remove everything else. 591 return true; 592 }; 593 } 594 595 if (!Config.Keep.empty()) { 596 RemovePred = [Config, RemovePred](const SectionBase &Sec) { 597 // Explicitly keep these sections regardless of previous removes. 598 if (is_contained(Config.Keep, Sec.Name)) 599 return false; 600 // Otherwise defer to RemovePred. 601 return RemovePred(Sec); 602 }; 603 } 604 605 // This has to be the last predicate assignment. 606 // If the option --keep-symbol has been specified 607 // and at least one of those symbols is present 608 // (equivalently, the updated symbol table is not empty) 609 // the symbol table and the string table should not be removed. 610 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) && 611 Obj.SymbolTable && !Obj.SymbolTable->empty()) { 612 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) { 613 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab()) 614 return false; 615 return RemovePred(Sec); 616 }; 617 } 618 619 Obj.removeSections(RemovePred); 620 621 if (!Config.SectionsToRename.empty()) { 622 for (auto &Sec : Obj.sections()) { 623 const auto Iter = Config.SectionsToRename.find(Sec.Name); 624 if (Iter != Config.SectionsToRename.end()) { 625 const SectionRename &SR = Iter->second; 626 Sec.Name = SR.NewName; 627 if (SR.NewFlags.hasValue()) { 628 // Preserve some flags which should not be dropped when setting flags. 629 // Also, preserve anything OS/processor dependant. 630 const uint64_t PreserveMask = ELF::SHF_COMPRESSED | ELF::SHF_EXCLUDE | 631 ELF::SHF_GROUP | ELF::SHF_LINK_ORDER | 632 ELF::SHF_MASKOS | ELF::SHF_MASKPROC | 633 ELF::SHF_TLS | ELF::SHF_INFO_LINK; 634 Sec.Flags = (Sec.Flags & PreserveMask) | 635 (SR.NewFlags.getValue() & ~PreserveMask); 636 } 637 } 638 } 639 } 640 641 if (!Config.AddSection.empty()) { 642 for (const auto &Flag : Config.AddSection) { 643 auto SecPair = Flag.split("="); 644 auto SecName = SecPair.first; 645 auto File = SecPair.second; 646 auto BufOrErr = MemoryBuffer::getFile(File); 647 if (!BufOrErr) 648 reportError(File, BufOrErr.getError()); 649 auto Buf = std::move(*BufOrErr); 650 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart()); 651 auto BufSize = Buf->getBufferSize(); 652 Obj.addSection<OwnedDataSection>(SecName, 653 ArrayRef<uint8_t>(BufPtr, BufSize)); 654 } 655 } 656 657 if (!Config.DumpSection.empty()) { 658 for (const auto &Flag : Config.DumpSection) { 659 std::pair<StringRef, StringRef> SecPair = Flag.split("="); 660 StringRef SecName = SecPair.first; 661 StringRef File = SecPair.second; 662 if (Error E = dumpSectionToFile(SecName, File, Obj)) 663 reportError(Config.InputFilename, std::move(E)); 664 } 665 } 666 667 if (!Config.AddGnuDebugLink.empty()) 668 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink); 669 } 670 671 static void executeElfObjcopyOnBinary(const CopyConfig &Config, Reader &Reader, 672 Buffer &Out, ElfType OutputElfType) { 673 std::unique_ptr<Object> Obj = Reader.create(); 674 675 handleArgs(Config, *Obj, Reader, OutputElfType); 676 677 std::unique_ptr<Writer> Writer = 678 createWriter(Config, *Obj, Out, OutputElfType); 679 Writer->finalize(); 680 Writer->write(); 681 } 682 683 // For regular archives this function simply calls llvm::writeArchive, 684 // For thin archives it writes the archive file itself as well as its members. 685 static Error deepWriteArchive(StringRef ArcName, 686 ArrayRef<NewArchiveMember> NewMembers, 687 bool WriteSymtab, object::Archive::Kind Kind, 688 bool Deterministic, bool Thin) { 689 Error E = 690 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin); 691 if (!Thin || E) 692 return E; 693 for (const NewArchiveMember &Member : NewMembers) { 694 // Internally, FileBuffer will use the buffer created by 695 // FileOutputBuffer::create, for regular files (that is the case for 696 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer. 697 // OnDiskBuffer uses a temporary file and then renames it. So in reality 698 // there is no inefficiency / duplicated in-memory buffers in this case. For 699 // now in-memory buffers can not be completely avoided since 700 // NewArchiveMember still requires them even though writeArchive does not 701 // write them on disk. 702 FileBuffer FB(Member.MemberName); 703 FB.allocate(Member.Buf->getBufferSize()); 704 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(), 705 FB.getBufferStart()); 706 if (auto E = FB.commit()) 707 return E; 708 } 709 return Error::success(); 710 } 711 712 static void executeElfObjcopyOnArchive(const CopyConfig &Config, 713 const Archive &Ar) { 714 std::vector<NewArchiveMember> NewArchiveMembers; 715 Error Err = Error::success(); 716 for (const Archive::Child &Child : Ar.children(Err)) { 717 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 718 if (!ChildOrErr) 719 reportError(Ar.getFileName(), ChildOrErr.takeError()); 720 Binary *Bin = ChildOrErr->get(); 721 722 Expected<StringRef> ChildNameOrErr = Child.getName(); 723 if (!ChildNameOrErr) 724 reportError(Ar.getFileName(), ChildNameOrErr.takeError()); 725 726 MemBuffer MB(ChildNameOrErr.get()); 727 ELFReader Reader(Bin); 728 executeElfObjcopyOnBinary(Config, Reader, MB, getOutputElfType(*Bin)); 729 730 Expected<NewArchiveMember> Member = 731 NewArchiveMember::getOldMember(Child, true); 732 if (!Member) 733 reportError(Ar.getFileName(), Member.takeError()); 734 Member->Buf = MB.releaseMemoryBuffer(); 735 Member->MemberName = Member->Buf->getBufferIdentifier(); 736 NewArchiveMembers.push_back(std::move(*Member)); 737 } 738 739 if (Err) 740 reportError(Config.InputFilename, std::move(Err)); 741 if (Error E = 742 deepWriteArchive(Config.OutputFilename, NewArchiveMembers, 743 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin())) 744 reportError(Config.OutputFilename, std::move(E)); 745 } 746 747 static void restoreDateOnFile(StringRef Filename, 748 const sys::fs::file_status &Stat) { 749 int FD; 750 751 if (auto EC = 752 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting)) 753 reportError(Filename, EC); 754 755 if (auto EC = sys::fs::setLastAccessAndModificationTime( 756 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime())) 757 reportError(Filename, EC); 758 759 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) 760 reportError(Filename, EC); 761 } 762 763 static void executeElfObjcopy(const CopyConfig &Config) { 764 sys::fs::file_status Stat; 765 if (Config.PreserveDates) 766 if (auto EC = sys::fs::status(Config.InputFilename, Stat)) 767 reportError(Config.InputFilename, EC); 768 769 if (Config.InputFormat == "binary") { 770 auto BufOrErr = MemoryBuffer::getFile(Config.InputFilename); 771 if (!BufOrErr) 772 reportError(Config.InputFilename, BufOrErr.getError()); 773 774 FileBuffer FB(Config.OutputFilename); 775 BinaryReader Reader(Config.BinaryArch, BufOrErr->get()); 776 executeElfObjcopyOnBinary(Config, Reader, FB, 777 getOutputElfType(Config.BinaryArch)); 778 } else { 779 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr = 780 createBinary(Config.InputFilename); 781 if (!BinaryOrErr) 782 reportError(Config.InputFilename, BinaryOrErr.takeError()); 783 784 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) { 785 executeElfObjcopyOnArchive(Config, *Ar); 786 } else { 787 FileBuffer FB(Config.OutputFilename); 788 Binary *Bin = BinaryOrErr.get().getBinary(); 789 ELFReader Reader(Bin); 790 executeElfObjcopyOnBinary(Config, Reader, FB, getOutputElfType(*Bin)); 791 } 792 } 793 794 if (Config.PreserveDates) { 795 restoreDateOnFile(Config.OutputFilename, Stat); 796 if (!Config.SplitDWO.empty()) 797 restoreDateOnFile(Config.SplitDWO, Stat); 798 } 799 } 800 801 static void addGlobalSymbolsFromFile(std::vector<std::string> &Symbols, 802 StringRef Filename) { 803 SmallVector<StringRef, 16> Lines; 804 auto BufOrErr = MemoryBuffer::getFile(Filename); 805 if (!BufOrErr) 806 reportError(Filename, BufOrErr.getError()); 807 808 BufOrErr.get()->getBuffer().split(Lines, '\n'); 809 for (StringRef Line : Lines) { 810 // Ignore everything after '#', trim whitespace, and only add the symbol if 811 // it's not empty. 812 auto TrimmedLine = Line.split('#').first.trim(); 813 if (!TrimmedLine.empty()) 814 Symbols.push_back(TrimmedLine.str()); 815 } 816 } 817 818 // ParseObjcopyOptions returns the config and sets the input arguments. If a 819 // help flag is set then ParseObjcopyOptions will print the help messege and 820 // exit. 821 static CopyConfig parseObjcopyOptions(ArrayRef<const char *> ArgsArr) { 822 ObjcopyOptTable T; 823 unsigned MissingArgumentIndex, MissingArgumentCount; 824 llvm::opt::InputArgList InputArgs = 825 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount); 826 827 if (InputArgs.size() == 0) { 828 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool"); 829 exit(1); 830 } 831 832 if (InputArgs.hasArg(OBJCOPY_help)) { 833 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool"); 834 exit(0); 835 } 836 837 SmallVector<const char *, 2> Positional; 838 839 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN)) 840 error("unknown argument '" + Arg->getAsString(InputArgs) + "'"); 841 842 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT)) 843 Positional.push_back(Arg->getValue()); 844 845 if (Positional.empty()) 846 error("No input file specified"); 847 848 if (Positional.size() > 2) 849 error("Too many positional arguments"); 850 851 CopyConfig Config; 852 Config.InputFilename = Positional[0]; 853 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1]; 854 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target); 855 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target); 856 if (Config.InputFormat == "binary") { 857 auto BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture); 858 if (BinaryArch.empty()) 859 error("Specified binary input without specifiying an architecture"); 860 Config.BinaryArch = getMachineInfo(BinaryArch); 861 } 862 863 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo); 864 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink); 865 Config.SymbolsPrefix = InputArgs.getLastArgValue(OBJCOPY_prefix_symbols); 866 867 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) { 868 if (!StringRef(Arg->getValue()).contains('=')) 869 error("Bad format for --redefine-sym"); 870 auto Old2New = StringRef(Arg->getValue()).split('='); 871 if (!Config.SymbolsToRename.insert(Old2New).second) 872 error("Multiple redefinition of symbol " + Old2New.first); 873 } 874 875 for (auto Arg : InputArgs.filtered(OBJCOPY_rename_section)) { 876 SectionRename SR = parseRenameSectionValue(StringRef(Arg->getValue())); 877 if (!Config.SectionsToRename.try_emplace(SR.OriginalName, SR).second) 878 error("Multiple renames of section " + SR.OriginalName); 879 } 880 881 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section)) 882 Config.ToRemove.push_back(Arg->getValue()); 883 for (auto Arg : InputArgs.filtered(OBJCOPY_keep)) 884 Config.Keep.push_back(Arg->getValue()); 885 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep)) 886 Config.OnlyKeep.push_back(Arg->getValue()); 887 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) 888 Config.AddSection.push_back(Arg->getValue()); 889 for (auto Arg : InputArgs.filtered(OBJCOPY_dump_section)) 890 Config.DumpSection.push_back(Arg->getValue()); 891 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all); 892 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu); 893 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug); 894 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo); 895 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections); 896 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc); 897 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded); 898 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo); 899 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden); 900 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken); 901 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all); 902 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug); 903 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols); 904 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol)) 905 Config.SymbolsToLocalize.push_back(Arg->getValue()); 906 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbol)) 907 Config.SymbolsToKeepGlobal.push_back(Arg->getValue()); 908 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_global_symbols)) 909 addGlobalSymbolsFromFile(Config.SymbolsToKeepGlobal, Arg->getValue()); 910 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol)) 911 Config.SymbolsToGlobalize.push_back(Arg->getValue()); 912 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol)) 913 Config.SymbolsToWeaken.push_back(Arg->getValue()); 914 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol)) 915 Config.SymbolsToRemove.push_back(Arg->getValue()); 916 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol)) 917 Config.SymbolsToKeep.push_back(Arg->getValue()); 918 919 Config.PreserveDates = InputArgs.hasArg(OBJCOPY_preserve_dates); 920 921 return Config; 922 } 923 924 // ParseStripOptions returns the config and sets the input arguments. If a 925 // help flag is set then ParseStripOptions will print the help messege and 926 // exit. 927 static CopyConfig parseStripOptions(ArrayRef<const char *> ArgsArr) { 928 StripOptTable T; 929 unsigned MissingArgumentIndex, MissingArgumentCount; 930 llvm::opt::InputArgList InputArgs = 931 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount); 932 933 if (InputArgs.size() == 0) { 934 T.PrintHelp(errs(), "llvm-strip", "strip tool"); 935 exit(1); 936 } 937 938 if (InputArgs.hasArg(STRIP_help)) { 939 T.PrintHelp(outs(), "llvm-strip", "strip tool"); 940 exit(0); 941 } 942 943 SmallVector<const char *, 2> Positional; 944 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN)) 945 error("unknown argument '" + Arg->getAsString(InputArgs) + "'"); 946 for (auto Arg : InputArgs.filtered(STRIP_INPUT)) 947 Positional.push_back(Arg->getValue()); 948 949 if (Positional.empty()) 950 error("No input file specified"); 951 952 if (Positional.size() > 1) 953 error("Support for multiple input files is not implemented yet"); 954 955 CopyConfig Config; 956 Config.InputFilename = Positional[0]; 957 Config.OutputFilename = 958 InputArgs.getLastArgValue(STRIP_output, Positional[0]); 959 960 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug); 961 962 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all); 963 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded); 964 Config.StripAll = InputArgs.hasArg(STRIP_strip_all); 965 966 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll) 967 Config.StripAll = true; 968 969 for (auto Arg : InputArgs.filtered(STRIP_remove_section)) 970 Config.ToRemove.push_back(Arg->getValue()); 971 972 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol)) 973 Config.SymbolsToKeep.push_back(Arg->getValue()); 974 975 Config.PreserveDates = InputArgs.hasArg(STRIP_preserve_dates); 976 977 return Config; 978 } 979 980 int main(int argc, char **argv) { 981 InitLLVM X(argc, argv); 982 ToolName = argv[0]; 983 CopyConfig Config; 984 if (sys::path::stem(ToolName).endswith_lower("strip")) 985 Config = parseStripOptions(makeArrayRef(argv + 1, argc)); 986 else 987 Config = parseObjcopyOptions(makeArrayRef(argv + 1, argc)); 988 executeElfObjcopy(Config); 989 } 990