]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/tools/llvm-strings/llvm-strings.cpp
Merge commit 3537338d1ab9 from llvm git (by Nikolas Klauser):
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / tools / llvm-strings / llvm-strings.cpp
1 //===-- llvm-strings.cpp - Printable String dumping utility ---------------===//
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 //
9 // This program is a utility that works like binutils "strings", that is, it
10 // prints out printable strings in a binary, objdump, or archive file.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Opts.inc"
15 #include "llvm/Object/Binary.h"
16 #include "llvm/Option/Arg.h"
17 #include "llvm/Option/ArgList.h"
18 #include "llvm/Option/Option.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Error.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/InitLLVM.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Program.h"
25 #include "llvm/Support/WithColor.h"
26 #include <cctype>
27 #include <string>
28
29 using namespace llvm;
30 using namespace llvm::object;
31
32 namespace {
33 enum ID {
34   OPT_INVALID = 0, // This is not an option ID.
35 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
36                HELPTEXT, METAVAR, VALUES)                                      \
37   OPT_##ID,
38 #include "Opts.inc"
39 #undef OPTION
40 };
41
42 #define PREFIX(NAME, VALUE)                                                    \
43   static constexpr StringLiteral NAME##_init[] = VALUE;                        \
44   static constexpr ArrayRef<StringLiteral> NAME(NAME##_init,                   \
45                                                 std::size(NAME##_init) - 1);
46 #include "Opts.inc"
47 #undef PREFIX
48
49 static constexpr opt::OptTable::Info InfoTable[] = {
50 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
51                HELPTEXT, METAVAR, VALUES)                                      \
52   {                                                                            \
53       PREFIX,      NAME,      HELPTEXT,                                        \
54       METAVAR,     OPT_##ID,  opt::Option::KIND##Class,                        \
55       PARAM,       FLAGS,     OPT_##GROUP,                                     \
56       OPT_##ALIAS, ALIASARGS, VALUES},
57 #include "Opts.inc"
58 #undef OPTION
59 };
60
61 class StringsOptTable : public opt::GenericOptTable {
62 public:
63   StringsOptTable() : GenericOptTable(InfoTable) {
64     setGroupedShortOptions(true);
65   }
66 };
67 } // namespace
68
69 static StringRef ToolName;
70
71 static cl::list<std::string> InputFileNames(cl::Positional,
72                                             cl::desc("<input object files>"));
73
74 static int MinLength = 4;
75 static bool PrintFileName;
76
77 enum radix { none, octal, hexadecimal, decimal };
78 static radix Radix;
79
80 [[noreturn]] static void reportCmdLineError(const Twine &Message) {
81   WithColor::error(errs(), ToolName) << Message << "\n";
82   exit(1);
83 }
84
85 template <typename T>
86 static void parseIntArg(const opt::InputArgList &Args, int ID, T &Value) {
87   if (const opt::Arg *A = Args.getLastArg(ID)) {
88     StringRef V(A->getValue());
89     if (!llvm::to_integer(V, Value, 0) || Value <= 0)
90       reportCmdLineError("expected a positive integer, but got '" + V + "'");
91   }
92 }
93
94 static void strings(raw_ostream &OS, StringRef FileName, StringRef Contents) {
95   auto print = [&OS, FileName](unsigned Offset, StringRef L) {
96     if (L.size() < static_cast<size_t>(MinLength))
97       return;
98     if (PrintFileName)
99       OS << FileName << ": ";
100     switch (Radix) {
101     case none:
102       break;
103     case octal:
104       OS << format("%7o ", Offset);
105       break;
106     case hexadecimal:
107       OS << format("%7x ", Offset);
108       break;
109     case decimal:
110       OS << format("%7u ", Offset);
111       break;
112     }
113     OS << L << '\n';
114   };
115
116   const char *B = Contents.begin();
117   const char *P = nullptr, *E = nullptr, *S = nullptr;
118   for (P = Contents.begin(), E = Contents.end(); P < E; ++P) {
119     if (isPrint(*P) || *P == '\t') {
120       if (S == nullptr)
121         S = P;
122     } else if (S) {
123       print(S - B, StringRef(S, P - S));
124       S = nullptr;
125     }
126   }
127   if (S)
128     print(S - B, StringRef(S, E - S));
129 }
130
131 int main(int argc, char **argv) {
132   InitLLVM X(argc, argv);
133   BumpPtrAllocator A;
134   StringSaver Saver(A);
135   StringsOptTable Tbl;
136   ToolName = argv[0];
137   opt::InputArgList Args =
138       Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver,
139                     [&](StringRef Msg) { reportCmdLineError(Msg); });
140   if (Args.hasArg(OPT_help)) {
141     Tbl.printHelp(
142         outs(),
143         (Twine(ToolName) + " [options] <input object files>").str().c_str(),
144         "llvm string dumper");
145     // TODO Replace this with OptTable API once it adds extrahelp support.
146     outs() << "\nPass @FILE as argument to read options from FILE.\n";
147     return 0;
148   }
149   if (Args.hasArg(OPT_version)) {
150     outs() << ToolName << '\n';
151     cl::PrintVersionMessage();
152     return 0;
153   }
154
155   parseIntArg(Args, OPT_bytes_EQ, MinLength);
156   PrintFileName = Args.hasArg(OPT_print_file_name);
157   StringRef R = Args.getLastArgValue(OPT_radix_EQ);
158   if (R.empty())
159     Radix = none;
160   else if (R == "o")
161     Radix = octal;
162   else if (R == "d")
163     Radix = decimal;
164   else if (R == "x")
165     Radix = hexadecimal;
166   else
167     reportCmdLineError("--radix value should be one of: '' (no offset), 'o' "
168                        "(octal), 'd' (decimal), 'x' (hexadecimal)");
169
170   if (MinLength == 0) {
171     errs() << "invalid minimum string length 0\n";
172     return EXIT_FAILURE;
173   }
174
175   std::vector<std::string> InputFileNames = Args.getAllArgValues(OPT_INPUT);
176   if (InputFileNames.empty())
177     InputFileNames.push_back("-");
178
179   for (const auto &File : InputFileNames) {
180     ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
181         MemoryBuffer::getFileOrSTDIN(File);
182     if (std::error_code EC = Buffer.getError())
183       errs() << File << ": " << EC.message() << '\n';
184     else
185       strings(llvm::outs(), File == "-" ? "{standard input}" : File,
186               Buffer.get()->getMemBufferRef().getBuffer());
187   }
188
189   return EXIT_SUCCESS;
190 }