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

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

Fix for -gs mode from Xiangyu

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