llvm-objcopy.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. #include "ObjcopyOptions.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/SmallVector.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/ADT/Twine.h"
  13. #include "llvm/BinaryFormat/ELF.h"
  14. #include "llvm/ObjCopy/COFF/COFFConfig.h"
  15. #include "llvm/ObjCopy/COFF/COFFObjcopy.h"
  16. #include "llvm/ObjCopy/CommonConfig.h"
  17. #include "llvm/ObjCopy/ELF/ELFConfig.h"
  18. #include "llvm/ObjCopy/ELF/ELFObjcopy.h"
  19. #include "llvm/ObjCopy/MachO/MachOConfig.h"
  20. #include "llvm/ObjCopy/MachO/MachOObjcopy.h"
  21. #include "llvm/ObjCopy/ObjCopy.h"
  22. #include "llvm/ObjCopy/wasm/WasmConfig.h"
  23. #include "llvm/ObjCopy/wasm/WasmObjcopy.h"
  24. #include "llvm/Object/Archive.h"
  25. #include "llvm/Object/ArchiveWriter.h"
  26. #include "llvm/Object/Binary.h"
  27. #include "llvm/Object/COFF.h"
  28. #include "llvm/Object/ELFObjectFile.h"
  29. #include "llvm/Object/ELFTypes.h"
  30. #include "llvm/Object/Error.h"
  31. #include "llvm/Object/MachO.h"
  32. #include "llvm/Object/MachOUniversal.h"
  33. #include "llvm/Object/Wasm.h"
  34. #include "llvm/Option/Arg.h"
  35. #include "llvm/Option/ArgList.h"
  36. #include "llvm/Option/Option.h"
  37. #include "llvm/Support/Casting.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Errc.h"
  40. #include "llvm/Support/Error.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/ErrorOr.h"
  43. #include "llvm/Support/FileUtilities.h"
  44. #include "llvm/Support/Host.h"
  45. #include "llvm/Support/InitLLVM.h"
  46. #include "llvm/Support/Memory.h"
  47. #include "llvm/Support/Path.h"
  48. #include "llvm/Support/Process.h"
  49. #include "llvm/Support/SmallVectorMemoryBuffer.h"
  50. #include "llvm/Support/StringSaver.h"
  51. #include "llvm/Support/WithColor.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include <algorithm>
  54. #include <cassert>
  55. #include <cstdlib>
  56. #include <memory>
  57. #include <string>
  58. #include <system_error>
  59. #include <utility>
  60. using namespace llvm;
  61. using namespace llvm::objcopy;
  62. using namespace llvm::object;
  63. // The name this program was invoked as.
  64. static StringRef ToolName;
  65. static ErrorSuccess reportWarning(Error E) {
  66. assert(E);
  67. WithColor::warning(errs(), ToolName) << toString(std::move(E)) << '\n';
  68. return Error::success();
  69. }
  70. static Expected<DriverConfig> getDriverConfig(ArrayRef<const char *> Args) {
  71. StringRef Stem = sys::path::stem(ToolName);
  72. auto Is = [=](StringRef Tool) {
  73. // We need to recognize the following filenames:
  74. //
  75. // llvm-objcopy -> objcopy
  76. // strip-10.exe -> strip
  77. // powerpc64-unknown-freebsd13-objcopy -> objcopy
  78. // llvm-install-name-tool -> install-name-tool
  79. auto I = Stem.rfind_insensitive(Tool);
  80. return I != StringRef::npos &&
  81. (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
  82. };
  83. if (Is("bitcode-strip") || Is("bitcode_strip"))
  84. return parseBitcodeStripOptions(Args, reportWarning);
  85. else if (Is("strip"))
  86. return parseStripOptions(Args, reportWarning);
  87. else if (Is("install-name-tool") || Is("install_name_tool"))
  88. return parseInstallNameToolOptions(Args);
  89. else
  90. return parseObjcopyOptions(Args, reportWarning);
  91. }
  92. /// The function executeObjcopyOnIHex does the dispatch based on the format
  93. /// of the output specified by the command line options.
  94. static Error executeObjcopyOnIHex(ConfigManager &ConfigMgr, MemoryBuffer &In,
  95. raw_ostream &Out) {
  96. // TODO: support output formats other than ELF.
  97. Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
  98. if (!ELFConfig)
  99. return ELFConfig.takeError();
  100. return elf::executeObjcopyOnIHex(ConfigMgr.getCommonConfig(), *ELFConfig, In,
  101. Out);
  102. }
  103. /// The function executeObjcopyOnRawBinary does the dispatch based on the format
  104. /// of the output specified by the command line options.
  105. static Error executeObjcopyOnRawBinary(ConfigManager &ConfigMgr,
  106. MemoryBuffer &In, raw_ostream &Out) {
  107. const CommonConfig &Config = ConfigMgr.getCommonConfig();
  108. switch (Config.OutputFormat) {
  109. case FileFormat::ELF:
  110. // FIXME: Currently, we call elf::executeObjcopyOnRawBinary even if the
  111. // output format is binary/ihex or it's not given. This behavior differs from
  112. // GNU objcopy. See https://bugs.llvm.org/show_bug.cgi?id=42171 for details.
  113. case FileFormat::Binary:
  114. case FileFormat::IHex:
  115. case FileFormat::Unspecified:
  116. Expected<const ELFConfig &> ELFConfig = ConfigMgr.getELFConfig();
  117. if (!ELFConfig)
  118. return ELFConfig.takeError();
  119. return elf::executeObjcopyOnRawBinary(Config, *ELFConfig, In, Out);
  120. }
  121. llvm_unreachable("unsupported output format");
  122. }
  123. /// The function executeObjcopy does the higher level dispatch based on the type
  124. /// of input (raw binary, archive or single object file) and takes care of the
  125. /// format-agnostic modifications, i.e. preserving dates.
  126. static Error executeObjcopy(ConfigManager &ConfigMgr) {
  127. CommonConfig &Config = ConfigMgr.Common;
  128. Expected<FilePermissionsApplier> PermsApplierOrErr =
  129. FilePermissionsApplier::create(Config.InputFilename);
  130. if (!PermsApplierOrErr)
  131. return PermsApplierOrErr.takeError();
  132. std::function<Error(raw_ostream & OutFile)> ObjcopyFunc;
  133. OwningBinary<llvm::object::Binary> BinaryHolder;
  134. std::unique_ptr<MemoryBuffer> MemoryBufferHolder;
  135. if (Config.InputFormat == FileFormat::Binary ||
  136. Config.InputFormat == FileFormat::IHex) {
  137. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  138. MemoryBuffer::getFileOrSTDIN(Config.InputFilename);
  139. if (!BufOrErr)
  140. return createFileError(Config.InputFilename, BufOrErr.getError());
  141. MemoryBufferHolder = std::move(*BufOrErr);
  142. if (Config.InputFormat == FileFormat::Binary)
  143. ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
  144. // Handle FileFormat::Binary.
  145. return executeObjcopyOnRawBinary(ConfigMgr, *MemoryBufferHolder,
  146. OutFile);
  147. };
  148. else
  149. ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
  150. // Handle FileFormat::IHex.
  151. return executeObjcopyOnIHex(ConfigMgr, *MemoryBufferHolder, OutFile);
  152. };
  153. } else {
  154. Expected<OwningBinary<llvm::object::Binary>> BinaryOrErr =
  155. createBinary(Config.InputFilename);
  156. if (!BinaryOrErr)
  157. return createFileError(Config.InputFilename, BinaryOrErr.takeError());
  158. BinaryHolder = std::move(*BinaryOrErr);
  159. if (Archive *Ar = dyn_cast<Archive>(BinaryHolder.getBinary())) {
  160. // Handle Archive.
  161. if (Error E = executeObjcopyOnArchive(ConfigMgr, *Ar))
  162. return E;
  163. } else {
  164. // Handle llvm::object::Binary.
  165. ObjcopyFunc = [&](raw_ostream &OutFile) -> Error {
  166. return executeObjcopyOnBinary(ConfigMgr, *BinaryHolder.getBinary(),
  167. OutFile);
  168. };
  169. }
  170. }
  171. if (ObjcopyFunc) {
  172. if (Config.SplitDWO.empty()) {
  173. // Apply transformations described by Config and store result into
  174. // Config.OutputFilename using specified ObjcopyFunc function.
  175. if (Error E = writeToOutput(Config.OutputFilename, ObjcopyFunc))
  176. return E;
  177. } else {
  178. Config.ExtractDWO = true;
  179. Config.StripDWO = false;
  180. // Copy .dwo tables from the Config.InputFilename into Config.SplitDWO
  181. // file using specified ObjcopyFunc function.
  182. if (Error E = writeToOutput(Config.SplitDWO, ObjcopyFunc))
  183. return E;
  184. Config.ExtractDWO = false;
  185. Config.StripDWO = true;
  186. // Apply transformations described by Config, remove .dwo tables and
  187. // store result into Config.OutputFilename using specified ObjcopyFunc
  188. // function.
  189. if (Error E = writeToOutput(Config.OutputFilename, ObjcopyFunc))
  190. return E;
  191. }
  192. }
  193. if (Error E =
  194. PermsApplierOrErr->apply(Config.OutputFilename, Config.PreserveDates))
  195. return E;
  196. if (!Config.SplitDWO.empty())
  197. if (Error E =
  198. PermsApplierOrErr->apply(Config.SplitDWO, Config.PreserveDates,
  199. static_cast<sys::fs::perms>(0666)))
  200. return E;
  201. return Error::success();
  202. }
  203. int llvm_objcopy_main(int argc, char **argv) {
  204. InitLLVM X(argc, argv);
  205. ToolName = argv[0];
  206. // Expand response files.
  207. // TODO: Move these lines, which are copied from lib/Support/CommandLine.cpp,
  208. // into a separate function in the CommandLine library and call that function
  209. // here. This is duplicated code.
  210. SmallVector<const char *, 20> NewArgv(argv, argv + argc);
  211. BumpPtrAllocator A;
  212. StringSaver Saver(A);
  213. cl::ExpandResponseFiles(Saver,
  214. Triple(sys::getProcessTriple()).isOSWindows()
  215. ? cl::TokenizeWindowsCommandLine
  216. : cl::TokenizeGNUCommandLine,
  217. NewArgv);
  218. auto Args = ArrayRef(NewArgv).drop_front();
  219. Expected<DriverConfig> DriverConfig = getDriverConfig(Args);
  220. if (!DriverConfig) {
  221. logAllUnhandledErrors(DriverConfig.takeError(),
  222. WithColor::error(errs(), ToolName));
  223. return 1;
  224. }
  225. for (ConfigManager &ConfigMgr : DriverConfig->CopyConfigs) {
  226. if (Error E = executeObjcopy(ConfigMgr)) {
  227. logAllUnhandledErrors(std::move(E), WithColor::error(errs(), ToolName));
  228. return 1;
  229. }
  230. }
  231. return 0;
  232. }