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

Last change on this file since 5016 was 5016, checked in by aambarts, 3 years ago

Adding -gs flag that pipes icgrep output to grep, thus giving colorized output and possibly backtracking capability in the future.

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