llvm-objcopy.cpp 13 KB

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