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/ADT/StringExtras.h"
16#include "llvm/Object/Binary.h"
17#include "llvm/Option/Arg.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/Option/Option.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/Error.h"
22#include "llvm/Support/Format.h"
23#include "llvm/Support/InitLLVM.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/Support/Program.h"
26#include "llvm/Support/WithColor.h"
27#include <cctype>
28#include <string>
29
30using namespace llvm;
31using namespace llvm::object;
32
33namespace {
34enum ID {
35 OPT_INVALID = 0, // This is not an option ID.
36#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
37#include "Opts.inc"
38#undef OPTION
39};
40
41using namespace llvm::opt;
42#define OPTTABLE_CODE
43#include "Opts.inc"
44
45class StringsOptTable : public opt::OptTable {
46public:
47 StringsOptTable() : OptTable(optionTables()) {
48 setGroupedShortOptions(true);
49 setDashDashParsing(true);
50 }
51};
52
53static StringRef ToolName;
54
55static cl::list<std::string> InputFileNames(cl::Positional,
56 cl::desc("<input object files>"));
57
58static int MinLength = 4;
59static bool PrintFileName;
60
61enum class Radix { None, Octal, Hexadecimal, Decimal };
62static Radix Radix;
63} // namespace
64
65[[noreturn]] static void reportCmdLineError(const Twine &Message) {
66 WithColor::error(OS&: errs(), Prefix: ToolName) << Message << "\n";
67 exit(status: 1);
68}
69
70template <typename T>
71static void parseIntArg(const opt::InputArgList &Args, int ID, T &Value) {
72 if (const opt::Arg *A = Args.getLastArg(Ids: ID)) {
73 StringRef V(A->getValue());
74 if (!llvm::to_integer(V, Value, 0) || Value <= 0)
75 reportCmdLineError(Message: "expected a positive integer, but got '" + V + "'");
76 }
77}
78
79static void strings(raw_ostream &OS, StringRef FileName, StringRef Contents) {
80 auto Print = [&OS, FileName](unsigned Offset, StringRef L) {
81 if (L.size() < static_cast<size_t>(MinLength))
82 return;
83 if (PrintFileName)
84 OS << FileName << ": ";
85 switch (Radix) {
86 case Radix::None:
87 break;
88 case Radix::Octal:
89 OS << format(Fmt: "%7o ", Vals: Offset);
90 break;
91 case Radix::Hexadecimal:
92 OS << format(Fmt: "%7x ", Vals: Offset);
93 break;
94 case Radix::Decimal:
95 OS << format(Fmt: "%7u ", Vals: Offset);
96 break;
97 }
98 OS << L << '\n';
99 };
100
101 const char *B = Contents.begin();
102 const char *P = nullptr, *E = nullptr, *S = nullptr;
103 for (P = Contents.begin(), E = Contents.end(); P < E; ++P) {
104 if (isPrint(C: *P) || *P == '\t') {
105 if (S == nullptr)
106 S = P;
107 } else if (S) {
108 Print(S - B, StringRef(S, P - S));
109 S = nullptr;
110 }
111 }
112 if (S)
113 Print(S - B, StringRef(S, E - S));
114}
115
116int main(int argc, char **argv) {
117 InitLLVM X(argc, argv);
118 BumpPtrAllocator A;
119 StringSaver Saver(A);
120 StringsOptTable Tbl;
121 ToolName = argv[0];
122 opt::InputArgList Args =
123 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver,
124 ErrorFn: [&](StringRef Msg) { reportCmdLineError(Message: Msg); });
125 if (Args.hasArg(Ids: OPT_help)) {
126 Tbl.printHelp(
127 OS&: outs(),
128 Usage: (Twine(ToolName) + " [options] <input object files>").str().c_str(),
129 Title: "llvm string dumper");
130 // TODO Replace this with OptTable API once it adds extrahelp support.
131 outs() << "\nPass @FILE as argument to read options from FILE.\n";
132 return 0;
133 }
134 if (Args.hasArg(Ids: OPT_version)) {
135 outs() << ToolName << '\n';
136 cl::PrintVersionMessage();
137 return 0;
138 }
139
140 parseIntArg(Args, ID: OPT_bytes_EQ, Value&: MinLength);
141 PrintFileName = Args.hasArg(Ids: OPT_print_file_name);
142 Arg *RadixArg = Args.getLastArg(Ids: OPT_radix_EQ);
143 if (!RadixArg) {
144 Radix = Radix::None;
145 } else {
146 Radix = llvm::StringSwitch<enum Radix>(RadixArg->getValue())
147 .Case(S: "o", Value: Radix::Octal)
148 .Case(S: "d", Value: Radix::Decimal)
149 .Case(S: "x", Value: Radix::Hexadecimal)
150 .Default(Value: Radix::None);
151 if (Radix == Radix::None)
152 reportCmdLineError(Message: "'" + StringRef(RadixArg->getValue()) +
153 "' is not a valid value for '" +
154 RadixArg->getSpelling() + "'");
155 }
156
157 if (MinLength == 0) {
158 errs() << "invalid minimum string length 0\n";
159 return EXIT_FAILURE;
160 }
161
162 std::vector<std::string> InputFileNames = Args.getAllArgValues(Id: OPT_INPUT);
163 if (InputFileNames.empty())
164 InputFileNames.push_back(x: "-");
165
166 for (const auto &File : InputFileNames) {
167 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
168 MemoryBuffer::getFileOrSTDIN(Filename: File, /*IsText=*/true);
169 if (std::error_code EC = Buffer.getError())
170 errs() << File << ": " << EC.message() << '\n';
171 else
172 strings(OS&: llvm::outs(), FileName: File == "-" ? "{standard input}" : File,
173 Contents: Buffer.get()->getMemBufferRef().getBuffer());
174 }
175
176 return EXIT_SUCCESS;
177}
178