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 #include "Object.h" 12 #include "llvm/ADT/STLExtras.h" 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/ADT/Twine.h" 15 #include "llvm/BinaryFormat/ELF.h" 16 #include "llvm/Object/Archive.h" 17 #include "llvm/Object/ArchiveWriter.h" 18 #include "llvm/Object/Binary.h" 19 #include "llvm/Object/ELFObjectFile.h" 20 #include "llvm/Object/ELFTypes.h" 21 #include "llvm/Object/Error.h" 22 #include "llvm/Option/Arg.h" 23 #include "llvm/Option/ArgList.h" 24 #include "llvm/Option/Option.h" 25 #include "llvm/Support/Casting.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/Compiler.h" 28 #include "llvm/Support/Error.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/ErrorOr.h" 31 #include "llvm/Support/FileOutputBuffer.h" 32 #include "llvm/Support/InitLLVM.h" 33 #include "llvm/Support/Path.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <algorithm> 36 #include <cassert> 37 #include <cstdlib> 38 #include <functional> 39 #include <iterator> 40 #include <memory> 41 #include <string> 42 #include <system_error> 43 #include <utility> 44 45 using namespace llvm; 46 using namespace object; 47 using namespace ELF; 48 49 namespace { 50 51 enum ObjcopyID { 52 OBJCOPY_INVALID = 0, // This is not an option ID. 53 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 54 HELPTEXT, METAVAR, VALUES) \ 55 OBJCOPY_##ID, 56 #include "ObjcopyOpts.inc" 57 #undef OPTION 58 }; 59 60 #define PREFIX(NAME, VALUE) const char *const OBJCOPY_##NAME[] = VALUE; 61 #include "ObjcopyOpts.inc" 62 #undef PREFIX 63 64 static const opt::OptTable::Info ObjcopyInfoTable[] = { 65 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 66 HELPTEXT, METAVAR, VALUES) \ 67 {OBJCOPY_##PREFIX, \ 68 NAME, \ 69 HELPTEXT, \ 70 METAVAR, \ 71 OBJCOPY_##ID, \ 72 opt::Option::KIND##Class, \ 73 PARAM, \ 74 FLAGS, \ 75 OBJCOPY_##GROUP, \ 76 OBJCOPY_##ALIAS, \ 77 ALIASARGS, \ 78 VALUES}, 79 #include "ObjcopyOpts.inc" 80 #undef OPTION 81 }; 82 83 class ObjcopyOptTable : public opt::OptTable { 84 public: 85 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {} 86 }; 87 88 enum StripID { 89 STRIP_INVALID = 0, // This is not an option ID. 90 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 91 HELPTEXT, METAVAR, VALUES) \ 92 STRIP_##ID, 93 #include "StripOpts.inc" 94 #undef OPTION 95 }; 96 97 #define PREFIX(NAME, VALUE) const char *const STRIP_##NAME[] = VALUE; 98 #include "StripOpts.inc" 99 #undef PREFIX 100 101 static const opt::OptTable::Info StripInfoTable[] = { 102 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 103 HELPTEXT, METAVAR, VALUES) \ 104 {STRIP_##PREFIX, NAME, HELPTEXT, \ 105 METAVAR, STRIP_##ID, opt::Option::KIND##Class, \ 106 PARAM, FLAGS, STRIP_##GROUP, \ 107 STRIP_##ALIAS, ALIASARGS, VALUES}, 108 #include "StripOpts.inc" 109 #undef OPTION 110 }; 111 112 class StripOptTable : public opt::OptTable { 113 public: 114 StripOptTable() : OptTable(StripInfoTable, true) {} 115 }; 116 117 } // namespace 118 119 // The name this program was invoked as. 120 static StringRef ToolName; 121 122 namespace llvm { 123 124 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) { 125 errs() << ToolName << ": " << Message << ".\n"; 126 errs().flush(); 127 exit(1); 128 } 129 130 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) { 131 assert(EC); 132 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; 133 exit(1); 134 } 135 136 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) { 137 assert(E); 138 std::string Buf; 139 raw_string_ostream OS(Buf); 140 logAllUnhandledErrors(std::move(E), OS, ""); 141 OS.flush(); 142 errs() << ToolName << ": '" << File << "': " << Buf; 143 exit(1); 144 } 145 146 } // end namespace llvm 147 148 struct CopyConfig { 149 StringRef OutputFilename; 150 StringRef InputFilename; 151 StringRef OutputFormat; 152 StringRef InputFormat; 153 StringRef BinaryArch; 154 155 StringRef SplitDWO; 156 StringRef AddGnuDebugLink; 157 std::vector<StringRef> ToRemove; 158 std::vector<StringRef> Keep; 159 std::vector<StringRef> OnlyKeep; 160 std::vector<StringRef> AddSection; 161 std::vector<StringRef> SymbolsToLocalize; 162 std::vector<StringRef> SymbolsToGlobalize; 163 std::vector<StringRef> SymbolsToWeaken; 164 std::vector<StringRef> SymbolsToRemove; 165 std::vector<StringRef> SymbolsToKeep; 166 StringMap<StringRef> SymbolsToRename; 167 bool StripAll = false; 168 bool StripAllGNU = false; 169 bool StripDebug = false; 170 bool StripSections = false; 171 bool StripNonAlloc = false; 172 bool StripDWO = false; 173 bool StripUnneeded = false; 174 bool ExtractDWO = false; 175 bool LocalizeHidden = false; 176 bool Weaken = false; 177 bool DiscardAll = false; 178 bool OnlyKeepDebug = false; 179 bool KeepFileSymbols = false; 180 }; 181 182 using SectionPred = std::function<bool(const SectionBase &Sec)>; 183 184 bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); } 185 186 bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) { 187 // We can't remove the section header string table. 188 if (&Sec == Obj.SectionNames) 189 return false; 190 // Short of keeping the string table we want to keep everything that is a DWO 191 // section and remove everything else. 192 return !IsDWOSection(Sec); 193 } 194 195 std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj, 196 Buffer &Buf, ElfType OutputElfType) { 197 if (Config.OutputFormat == "binary") { 198 return llvm::make_unique<BinaryWriter>(Obj, Buf); 199 } 200 // Depending on the initial ELFT and OutputFormat we need a different Writer. 201 switch (OutputElfType) { 202 case ELFT_ELF32LE: 203 return llvm::make_unique<ELFWriter<ELF32LE>>(Obj, Buf, 204 !Config.StripSections); 205 case ELFT_ELF64LE: 206 return llvm::make_unique<ELFWriter<ELF64LE>>(Obj, Buf, 207 !Config.StripSections); 208 case ELFT_ELF32BE: 209 return llvm::make_unique<ELFWriter<ELF32BE>>(Obj, Buf, 210 !Config.StripSections); 211 case ELFT_ELF64BE: 212 return llvm::make_unique<ELFWriter<ELF64BE>>(Obj, Buf, 213 !Config.StripSections); 214 } 215 llvm_unreachable("Invalid output format"); 216 } 217 218 void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader, 219 StringRef File, ElfType OutputElfType) { 220 auto DWOFile = Reader.create(); 221 DWOFile->removeSections( 222 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); }); 223 FileBuffer FB(File); 224 auto Writer = CreateWriter(Config, *DWOFile, FB, OutputElfType); 225 Writer->finalize(); 226 Writer->write(); 227 } 228 229 // This function handles the high level operations of GNU objcopy including 230 // handling command line options. It's important to outline certain properties 231 // we expect to hold of the command line operations. Any operation that "keeps" 232 // should keep regardless of a remove. Additionally any removal should respect 233 // any previous removals. Lastly whether or not something is removed shouldn't 234 // depend a) on the order the options occur in or b) on some opaque priority 235 // system. The only priority is that keeps/copies overrule removes. 236 void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader, 237 ElfType OutputElfType) { 238 239 if (!Config.SplitDWO.empty()) { 240 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType); 241 } 242 243 // TODO: update or remove symbols only if there is an option that affects 244 // them. 245 if (Obj.SymbolTable) { 246 Obj.SymbolTable->updateSymbols([&](Symbol &Sym) { 247 if ((Config.LocalizeHidden && 248 (Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL)) || 249 (!Config.SymbolsToLocalize.empty() && 250 is_contained(Config.SymbolsToLocalize, Sym.Name))) 251 Sym.Binding = STB_LOCAL; 252 253 if (!Config.SymbolsToGlobalize.empty() && 254 is_contained(Config.SymbolsToGlobalize, Sym.Name)) 255 Sym.Binding = STB_GLOBAL; 256 257 if (!Config.SymbolsToWeaken.empty() && 258 is_contained(Config.SymbolsToWeaken, Sym.Name) && 259 Sym.Binding == STB_GLOBAL) 260 Sym.Binding = STB_WEAK; 261 262 if (Config.Weaken && Sym.Binding == STB_GLOBAL && 263 Sym.getShndx() != SHN_UNDEF) 264 Sym.Binding = STB_WEAK; 265 266 const auto I = Config.SymbolsToRename.find(Sym.Name); 267 if (I != Config.SymbolsToRename.end()) 268 Sym.Name = I->getValue(); 269 }); 270 271 // The purpose of this loop is to mark symbols referenced by sections 272 // (like GroupSection or RelocationSection). This way, we know which 273 // symbols are still 'needed' and wich are not. 274 if (Config.StripUnneeded) { 275 for (auto &Section : Obj.sections()) 276 Section.markSymbols(); 277 } 278 279 Obj.removeSymbols([&](const Symbol &Sym) { 280 if ((!Config.SymbolsToKeep.empty() && 281 is_contained(Config.SymbolsToKeep, Sym.Name)) || 282 (Config.KeepFileSymbols && Sym.Type == STT_FILE)) 283 return false; 284 285 if (Config.DiscardAll && Sym.Binding == STB_LOCAL && 286 Sym.getShndx() != SHN_UNDEF && Sym.Type != STT_FILE && 287 Sym.Type != STT_SECTION) 288 return true; 289 290 if (Config.StripAll || Config.StripAllGNU) 291 return true; 292 293 if (!Config.SymbolsToRemove.empty() && 294 is_contained(Config.SymbolsToRemove, Sym.Name)) { 295 return true; 296 } 297 298 if (Config.StripUnneeded && !Sym.Referenced && 299 (Sym.Binding == STB_LOCAL || Sym.getShndx() == SHN_UNDEF) && 300 Sym.Type != STT_FILE && Sym.Type != STT_SECTION) 301 return true; 302 303 return false; 304 }); 305 } 306 307 SectionPred RemovePred = [](const SectionBase &) { return false; }; 308 309 // Removes: 310 if (!Config.ToRemove.empty()) { 311 RemovePred = [&Config](const SectionBase &Sec) { 312 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove), 313 Sec.Name) != std::end(Config.ToRemove); 314 }; 315 } 316 317 if (Config.StripDWO || !Config.SplitDWO.empty()) 318 RemovePred = [RemovePred](const SectionBase &Sec) { 319 return IsDWOSection(Sec) || RemovePred(Sec); 320 }; 321 322 if (Config.ExtractDWO) 323 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 324 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec); 325 }; 326 327 if (Config.StripAllGNU) 328 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 329 if (RemovePred(Sec)) 330 return true; 331 if ((Sec.Flags & SHF_ALLOC) != 0) 332 return false; 333 if (&Sec == Obj.SectionNames) 334 return false; 335 switch (Sec.Type) { 336 case SHT_SYMTAB: 337 case SHT_REL: 338 case SHT_RELA: 339 case SHT_STRTAB: 340 return true; 341 } 342 return Sec.Name.startswith(".debug"); 343 }; 344 345 if (Config.StripSections) { 346 RemovePred = [RemovePred](const SectionBase &Sec) { 347 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0; 348 }; 349 } 350 351 if (Config.StripDebug) { 352 RemovePred = [RemovePred](const SectionBase &Sec) { 353 return RemovePred(Sec) || Sec.Name.startswith(".debug"); 354 }; 355 } 356 357 if (Config.StripNonAlloc) 358 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 359 if (RemovePred(Sec)) 360 return true; 361 if (&Sec == Obj.SectionNames) 362 return false; 363 return (Sec.Flags & SHF_ALLOC) == 0; 364 }; 365 366 if (Config.StripAll) 367 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 368 if (RemovePred(Sec)) 369 return true; 370 if (&Sec == Obj.SectionNames) 371 return false; 372 if (Sec.Name.startswith(".gnu.warning")) 373 return false; 374 return (Sec.Flags & SHF_ALLOC) == 0; 375 }; 376 377 // Explicit copies: 378 if (!Config.OnlyKeep.empty()) { 379 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) { 380 // Explicitly keep these sections regardless of previous removes. 381 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep), 382 Sec.Name) != std::end(Config.OnlyKeep)) 383 return false; 384 385 // Allow all implicit removes. 386 if (RemovePred(Sec)) 387 return true; 388 389 // Keep special sections. 390 if (Obj.SectionNames == &Sec) 391 return false; 392 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec) 393 return false; 394 395 // Remove everything else. 396 return true; 397 }; 398 } 399 400 if (!Config.Keep.empty()) { 401 RemovePred = [Config, RemovePred](const SectionBase &Sec) { 402 // Explicitly keep these sections regardless of previous removes. 403 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) != 404 std::end(Config.Keep)) 405 return false; 406 // Otherwise defer to RemovePred. 407 return RemovePred(Sec); 408 }; 409 } 410 411 // This has to be the last predicate assignment. 412 // If the option --keep-symbol has been specified 413 // and at least one of those symbols is present 414 // (equivalently, the updated symbol table is not empty) 415 // the symbol table and the string table should not be removed. 416 if ((!Config.SymbolsToKeep.empty() || Config.KeepFileSymbols) && 417 !Obj.SymbolTable->empty()) { 418 RemovePred = [&Obj, RemovePred](const SectionBase &Sec) { 419 if (&Sec == Obj.SymbolTable || &Sec == Obj.SymbolTable->getStrTab()) 420 return false; 421 return RemovePred(Sec); 422 }; 423 } 424 425 Obj.removeSections(RemovePred); 426 427 if (!Config.AddSection.empty()) { 428 for (const auto &Flag : Config.AddSection) { 429 auto SecPair = Flag.split("="); 430 auto SecName = SecPair.first; 431 auto File = SecPair.second; 432 auto BufOrErr = MemoryBuffer::getFile(File); 433 if (!BufOrErr) 434 reportError(File, BufOrErr.getError()); 435 auto Buf = std::move(*BufOrErr); 436 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart()); 437 auto BufSize = Buf->getBufferSize(); 438 Obj.addSection<OwnedDataSection>(SecName, 439 ArrayRef<uint8_t>(BufPtr, BufSize)); 440 } 441 } 442 443 if (!Config.AddGnuDebugLink.empty()) 444 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink); 445 } 446 447 void ExecuteElfObjcopyOnBinary(const CopyConfig &Config, Binary &Binary, 448 Buffer &Out) { 449 ELFReader Reader(&Binary); 450 std::unique_ptr<Object> Obj = Reader.create(); 451 452 HandleArgs(Config, *Obj, Reader, Reader.getElfType()); 453 454 std::unique_ptr<Writer> Writer = 455 CreateWriter(Config, *Obj, Out, Reader.getElfType()); 456 Writer->finalize(); 457 Writer->write(); 458 } 459 460 // For regular archives this function simply calls llvm::writeArchive, 461 // For thin archives it writes the archive file itself as well as its members. 462 Error deepWriteArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers, 463 bool WriteSymtab, object::Archive::Kind Kind, 464 bool Deterministic, bool Thin) { 465 Error E = 466 writeArchive(ArcName, NewMembers, WriteSymtab, Kind, Deterministic, Thin); 467 if (!Thin || E) 468 return E; 469 for (const NewArchiveMember &Member : NewMembers) { 470 // Internally, FileBuffer will use the buffer created by 471 // FileOutputBuffer::create, for regular files (that is the case for 472 // deepWriteArchive) FileOutputBuffer::create will return OnDiskBuffer. 473 // OnDiskBuffer uses a temporary file and then renames it. So in reality 474 // there is no inefficiency / duplicated in-memory buffers in this case. For 475 // now in-memory buffers can not be completely avoided since 476 // NewArchiveMember still requires them even though writeArchive does not 477 // write them on disk. 478 FileBuffer FB(Member.MemberName); 479 FB.allocate(Member.Buf->getBufferSize()); 480 std::copy(Member.Buf->getBufferStart(), Member.Buf->getBufferEnd(), 481 FB.getBufferStart()); 482 if (auto E = FB.commit()) 483 return E; 484 } 485 return Error::success(); 486 } 487 488 void ExecuteElfObjcopyOnArchive(const CopyConfig &Config, const Archive &Ar) { 489 std::vector<NewArchiveMember> NewArchiveMembers; 490 Error Err = Error::success(); 491 for (const Archive::Child &Child : Ar.children(Err)) { 492 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 493 if (!ChildOrErr) 494 reportError(Ar.getFileName(), ChildOrErr.takeError()); 495 Expected<StringRef> ChildNameOrErr = Child.getName(); 496 if (!ChildNameOrErr) 497 reportError(Ar.getFileName(), ChildNameOrErr.takeError()); 498 499 MemBuffer MB(ChildNameOrErr.get()); 500 ExecuteElfObjcopyOnBinary(Config, **ChildOrErr, MB); 501 502 Expected<NewArchiveMember> Member = 503 NewArchiveMember::getOldMember(Child, true); 504 if (!Member) 505 reportError(Ar.getFileName(), Member.takeError()); 506 Member->Buf = MB.releaseMemoryBuffer(); 507 Member->MemberName = Member->Buf->getBufferIdentifier(); 508 NewArchiveMembers.push_back(std::move(*Member)); 509 } 510 511 if (Err) 512 reportError(Config.InputFilename, std::move(Err)); 513 if (Error E = 514 deepWriteArchive(Config.OutputFilename, NewArchiveMembers, 515 Ar.hasSymbolTable(), Ar.kind(), true, Ar.isThin())) 516 reportError(Config.OutputFilename, std::move(E)); 517 } 518 519 void ExecuteElfObjcopy(const CopyConfig &Config) { 520 Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr = 521 createBinary(Config.InputFilename); 522 if (!BinaryOrErr) 523 reportError(Config.InputFilename, BinaryOrErr.takeError()); 524 525 if (Archive *Ar = dyn_cast<Archive>(BinaryOrErr.get().getBinary())) 526 return ExecuteElfObjcopyOnArchive(Config, *Ar); 527 528 FileBuffer FB(Config.OutputFilename); 529 ExecuteElfObjcopyOnBinary(Config, *BinaryOrErr.get().getBinary(), FB); 530 } 531 532 // ParseObjcopyOptions returns the config and sets the input arguments. If a 533 // help flag is set then ParseObjcopyOptions will print the help messege and 534 // exit. 535 CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) { 536 ObjcopyOptTable T; 537 unsigned MissingArgumentIndex, MissingArgumentCount; 538 llvm::opt::InputArgList InputArgs = 539 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount); 540 541 if (InputArgs.size() == 0) { 542 T.PrintHelp(errs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool"); 543 exit(1); 544 } 545 546 if (InputArgs.hasArg(OBJCOPY_help)) { 547 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool"); 548 exit(0); 549 } 550 551 SmallVector<const char *, 2> Positional; 552 553 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN)) 554 error("unknown argument '" + Arg->getAsString(InputArgs) + "'"); 555 556 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT)) 557 Positional.push_back(Arg->getValue()); 558 559 if (Positional.empty()) 560 error("No input file specified"); 561 562 if (Positional.size() > 2) 563 error("Too many positional arguments"); 564 565 CopyConfig Config; 566 Config.InputFilename = Positional[0]; 567 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1]; 568 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target); 569 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target); 570 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture); 571 572 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo); 573 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink); 574 575 for (auto Arg : InputArgs.filtered(OBJCOPY_redefine_symbol)) { 576 if (!StringRef(Arg->getValue()).contains('=')) 577 error("Bad format for --redefine-sym"); 578 auto Old2New = StringRef(Arg->getValue()).split('='); 579 if (!Config.SymbolsToRename.insert(Old2New).second) 580 error("Multiple redefinition of symbol " + Old2New.first); 581 } 582 583 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section)) 584 Config.ToRemove.push_back(Arg->getValue()); 585 for (auto Arg : InputArgs.filtered(OBJCOPY_keep)) 586 Config.Keep.push_back(Arg->getValue()); 587 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep)) 588 Config.OnlyKeep.push_back(Arg->getValue()); 589 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) 590 Config.AddSection.push_back(Arg->getValue()); 591 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all); 592 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu); 593 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug); 594 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo); 595 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections); 596 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc); 597 Config.StripUnneeded = InputArgs.hasArg(OBJCOPY_strip_unneeded); 598 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo); 599 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden); 600 Config.Weaken = InputArgs.hasArg(OBJCOPY_weaken); 601 Config.DiscardAll = InputArgs.hasArg(OBJCOPY_discard_all); 602 Config.OnlyKeepDebug = InputArgs.hasArg(OBJCOPY_only_keep_debug); 603 Config.KeepFileSymbols = InputArgs.hasArg(OBJCOPY_keep_file_symbols); 604 for (auto Arg : InputArgs.filtered(OBJCOPY_localize_symbol)) 605 Config.SymbolsToLocalize.push_back(Arg->getValue()); 606 for (auto Arg : InputArgs.filtered(OBJCOPY_globalize_symbol)) 607 Config.SymbolsToGlobalize.push_back(Arg->getValue()); 608 for (auto Arg : InputArgs.filtered(OBJCOPY_weaken_symbol)) 609 Config.SymbolsToWeaken.push_back(Arg->getValue()); 610 for (auto Arg : InputArgs.filtered(OBJCOPY_strip_symbol)) 611 Config.SymbolsToRemove.push_back(Arg->getValue()); 612 for (auto Arg : InputArgs.filtered(OBJCOPY_keep_symbol)) 613 Config.SymbolsToKeep.push_back(Arg->getValue()); 614 615 return Config; 616 } 617 618 // ParseStripOptions returns the config and sets the input arguments. If a 619 // help flag is set then ParseStripOptions will print the help messege and 620 // exit. 621 CopyConfig ParseStripOptions(ArrayRef<const char *> ArgsArr) { 622 StripOptTable T; 623 unsigned MissingArgumentIndex, MissingArgumentCount; 624 llvm::opt::InputArgList InputArgs = 625 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount); 626 627 if (InputArgs.size() == 0) { 628 T.PrintHelp(errs(), "llvm-strip <input> [ <output> ]", "strip tool"); 629 exit(1); 630 } 631 632 if (InputArgs.hasArg(STRIP_help)) { 633 T.PrintHelp(outs(), "llvm-strip <input> [ <output> ]", "strip tool"); 634 exit(0); 635 } 636 637 SmallVector<const char *, 2> Positional; 638 for (auto Arg : InputArgs.filtered(STRIP_UNKNOWN)) 639 error("unknown argument '" + Arg->getAsString(InputArgs) + "'"); 640 for (auto Arg : InputArgs.filtered(STRIP_INPUT)) 641 Positional.push_back(Arg->getValue()); 642 643 if (Positional.empty()) 644 error("No input file specified"); 645 646 if (Positional.size() > 2) 647 error("Support for multiple input files is not implemented yet"); 648 649 CopyConfig Config; 650 Config.InputFilename = Positional[0]; 651 Config.OutputFilename = 652 InputArgs.getLastArgValue(STRIP_output, Positional[0]); 653 654 Config.StripDebug = InputArgs.hasArg(STRIP_strip_debug); 655 656 Config.DiscardAll = InputArgs.hasArg(STRIP_discard_all); 657 Config.StripUnneeded = InputArgs.hasArg(STRIP_strip_unneeded); 658 Config.StripAll = InputArgs.hasArg(STRIP_strip_all); 659 660 if (!Config.StripDebug && !Config.StripUnneeded && !Config.DiscardAll) 661 Config.StripAll = true; 662 663 for (auto Arg : InputArgs.filtered(STRIP_remove_section)) 664 Config.ToRemove.push_back(Arg->getValue()); 665 666 for (auto Arg : InputArgs.filtered(STRIP_keep_symbol)) 667 Config.SymbolsToKeep.push_back(Arg->getValue()); 668 669 return Config; 670 } 671 672 int main(int argc, char **argv) { 673 InitLLVM X(argc, argv); 674 ToolName = argv[0]; 675 CopyConfig Config; 676 if (sys::path::stem(ToolName).endswith_lower("strip")) 677 Config = ParseStripOptions(makeArrayRef(argv + 1, argc)); 678 else 679 Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc)); 680 ExecuteElfObjcopy(Config); 681 } 682