source: icGREP/icgrep-devel/icgrep/icgrep.cpp @ 5167

Last change on this file since 5167 was 5167, checked in by cameron, 3 years ago

Flags for future syntax options

File size: 13.6 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <cstdio>
8#include <vector>
9#include <llvm/Support/CommandLine.h>
10#include <llvm/Support/ErrorHandling.h>
11#include <llvm/Support/Signals.h>
12#include <re/re_alt.h>
13#include <re/re_parser.h>
14#include <grep_engine.h>
15#include <fstream>
16#include <string>
17
18#include <boost/uuid/sha1.hpp>
19#include <toolchain.h>
20#include <re/re_toolchain.h>
21#include <pablo/pablo_toolchain.h>
22#include <mutex>
23#include <boost/filesystem.hpp>
24
25#include <iostream> // MEEE
26
27#ifdef PRINT_TIMING_INFORMATION
28#include <hrtime.h>
29#include <util/papi_helper.hpp>
30#endif
31
32static cl::OptionCategory LegacyGrepOptions("A. Standard Grep Options",
33                                       "These are standard grep options intended for compatibility with typical grep usage.");
34enum RE_Syntax {FixedStrings, BRE, ERE, PCRE};
35
36#ifdef FUTURE
37static cl::OptionCategory RegexpOptions("Regular Expression Interpretation", "These options control regular expression interpretation");
38static cl::opt<RE_Syntax> RegexpSyntax(cl::desc("Regular expression syntax:"),
39    cl::values(
40        clEnumValN(FixedStrings, "F", "Fixed strings, separated by newlines"),
41        clEnumValN(BRE, "G", "Posix basic regular expression (BRE) syntax"),
42        clEnumValN(ERE, "E", "Posix extened regular expression (ERE) syntax"),
43        clEnumValN(PCRE, "P", "Perl-compatible regular expression (PCRE) syntax - default"),
44               clEnumValEnd), cl::cat(LegacyGrepOptions), cl::Grouping, cl::init(PCRE));
45#endif
46
47static cl::opt<bool> UTF_16("UTF-16", cl::desc("Regular expressions over the UTF-16 representation of Unicode."), cl::cat(LegacyGrepOptions));
48static cl::OptionCategory EnhancedGrepOptions("B. Enhanced Grep Options",
49                                       "These are additional options for icgrep functionality and performance.");
50static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(LegacyGrepOptions), cl::Grouping);
51static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
52
53static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
54
55static cl::opt<bool> EnterDirectoriesRecursively("r", cl::desc("Recursively process files within directories, (but follow only top-level symlinks unless -R)."), cl::cat(LegacyGrepOptions), cl::Grouping);
56static cl::opt<bool> FollowSubdirectorySymlinks("R", cl::desc("Recursively process files within directories, following symlinks at all levels."), cl::cat(LegacyGrepOptions), cl::Grouping);
57static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(LegacyGrepOptions), cl::Grouping);
58
59
60static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(LegacyGrepOptions));
61static cl::opt<std::string> RegexFilename("f", cl::desc("Take regular expressions (one per line) from a file"), cl::value_desc("regex file"), cl::init(""), cl::cat(LegacyGrepOptions));
62static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""));
63
64static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
65
66static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
67         Gives you colored output + back-referencing capability."), cl::cat(EnhancedGrepOptions));
68
69
70static std::vector<std::string> allFiles;
71//
72// Handler for errors reported through llvm::report_fatal_error.  Report
73// and signal error code 2 (grep convention).
74//
75static void icgrep_error_handler(void *UserData, const std::string &Message,
76                             bool GenCrashDiag) {
77
78    // Modified from LLVM's internal report_fatal_error logic.
79    SmallVector<char, 64> Buffer;
80    raw_svector_ostream OS(Buffer);
81    OS << "icgrep ERROR: " << Message << "\n";
82    StringRef MessageStr = OS.str();
83    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
84    (void)written; // If something went wrong, we deliberately just give up.
85
86    // Run the interrupt handlers to make sure any special cleanups get done, in
87    // particular that we remove files registered with RemoveFileOnSignal.
88    llvm::sys::RunInterruptHandlers();
89    exit(2);
90}
91
92static std::string allREs;
93static re::ModeFlagSet globalFlags = 0;
94
95re::RE * get_icgrep_RE() {
96 
97    //std::vector<std::string> regexVector;
98    if (RegexFilename != "") {
99        std::ifstream regexFile(RegexFilename.c_str());
100        std::string r;
101        if (regexFile.is_open()) {
102            while (std::getline(regexFile, r)) {
103                regexVector.push_back(r);
104            }
105            regexFile.close();
106        }
107    }
108   
109    // if there are no regexes specified through -e or -f, the first positional argument
110    // must be a regex, not an input file.
111   
112    if (regexVector.size() == 0) {
113        regexVector.push_back(inputFiles[0]);
114        inputFiles.erase(inputFiles.begin());
115    }
116    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
117
118 
119    std::vector<re::RE *> REs;
120    re::RE * re_ast = nullptr;
121    for (unsigned i = 0; i < regexVector.size(); i++) {
122        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
123        REs.push_back(re_ast);
124        allREs += regexVector[i] + "\n";
125    }
126    if (REs.size() > 1) {
127        re_ast = re::makeAlt(REs.begin(), REs.end());
128    }
129   
130    return re_ast;
131}
132
133std::string sha1sum(const std::string & str) {
134    char buffer[41];    // 40 hex-digits and the terminating null
135    unsigned int digest[5];     // 160 bits in total
136
137    boost::uuids::detail::sha1 sha1;
138    sha1.process_bytes(str.c_str(), str.size());
139    sha1.get_digest(digest);
140    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
141             digest[0], digest[1], digest[2], digest[3], digest[4]);
142    return std::string(buffer);
143}
144
145std::vector<size_t> total_CountOnly;
146std::mutex count_mutex;
147size_t fileCount;
148void *DoGrep(void *args)
149{
150    size_t fileIdx;
151    GrepEngine * grepEngine = (GrepEngine *)args;
152
153    count_mutex.lock();
154    fileIdx = fileCount;
155    fileCount++;
156    count_mutex.unlock();
157
158    while (fileIdx < allFiles.size()){
159        grepEngine->doGrep(allFiles[fileIdx], fileIdx, CountOnly, total_CountOnly, UTF_16);
160       
161        count_mutex.lock();
162        fileIdx = fileCount;
163        fileCount++;
164        count_mutex.unlock();
165    }
166
167    pthread_exit(NULL);
168}
169
170
171// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
172bool isArgUnwantedForAll(char *argument) {
173    std::vector<std::string> unwantedFlags = {"-gs"};
174    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
175        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
176            return true;
177        }
178    }
179    return false;
180}
181// Filters out the command line strings that shouldn't be passed on to Grep
182bool isArgUnwantedForGrep(char *argument) {
183    std::vector<std::string> unwantedFlags = {"-n"};
184
185    for (unsigned i = 0; i < inputFiles.size(); ++i){
186        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
187            return true;
188        }
189    }
190
191    for (unsigned i = 0; i < inputFiles.size(); ++i){    // filter out input content files.
192        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
193            return true;
194        }
195    }
196
197    return false;
198}
199// Filters out the command line strings that shouldn't be passed on to IcGrep
200bool isArgUnwantedForIcGrep(char *argument) {
201    bool isUnwanted = false;
202    std::vector<std::string> unwantedFlags = {"-c"};
203
204    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
205        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
206            isUnwanted = true;
207        }
208    }
209
210    return isUnwanted;
211}
212
213/*
214* Constructs a shell command that calls icgrep and then pipes the output to grep.
215* Then executs this shell command using the "system()" function.
216* This allows the output to be colored since all output is piped to grep.
217*/ 
218void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
219    std::string icGrepArguments = "";
220    std::string grepArguments = "";
221
222    // Construct the shell arguments for icgrep and grep
223    // by filtering out the command line arguments passed into this process.
224    for (int i = 1; i < argc; i++) {
225        if (!isArgUnwantedForAll(argv[i])) {
226
227            if (!isArgUnwantedForIcGrep(argv[i])) {
228                // Wrap everything in quotes since the arguments passed into this program had them stripped by bash.
229                icGrepArguments.append("\"");       
230                icGrepArguments.append(argv[i]);
231                icGrepArguments.append("\" ");
232            }
233
234            if (!isArgUnwantedForGrep(argv[i])) {
235                grepArguments.append("\"");
236                grepArguments.append(argv[i]);
237                grepArguments.append("\" ");
238            }
239        }
240    }
241
242    std::string systemCall = argv[0];
243    systemCall.append(" ");
244    systemCall.append(icGrepArguments);
245    systemCall.append(" ");
246    systemCall.append(" | grep --color=always -P ");
247    systemCall.append(grepArguments);
248
249    system(systemCall.c_str());
250}
251
252
253// This is a stub, to be expanded later.
254bool excludeDirectory(boost::filesystem::path dirpath) { return dirpath.filename() == ".svn";}
255
256std::vector<std::string> getFullFileList(cl::list<std::string> & inputFiles) {
257    using namespace boost::filesystem;
258    symlink_option follow_symlink = FollowSubdirectorySymlinks ? symlink_option::recurse : symlink_option::none;
259    std::vector<std::string> expanded_paths;
260    boost::system::error_code errc;
261    if (FollowSubdirectorySymlinks) {
262        EnterDirectoriesRecursively = true;
263    }
264    for (auto & f : inputFiles) {
265        path p(f);
266        if (EnterDirectoriesRecursively && is_directory(p)) {
267            if (!excludeDirectory(p)) {
268                recursive_directory_iterator di(p, follow_symlink, errc), end;
269                if (errc) {
270                    // If we cannot enter the directory, keep it in the list of files.
271                    expanded_paths.push_back(f); 
272                    continue;
273                }
274                while (di != end) {
275                    auto & e = di->path();
276                    if (is_directory(e)) {
277                        if (excludeDirectory(e)) di.no_push();
278                    }
279                    else expanded_paths.push_back(e.string());
280                    di.increment(errc);
281                    if (errc) {
282                        expanded_paths.push_back(e.string()); 
283                    }
284                }
285            }
286        }
287        else expanded_paths.push_back(p.string());
288    }
289    return expanded_paths;
290}
291
292
293int main(int argc, char *argv[]) {
294    llvm::install_fatal_error_handler(&icgrep_error_handler);
295    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags(), pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
296    cl::ParseCommandLineOptions(argc, argv);
297#ifdef FUTURE
298    if (RegexpSyntax != RE_Syntax::PCRE) {
299        llvm::report_fatal_error("Sorry, only PCRE syntax is fully supported\n.");
300    }
301#endif
302    re::RE * re_ast = get_icgrep_RE();
303    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
304
305    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
306        pipeIcGrepOutputToGrep(argc, argv);
307        return 0;   // icgrep is called again, so we need to end this process.
308    }
309   
310    GrepEngine grepEngine;
311    grepEngine.grepCodeGen(module_name, re_ast, CountOnly, UTF_16);
312    //std::cerr << "grepCodeGen complete";
313
314    releaseSlabAllocatorMemory();
315   
316    allFiles = getFullFileList(inputFiles);
317   
318    initResult(allFiles);
319    for (unsigned i=0; i < allFiles.size(); ++i){
320        total_CountOnly.push_back(0);
321    }
322
323    if (Threads <= 1) {
324
325        #ifdef PRINT_TIMING_INFORMATION
326        // PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY
327        // PAPI_RES_STL, PAPI_BR_MSP, PAPI_LST_INS, PAPI_L1_TCM
328        papi::PapiCounter<4> papiCounters({PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY});
329        #endif
330        for (unsigned i = 0; i != allFiles.size(); ++i) {
331            #ifdef PRINT_TIMING_INFORMATION
332            papiCounters.start();
333            const timestamp_t execution_start = read_cycle_counter();
334            #endif
335            grepEngine.doGrep(allFiles[i], i, CountOnly, total_CountOnly, UTF_16);
336            #ifdef PRINT_TIMING_INFORMATION
337            const timestamp_t execution_end = read_cycle_counter();
338            papiCounters.stop();
339            std::cerr << "EXECUTION TIME: " << allFiles[i] << ":" << "CYCLES|" << (execution_end - execution_start) << papiCounters << std::endl;
340            #endif
341        }       
342    } else if (Threads > 1) {
343        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
344        pthread_t threads[numOfThreads];
345
346        for(unsigned long i = 0; i < numOfThreads; ++i){
347            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
348            if (rc) {
349                llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
350            }
351        }
352
353        for(unsigned i = 0; i < numOfThreads; ++i) {
354            void * status = nullptr;
355            const int rc = pthread_join(threads[i], &status);
356            if (rc) {
357                llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
358            }
359        }
360    }
361   
362    PrintResult(CountOnly, total_CountOnly);
363   
364    return 0;
365}
Note: See TracBrowser for help on using the repository browser.