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

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

Include codegen options in -help

File size: 8.5 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 <re/re_alt.h>
11#include <re/re_parser.h>
12#include <grep_engine.h>
13#include <fstream>
14#include <string>
15
16#include <boost/uuid/sha1.hpp>
17#include <toolchain.h>
18#include <re/re_toolchain.h>
19#include <pablo/pablo_toolchain.h>
20#include <mutex>
21
22#include <iostream> // MEEE
23static cl::OptionCategory LegacyGrepOptions("A. Standard Grep Options",
24                                       "These are standard grep options intended for compatibility with typical grep usage.");
25static cl::OptionCategory EnhancedGrepOptions("B. Enhanced Grep Options",
26                                       "These are additional options for icgrep functionality and performance.");
27static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(LegacyGrepOptions));
28static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
29
30static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
31
32static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(LegacyGrepOptions));
33
34
35static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(LegacyGrepOptions));
36static 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));
37static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""));
38
39static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
40
41static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
42         Gives you colored output + back-referencing capability."), cl::cat(EnhancedGrepOptions));
43
44
45static std::string allREs;
46static re::ModeFlagSet globalFlags = 0;
47
48re::RE * get_icgrep_RE() {
49 
50    //std::vector<std::string> regexVector;
51    if (RegexFilename != "") {
52        std::ifstream regexFile(RegexFilename.c_str());
53        std::string r;
54        if (regexFile.is_open()) {
55            while (std::getline(regexFile, r)) {
56                regexVector.push_back(r);
57            }
58            regexFile.close();
59        }
60    }
61   
62    // if there are no regexes specified through -e or -f, the first positional argument
63    // must be a regex, not an input file.
64   
65    if (regexVector.size() == 0) {
66        regexVector.push_back(inputFiles[0]);
67        inputFiles.erase(inputFiles.begin());
68    }
69    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
70
71 
72    std::vector<re::RE *> REs;
73    re::RE * re_ast = nullptr;
74    for (unsigned i = 0; i < regexVector.size(); i++) {
75        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
76        REs.push_back(re_ast);
77        allREs += regexVector[i] + "\n";
78    }
79    if (REs.size() > 1) {
80        re_ast = re::makeAlt(REs.begin(), REs.end());
81    }
82   
83    return re_ast;
84}
85
86std::string sha1sum(const std::string & str) {
87    char buffer[41];    // 40 hex-digits and the terminating null
88    unsigned int digest[5];     // 160 bits in total
89
90    boost::uuids::detail::sha1 sha1;
91    sha1.process_bytes(str.c_str(), str.size());
92    sha1.get_digest(digest);
93    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
94             digest[0], digest[1], digest[2], digest[3], digest[4]);
95    return std::string(buffer);
96}
97
98std::vector<int> total_CountOnly;
99std::mutex count_mutex;
100size_t fileCount;
101void *DoGrep(void *args)
102{
103    size_t fileIdx;
104    GrepEngine * grepEngine = (GrepEngine *)args;
105
106    count_mutex.lock();
107    fileIdx = fileCount;
108    fileCount++;
109    count_mutex.unlock();
110
111    while (fileIdx < inputFiles.size()){
112        grepEngine->doGrep(inputFiles[fileIdx], fileIdx, CountOnly, total_CountOnly);
113       
114        count_mutex.lock();
115        fileIdx = fileCount;
116        fileCount++;
117        count_mutex.unlock();
118    }
119
120    pthread_exit(NULL);
121}
122
123
124// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
125bool isArgUnwantedForAll(char *argument) {
126
127    bool isUnwated = false;
128    std::vector<std::string> unwantedFlags = {"-gs"};
129
130    for (int i=0; i<unwantedFlags.size(); i++){   
131        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
132            isUnwated = true;
133        }
134    }
135
136    return isUnwated;
137}
138// Filters out the command line strings that shouldn't be passed on to Grep
139bool isArgUnwantedForGrep(char *argument) {
140    bool isUnwated = false;
141    std::vector<std::string> unwantedFlags = {"-n"};
142
143    for (int i = 0; i < unwantedFlags.size(); i++){
144        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
145            isUnwated = true;
146        }
147    }
148
149    for (int i = 0; i < inputFiles.size(); i++){    // filter out input content files.
150        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
151            isUnwated = true;
152        }
153    }
154
155    return isUnwated;
156}
157// Filters out the command line strings that shouldn't be passed on to IcGrep
158bool isArgUnwantedForIcGrep(char *argument) {
159    bool isUnwated = false;
160    std::vector<std::string> unwantedFlags = {"-c"};
161
162    for (int i=0; i<unwantedFlags.size(); i++){
163        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
164            isUnwated = true;
165        }
166    }
167
168    return isUnwated;
169}
170
171/*
172* Constructs a shell command that calls icgrep and then pipes the output to grep.
173* Then executs this shell command using the "system()" function.
174* This allows the output to be colored since all output is piped to grep.
175*/ 
176void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
177    std::string icGrepArguments = "";
178    std::string grepArguments = "";
179
180    // Construct the shell arguments for icgrep and grep
181    // by filtering out the command line arguments passed into this process.
182    for (int i=1; i< argc; i++) {
183        if (!isArgUnwantedForAll(argv[i])) {
184
185            if (!isArgUnwantedForIcGrep(argv[i])) {
186                icGrepArguments.append(argv[i]);
187                icGrepArguments.append(" ");
188            }
189
190            if (!isArgUnwantedForGrep(argv[i])) {
191                grepArguments.append(argv[i]);
192                grepArguments.append(" ");
193            }
194        }
195    }
196
197    std::string systemCall = "./icgrep ";
198    systemCall.append(icGrepArguments);
199    systemCall.append(" ");
200    systemCall.append(" | grep --color=always -P ");
201    systemCall.append(grepArguments);
202    system(systemCall.c_str());
203}
204
205
206int main(int argc, char *argv[]) {
207    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags(), pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
208    cl::ParseCommandLineOptions(argc, argv);
209   
210    re::RE * re_ast = get_icgrep_RE();
211    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
212
213    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
214        pipeIcGrepOutputToGrep(argc, argv);
215        return 0;   // icgrep is called again, so we need to end this process.
216    }
217   
218    GrepEngine grepEngine;
219    grepEngine.grepCodeGen(module_name, re_ast, CountOnly);
220   
221    initResult(inputFiles);
222    for (int i=0; i<inputFiles.size(); i++){
223        total_CountOnly.push_back(0);
224    }
225
226    if (Threads <= 1) {
227        for (unsigned i = 0; i != inputFiles.size(); ++i) {
228            grepEngine.doGrep(inputFiles[i], i, CountOnly, total_CountOnly);
229        }       
230    } else if (Threads > 1) {
231        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
232        pthread_t threads[numOfThreads];
233
234        for(unsigned long i = 0; i < numOfThreads; ++i){
235            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
236            if (rc) {
237                throw std::runtime_error("Failed to create thread: code " + std::to_string(rc));
238            }
239        }
240
241        for(unsigned i = 0; i < numOfThreads; ++i) {
242            void * status = nullptr;
243            const int rc = pthread_join(threads[i], &status);
244            if (rc) {
245                throw std::runtime_error("Failed to join thread: code " + std::to_string(rc));
246            }
247        }
248    }
249    PrintResult(CountOnly, total_CountOnly);
250   
251    return 0;
252}
Note: See TracBrowser for help on using the repository browser.