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/Binary.h" 17 #include "llvm/Object/ELFObjectFile.h" 18 #include "llvm/Object/ELFTypes.h" 19 #include "llvm/Object/Error.h" 20 #include "llvm/Option/Arg.h" 21 #include "llvm/Option/ArgList.h" 22 #include "llvm/Option/Option.h" 23 #include "llvm/Support/Casting.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/Compiler.h" 26 #include "llvm/Support/Error.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/ErrorOr.h" 29 #include "llvm/Support/FileOutputBuffer.h" 30 #include "llvm/Support/InitLLVM.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstdlib> 35 #include <functional> 36 #include <iterator> 37 #include <memory> 38 #include <string> 39 #include <system_error> 40 #include <utility> 41 42 using namespace llvm; 43 using namespace object; 44 using namespace ELF; 45 46 namespace { 47 48 enum ID { 49 OBJCOPY_INVALID = 0, // This is not an option ID. 50 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 51 HELPTEXT, METAVAR, VALUES) \ 52 OBJCOPY_##ID, 53 #include "Opts.inc" 54 #undef OPTION 55 }; 56 57 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; 58 #include "Opts.inc" 59 #undef PREFIX 60 61 static constexpr opt::OptTable::Info ObjcopyInfoTable[] = { 62 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 63 HELPTEXT, METAVAR, VALUES) \ 64 {PREFIX, NAME, HELPTEXT, \ 65 METAVAR, OBJCOPY_##ID, opt::Option::KIND##Class, \ 66 PARAM, FLAGS, OBJCOPY_##GROUP, \ 67 OBJCOPY_##ALIAS, ALIASARGS, VALUES}, 68 #include "Opts.inc" 69 #undef OPTION 70 }; 71 72 class ObjcopyOptTable : public opt::OptTable { 73 public: 74 ObjcopyOptTable() : OptTable(ObjcopyInfoTable, true) {} 75 }; 76 77 } // namespace 78 79 // The name this program was invoked as. 80 static StringRef ToolName; 81 82 namespace llvm { 83 84 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) { 85 errs() << ToolName << ": " << Message << ".\n"; 86 errs().flush(); 87 exit(1); 88 } 89 90 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) { 91 assert(EC); 92 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; 93 exit(1); 94 } 95 96 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) { 97 assert(E); 98 std::string Buf; 99 raw_string_ostream OS(Buf); 100 logAllUnhandledErrors(std::move(E), OS, ""); 101 OS.flush(); 102 errs() << ToolName << ": '" << File << "': " << Buf; 103 exit(1); 104 } 105 106 } // end namespace llvm 107 108 struct CopyConfig { 109 StringRef OutputFilename; 110 StringRef InputFilename; 111 StringRef OutputFormat; 112 StringRef InputFormat; 113 StringRef BinaryArch; 114 115 StringRef SplitDWO; 116 StringRef AddGnuDebugLink; 117 std::vector<StringRef> ToRemove; 118 std::vector<StringRef> Keep; 119 std::vector<StringRef> OnlyKeep; 120 std::vector<StringRef> AddSection; 121 bool StripAll; 122 bool StripAllGNU; 123 bool StripDebug; 124 bool StripSections; 125 bool StripNonAlloc; 126 bool StripDWO; 127 bool ExtractDWO; 128 bool LocalizeHidden; 129 }; 130 131 using SectionPred = std::function<bool(const SectionBase &Sec)>; 132 133 bool IsDWOSection(const SectionBase &Sec) { return Sec.Name.endswith(".dwo"); } 134 135 bool OnlyKeepDWOPred(const Object &Obj, const SectionBase &Sec) { 136 // We can't remove the section header string table. 137 if (&Sec == Obj.SectionNames) 138 return false; 139 // Short of keeping the string table we want to keep everything that is a DWO 140 // section and remove everything else. 141 return !IsDWOSection(Sec); 142 } 143 144 std::unique_ptr<Writer> CreateWriter(const CopyConfig &Config, Object &Obj, 145 StringRef File, ElfType OutputElfType) { 146 if (Config.OutputFormat == "binary") { 147 return llvm::make_unique<BinaryWriter>(File, Obj); 148 } 149 // Depending on the initial ELFT and OutputFormat we need a different Writer. 150 switch (OutputElfType) { 151 case ELFT_ELF32LE: 152 return llvm::make_unique<ELFWriter<ELF32LE>>(File, Obj, 153 !Config.StripSections); 154 case ELFT_ELF64LE: 155 return llvm::make_unique<ELFWriter<ELF64LE>>(File, Obj, 156 !Config.StripSections); 157 case ELFT_ELF32BE: 158 return llvm::make_unique<ELFWriter<ELF32BE>>(File, Obj, 159 !Config.StripSections); 160 case ELFT_ELF64BE: 161 return llvm::make_unique<ELFWriter<ELF64BE>>(File, Obj, 162 !Config.StripSections); 163 } 164 llvm_unreachable("Invalid output format"); 165 } 166 167 void SplitDWOToFile(const CopyConfig &Config, const Reader &Reader, 168 StringRef File, ElfType OutputElfType) { 169 auto DWOFile = Reader.create(); 170 DWOFile->removeSections( 171 [&](const SectionBase &Sec) { return OnlyKeepDWOPred(*DWOFile, Sec); }); 172 auto Writer = CreateWriter(Config, *DWOFile, File, OutputElfType); 173 Writer->finalize(); 174 Writer->write(); 175 } 176 177 // This function handles the high level operations of GNU objcopy including 178 // handling command line options. It's important to outline certain properties 179 // we expect to hold of the command line operations. Any operation that "keeps" 180 // should keep regardless of a remove. Additionally any removal should respect 181 // any previous removals. Lastly whether or not something is removed shouldn't 182 // depend a) on the order the options occur in or b) on some opaque priority 183 // system. The only priority is that keeps/copies overrule removes. 184 void HandleArgs(const CopyConfig &Config, Object &Obj, const Reader &Reader, 185 ElfType OutputElfType) { 186 187 if (!Config.SplitDWO.empty()) { 188 SplitDWOToFile(Config, Reader, Config.SplitDWO, OutputElfType); 189 } 190 191 // Localize: 192 193 if (Config.LocalizeHidden) { 194 Obj.SymbolTable->localize([](const Symbol &Sym) { 195 return Sym.Visibility == STV_HIDDEN || Sym.Visibility == STV_INTERNAL; 196 }); 197 } 198 199 SectionPred RemovePred = [](const SectionBase &) { return false; }; 200 201 // Removes: 202 203 if (!Config.ToRemove.empty()) { 204 RemovePred = [&Config](const SectionBase &Sec) { 205 return std::find(std::begin(Config.ToRemove), std::end(Config.ToRemove), 206 Sec.Name) != std::end(Config.ToRemove); 207 }; 208 } 209 210 if (Config.StripDWO || !Config.SplitDWO.empty()) 211 RemovePred = [RemovePred](const SectionBase &Sec) { 212 return IsDWOSection(Sec) || RemovePred(Sec); 213 }; 214 215 if (Config.ExtractDWO) 216 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 217 return OnlyKeepDWOPred(Obj, Sec) || RemovePred(Sec); 218 }; 219 220 if (Config.StripAllGNU) 221 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 222 if (RemovePred(Sec)) 223 return true; 224 if ((Sec.Flags & SHF_ALLOC) != 0) 225 return false; 226 if (&Sec == Obj.SectionNames) 227 return false; 228 switch (Sec.Type) { 229 case SHT_SYMTAB: 230 case SHT_REL: 231 case SHT_RELA: 232 case SHT_STRTAB: 233 return true; 234 } 235 return Sec.Name.startswith(".debug"); 236 }; 237 238 if (Config.StripSections) { 239 RemovePred = [RemovePred](const SectionBase &Sec) { 240 return RemovePred(Sec) || (Sec.Flags & SHF_ALLOC) == 0; 241 }; 242 } 243 244 if (Config.StripDebug) { 245 RemovePred = [RemovePred](const SectionBase &Sec) { 246 return RemovePred(Sec) || Sec.Name.startswith(".debug"); 247 }; 248 } 249 250 if (Config.StripNonAlloc) 251 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 252 if (RemovePred(Sec)) 253 return true; 254 if (&Sec == Obj.SectionNames) 255 return false; 256 return (Sec.Flags & SHF_ALLOC) == 0; 257 }; 258 259 if (Config.StripAll) 260 RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { 261 if (RemovePred(Sec)) 262 return true; 263 if (&Sec == Obj.SectionNames) 264 return false; 265 if (Sec.Name.startswith(".gnu.warning")) 266 return false; 267 return (Sec.Flags & SHF_ALLOC) == 0; 268 }; 269 270 // Explicit copies: 271 272 if (!Config.OnlyKeep.empty()) { 273 RemovePred = [&Config, RemovePred, &Obj](const SectionBase &Sec) { 274 // Explicitly keep these sections regardless of previous removes. 275 if (std::find(std::begin(Config.OnlyKeep), std::end(Config.OnlyKeep), 276 Sec.Name) != std::end(Config.OnlyKeep)) 277 return false; 278 279 // Allow all implicit removes. 280 if (RemovePred(Sec)) 281 return true; 282 283 // Keep special sections. 284 if (Obj.SectionNames == &Sec) 285 return false; 286 if (Obj.SymbolTable == &Sec || Obj.SymbolTable->getStrTab() == &Sec) 287 return false; 288 289 // Remove everything else. 290 return true; 291 }; 292 } 293 294 if (!Config.Keep.empty()) { 295 RemovePred = [Config, RemovePred](const SectionBase &Sec) { 296 // Explicitly keep these sections regardless of previous removes. 297 if (std::find(std::begin(Config.Keep), std::end(Config.Keep), Sec.Name) != 298 std::end(Config.Keep)) 299 return false; 300 // Otherwise defer to RemovePred. 301 return RemovePred(Sec); 302 }; 303 } 304 305 Obj.removeSections(RemovePred); 306 307 if (!Config.AddSection.empty()) { 308 for (const auto &Flag : Config.AddSection) { 309 auto SecPair = Flag.split("="); 310 auto SecName = SecPair.first; 311 auto File = SecPair.second; 312 auto BufOrErr = MemoryBuffer::getFile(File); 313 if (!BufOrErr) 314 reportError(File, BufOrErr.getError()); 315 auto Buf = std::move(*BufOrErr); 316 auto BufPtr = reinterpret_cast<const uint8_t *>(Buf->getBufferStart()); 317 auto BufSize = Buf->getBufferSize(); 318 Obj.addSection<OwnedDataSection>(SecName, 319 ArrayRef<uint8_t>(BufPtr, BufSize)); 320 } 321 } 322 323 if (!Config.AddGnuDebugLink.empty()) { 324 Obj.addSection<GnuDebugLinkSection>(Config.AddGnuDebugLink); 325 } 326 } 327 328 std::unique_ptr<Reader> CreateReader(StringRef InputFilename, 329 ElfType &OutputElfType) { 330 // Right now we can only read ELF files so there's only one reader; 331 auto Out = llvm::make_unique<ELFReader>(InputFilename); 332 // We need to set the default ElfType for output. 333 OutputElfType = Out->getElfType(); 334 return std::move(Out); 335 } 336 337 void ExecuteElfObjcopy(const CopyConfig &Config) { 338 ElfType OutputElfType; 339 auto Reader = CreateReader(Config.InputFilename, OutputElfType); 340 auto Obj = Reader->create(); 341 auto Writer = 342 CreateWriter(Config, *Obj, Config.OutputFilename, OutputElfType); 343 HandleArgs(Config, *Obj, *Reader, OutputElfType); 344 Writer->finalize(); 345 Writer->write(); 346 } 347 348 // ParseObjcopyOptions returns the config and sets the input arguments. If a 349 // help flag is set then ParseObjcopyOptions will print the help messege and 350 // exit. 351 CopyConfig ParseObjcopyOptions(ArrayRef<const char *> ArgsArr) { 352 ObjcopyOptTable T; 353 unsigned MissingArgumentIndex, MissingArgumentCount; 354 llvm::opt::InputArgList InputArgs = 355 T.ParseArgs(ArgsArr, MissingArgumentIndex, MissingArgumentCount); 356 357 if (InputArgs.size() == 0 || InputArgs.hasArg(OBJCOPY_help)) { 358 T.PrintHelp(outs(), "llvm-objcopy <input> [ <output> ]", "objcopy tool"); 359 exit(0); 360 } 361 362 SmallVector<const char *, 2> Positional; 363 364 for (auto Arg : InputArgs.filtered(OBJCOPY_UNKNOWN)) 365 error("unknown argument '" + Arg->getAsString(InputArgs) + "'"); 366 367 for (auto Arg : InputArgs.filtered(OBJCOPY_INPUT)) 368 Positional.push_back(Arg->getValue()); 369 370 if (Positional.empty()) 371 error("No input file specified"); 372 373 if (Positional.size() > 2) 374 error("Too many positional arguments"); 375 376 CopyConfig Config; 377 Config.InputFilename = Positional[0]; 378 Config.OutputFilename = Positional[Positional.size() == 1 ? 0 : 1]; 379 Config.InputFormat = InputArgs.getLastArgValue(OBJCOPY_input_target); 380 Config.OutputFormat = InputArgs.getLastArgValue(OBJCOPY_output_target); 381 Config.BinaryArch = InputArgs.getLastArgValue(OBJCOPY_binary_architecture); 382 383 Config.SplitDWO = InputArgs.getLastArgValue(OBJCOPY_split_dwo); 384 Config.AddGnuDebugLink = InputArgs.getLastArgValue(OBJCOPY_add_gnu_debuglink); 385 for (auto Arg : InputArgs.filtered(OBJCOPY_remove_section)) 386 Config.ToRemove.push_back(Arg->getValue()); 387 for (auto Arg : InputArgs.filtered(OBJCOPY_keep)) 388 Config.Keep.push_back(Arg->getValue()); 389 for (auto Arg : InputArgs.filtered(OBJCOPY_only_keep)) 390 Config.OnlyKeep.push_back(Arg->getValue()); 391 for (auto Arg : InputArgs.filtered(OBJCOPY_add_section)) 392 Config.AddSection.push_back(Arg->getValue()); 393 Config.StripAll = InputArgs.hasArg(OBJCOPY_strip_all); 394 Config.StripAllGNU = InputArgs.hasArg(OBJCOPY_strip_all_gnu); 395 Config.StripDebug = InputArgs.hasArg(OBJCOPY_strip_debug); 396 Config.StripDWO = InputArgs.hasArg(OBJCOPY_strip_dwo); 397 Config.StripSections = InputArgs.hasArg(OBJCOPY_strip_sections); 398 Config.StripNonAlloc = InputArgs.hasArg(OBJCOPY_strip_non_alloc); 399 Config.ExtractDWO = InputArgs.hasArg(OBJCOPY_extract_dwo); 400 Config.LocalizeHidden = InputArgs.hasArg(OBJCOPY_localize_hidden); 401 402 return Config; 403 } 404 405 int main(int argc, char **argv) { 406 InitLLVM X(argc, argv); 407 ToolName = argv[0]; 408 409 CopyConfig Config = ParseObjcopyOptions(makeArrayRef(argv + 1, argc)); 410 ExecuteElfObjcopy(Config); 411 } 412