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

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

Fix for threading to ensure first file is processed.

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