1 //===-- SpecialCaseList.cpp - special case list for sanitizers ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is a utility class for instrumentation passes (like AddressSanitizer
11 // or ThreadSanitizer) to avoid instrumenting some functions or global
12 // variables, or to instrument some functions or global variables in a specific
13 // way, based on a user-supplied list.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Support/SpecialCaseList.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSet.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/Regex.h"
23 #include <string>
24 #include <system_error>
25 #include <utility>
26 
27 namespace llvm {
28 
29 /// Represents a set of regular expressions.  Regular expressions which are
30 /// "literal" (i.e. no regex metacharacters) are stored in Strings, while all
31 /// others are represented as a single pipe-separated regex in RegEx.  The
32 /// reason for doing so is efficiency; StringSet is much faster at matching
33 /// literal strings than Regex.
34 struct SpecialCaseList::Entry {
35   StringSet<> Strings;
36   std::unique_ptr<Regex> RegEx;
37 
38   bool match(StringRef Query) const {
39     return Strings.count(Query) || (RegEx && RegEx->match(Query));
40   }
41 };
42 
43 SpecialCaseList::SpecialCaseList() : Entries(), Regexps(), IsCompiled(false) {}
44 
45 std::unique_ptr<SpecialCaseList>
46 SpecialCaseList::create(const std::vector<std::string> &Paths,
47                         std::string &Error) {
48   std::unique_ptr<SpecialCaseList> SCL(new SpecialCaseList());
49   for (const auto &Path : Paths) {
50     ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
51         MemoryBuffer::getFile(Path);
52     if (std::error_code EC = FileOrErr.getError()) {
53       Error = (Twine("can't open file '") + Path + "': " + EC.message()).str();
54       return nullptr;
55     }
56     std::string ParseError;
57     if (!SCL->parse(FileOrErr.get().get(), ParseError)) {
58       Error = (Twine("error parsing file '") + Path + "': " + ParseError).str();
59       return nullptr;
60     }
61   }
62   SCL->compile();
63   return SCL;
64 }
65 
66 std::unique_ptr<SpecialCaseList> SpecialCaseList::create(const MemoryBuffer *MB,
67                                                          std::string &Error) {
68   std::unique_ptr<SpecialCaseList> SCL(new SpecialCaseList());
69   if (!SCL->parse(MB, Error))
70     return nullptr;
71   SCL->compile();
72   return SCL;
73 }
74 
75 std::unique_ptr<SpecialCaseList>
76 SpecialCaseList::createOrDie(const std::vector<std::string> &Paths) {
77   std::string Error;
78   if (auto SCL = create(Paths, Error))
79     return SCL;
80   report_fatal_error(Error);
81 }
82 
83 bool SpecialCaseList::parse(const MemoryBuffer *MB, std::string &Error) {
84   // Iterate through each line in the blacklist file.
85   SmallVector<StringRef, 16> Lines;
86   SplitString(MB->getBuffer(), Lines, "\n\r");
87   int LineNo = 1;
88   for (auto I = Lines.begin(), E = Lines.end(); I != E; ++I, ++LineNo) {
89     // Ignore empty lines and lines starting with "#"
90     if (I->empty() || I->startswith("#"))
91       continue;
92     // Get our prefix and unparsed regexp.
93     std::pair<StringRef, StringRef> SplitLine = I->split(":");
94     StringRef Prefix = SplitLine.first;
95     if (SplitLine.second.empty()) {
96       // Missing ':' in the line.
97       Error = (Twine("malformed line ") + Twine(LineNo) + ": '" +
98                SplitLine.first + "'").str();
99       return false;
100     }
101 
102     std::pair<StringRef, StringRef> SplitRegexp = SplitLine.second.split("=");
103     std::string Regexp = SplitRegexp.first;
104     StringRef Category = SplitRegexp.second;
105 
106     // See if we can store Regexp in Strings.
107     if (Regex::isLiteralERE(Regexp)) {
108       Entries[Prefix][Category].Strings.insert(Regexp);
109       continue;
110     }
111 
112     // Replace * with .*
113     for (size_t pos = 0; (pos = Regexp.find("*", pos)) != std::string::npos;
114          pos += strlen(".*")) {
115       Regexp.replace(pos, strlen("*"), ".*");
116     }
117 
118     // Check that the regexp is valid.
119     Regex CheckRE(Regexp);
120     std::string REError;
121     if (!CheckRE.isValid(REError)) {
122       Error = (Twine("malformed regex in line ") + Twine(LineNo) + ": '" +
123                SplitLine.second + "': " + REError).str();
124       return false;
125     }
126 
127     // Add this regexp into the proper group by its prefix.
128     if (!Regexps[Prefix][Category].empty())
129       Regexps[Prefix][Category] += "|";
130     Regexps[Prefix][Category] += "^" + Regexp + "$";
131   }
132   return true;
133 }
134 
135 void SpecialCaseList::compile() {
136   assert(!IsCompiled && "compile() should only be called once");
137   // Iterate through each of the prefixes, and create Regexs for them.
138   for (StringMap<StringMap<std::string>>::const_iterator I = Regexps.begin(),
139                                                          E = Regexps.end();
140        I != E; ++I) {
141     for (StringMap<std::string>::const_iterator II = I->second.begin(),
142                                                 IE = I->second.end();
143          II != IE; ++II) {
144       Entries[I->getKey()][II->getKey()].RegEx.reset(new Regex(II->getValue()));
145     }
146   }
147   Regexps.clear();
148   IsCompiled = true;
149 }
150 
151 SpecialCaseList::~SpecialCaseList() {}
152 
153 bool SpecialCaseList::inSection(StringRef Section, StringRef Query,
154                                 StringRef Category) const {
155   assert(IsCompiled && "SpecialCaseList::compile() was not called!");
156   StringMap<StringMap<Entry> >::const_iterator I = Entries.find(Section);
157   if (I == Entries.end()) return false;
158   StringMap<Entry>::const_iterator II = I->second.find(Category);
159   if (II == I->second.end()) return false;
160 
161   return II->getValue().match(Query);
162 }
163 
164 }  // namespace llvm
165