1 //===-- llvm-strings.cpp - Printable String dumping utility ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This program is a utility that works like binutils "strings", that is, it 11 // prints out printable strings in a binary, objdump, or archive file. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Object/Binary.h" 16 #include "llvm/Support/CommandLine.h" 17 #include "llvm/Support/Error.h" 18 #include "llvm/Support/MemoryBuffer.h" 19 #include "llvm/Support/PrettyStackTrace.h" 20 #include "llvm/Support/Program.h" 21 #include "llvm/Support/Signals.h" 22 #include <cctype> 23 #include <string> 24 25 using namespace llvm; 26 using namespace llvm::object; 27 28 static cl::list<std::string> InputFileNames(cl::Positional, 29 cl::desc("<input object files>"), 30 cl::ZeroOrMore); 31 32 static cl::opt<bool> 33 PrintFileName("print-file-name", 34 cl::desc("Print the name of the file before each string")); 35 static cl::alias PrintFileNameShort("f", cl::desc(""), 36 cl::aliasopt(PrintFileName)); 37 38 static void strings(raw_ostream &OS, StringRef FileName, StringRef Contents) { 39 auto print = [&OS, FileName](StringRef L) { 40 if (PrintFileName) 41 OS << FileName << ": "; 42 OS << L << '\n'; 43 }; 44 45 const char *P = nullptr, *E = nullptr, *S = nullptr; 46 for (P = Contents.begin(), E = Contents.end(); P < E; ++P) { 47 if (std::isgraph(*P) || std::isblank(*P)) { 48 if (S == nullptr) 49 S = P; 50 } else if (S) { 51 if (P - S > 3) 52 print(StringRef(S, P - S)); 53 S = nullptr; 54 } 55 } 56 if (S && E - S > 3) 57 print(StringRef(S, E - S)); 58 } 59 60 int main(int argc, char **argv) { 61 sys::PrintStackTraceOnErrorSignal(argv[0]); 62 PrettyStackTraceProgram X(argc, argv); 63 64 cl::ParseCommandLineOptions(argc, argv, "llvm string dumper\n"); 65 66 if (InputFileNames.empty()) 67 InputFileNames.push_back("-"); 68 69 for (const auto &File : InputFileNames) { 70 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = 71 MemoryBuffer::getFileOrSTDIN(File); 72 if (std::error_code EC = Buffer.getError()) 73 errs() << File << ": " << EC.message() << '\n'; 74 else 75 strings(llvm::outs(), File == "-" ? "{standard input}" : File, 76 Buffer.get()->getMemBufferRef().getBuffer()); 77 } 78 79 return EXIT_SUCCESS; 80 } 81