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

Last change on this file since 5037 was 5037, checked in by nmedfort, 3 years ago

UnicodeSet? bug fix and compile warning clean-up.

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<uint64_t> 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    std::vector<std::string> unwantedFlags = {"-gs"};
127    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
128        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
129            return true;
130        }
131    }
132    return false;
133}
134// Filters out the command line strings that shouldn't be passed on to Grep
135bool isArgUnwantedForGrep(char *argument) {
136    std::vector<std::string> unwantedFlags = {"-n"};
137
138    for (unsigned i = 0; i < inputFiles.size(); ++i){
139        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
140            return true;
141        }
142    }
143
144    for (unsigned i = 0; i < inputFiles.size(); ++i){    // filter out input content files.
145        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
146            return true;
147        }
148    }
149
150    return false;
151}
152// Filters out the command line strings that shouldn't be passed on to IcGrep
153bool isArgUnwantedForIcGrep(char *argument) {
154    bool isUnwated = false;
155    std::vector<std::string> unwantedFlags = {"-c"};
156
157    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
158        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
159            isUnwated = true;
160        }
161    }
162
163    return isUnwated;
164}
165
166/*
167* Constructs a shell command that calls icgrep and then pipes the output to grep.
168* Then executs this shell command using the "system()" function.
169* This allows the output to be colored since all output is piped to grep.
170*/ 
171void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
172    std::string icGrepArguments = "";
173    std::string grepArguments = "";
174
175    // Construct the shell arguments for icgrep and grep
176    // by filtering out the command line arguments passed into this process.
177    for (int i = 1; i < argc; i++) {
178        if (!isArgUnwantedForAll(argv[i])) {
179
180            if (!isArgUnwantedForIcGrep(argv[i])) {
181                icGrepArguments.append(argv[i]);
182                icGrepArguments.append(" ");
183            }
184
185            if (!isArgUnwantedForGrep(argv[i])) {
186                grepArguments.append(argv[i]);
187                grepArguments.append(" ");
188            }
189        }
190    }
191
192    std::string systemCall = "./icgrep ";
193    systemCall.append(icGrepArguments);
194    systemCall.append(" ");
195    systemCall.append(" | grep --color=always -P ");
196    systemCall.append(grepArguments);
197    system(systemCall.c_str());
198}
199
200
201int main(int argc, char *argv[]) {
202    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags(), pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
203    cl::ParseCommandLineOptions(argc, argv);
204   
205    re::RE * re_ast = get_icgrep_RE();
206    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
207
208    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
209        pipeIcGrepOutputToGrep(argc, argv);
210        return 0;   // icgrep is called again, so we need to end this process.
211    }
212   
213    GrepEngine grepEngine;
214    grepEngine.grepCodeGen(module_name, re_ast, CountOnly);
215   
216    initResult(inputFiles);
217    for (unsigned i=0; i<inputFiles.size(); ++i){
218        total_CountOnly.push_back(0);
219    }
220
221    if (Threads <= 1) {
222        for (unsigned i = 0; i != inputFiles.size(); ++i) {
223            grepEngine.doGrep(inputFiles[i], i, CountOnly, total_CountOnly);
224        }       
225    } else if (Threads > 1) {
226        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
227        pthread_t threads[numOfThreads];
228
229        for(unsigned long i = 0; i < numOfThreads; ++i){
230            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
231            if (rc) {
232                throw std::runtime_error("Failed to create thread: code " + std::to_string(rc));
233            }
234        }
235
236        for(unsigned i = 0; i < numOfThreads; ++i) {
237            void * status = nullptr;
238            const int rc = pthread_join(threads[i], &status);
239            if (rc) {
240                throw std::runtime_error("Failed to join thread: code " + std::to_string(rc));
241            }
242        }
243    }
244    PrintResult(CountOnly, total_CountOnly);
245   
246    return 0;
247}
Note: See TracBrowser for help on using the repository browser.