llvm-objcopy.cpp 12 KB

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