43824891af3897480bfcaa780b6be423293a96a1
[oota-llvm.git] / lib / Support / SpecialCaseList.cpp
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/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/Regex.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <string>
26 #include <system_error>
27 #include <utility>
28
29 namespace llvm {
30
31 /// Represents a set of regular expressions.  Regular expressions which are
32 /// "literal" (i.e. no regex metacharacters) are stored in Strings, while all
33 /// others are represented as a single pipe-separated regex in RegEx.  The
34 /// reason for doing so is efficiency; StringSet is much faster at matching
35 /// literal strings than Regex.
36 struct SpecialCaseList::Entry {
37   Entry() {}
38   Entry(Entry &&Other)
39       : Strings(std::move(Other.Strings)), RegEx(std::move(Other.RegEx)) {}
40   Entry &operator=(Entry &&Other) {
41     Strings = std::move(Other.Strings);
42     RegEx = std::move(Other.RegEx);
43     return *this;
44   }
45
46   StringSet<> Strings;
47   std::unique_ptr<Regex> RegEx;
48
49   bool match(StringRef Query) const {
50     return Strings.count(Query) || (RegEx && RegEx->match(Query));
51   }
52 };
53
54 SpecialCaseList::SpecialCaseList() : Entries() {}
55
56 SpecialCaseList *SpecialCaseList::create(
57     const StringRef Path, std::string &Error) {
58   if (Path.empty())
59     return new SpecialCaseList();
60   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
61       MemoryBuffer::getFile(Path);
62   if (std::error_code EC = FileOrErr.getError()) {
63     Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str();
64     return nullptr;
65   }
66   return create(FileOrErr.get().get(), Error);
67 }
68
69 SpecialCaseList *SpecialCaseList::create(
70     const MemoryBuffer *MB, std::string &Error) {
71   std::unique_ptr<SpecialCaseList> SCL(new SpecialCaseList());
72   if (!SCL->parse(MB, Error))
73     return nullptr;
74   return SCL.release();
75 }
76
77 SpecialCaseList *SpecialCaseList::createOrDie(const StringRef Path) {
78   std::string Error;
79   if (SpecialCaseList *SCL = create(Path, Error))
80     return SCL;
81   report_fatal_error(Error);
82 }
83
84 bool SpecialCaseList::parse(const MemoryBuffer *MB, std::string &Error) {
85   // Iterate through each line in the blacklist file.
86   SmallVector<StringRef, 16> Lines;
87   SplitString(MB->getBuffer(), Lines, "\n\r");
88   StringMap<StringMap<std::string> > Regexps;
89   assert(Entries.empty() &&
90          "parse() should be called on an empty SpecialCaseList");
91   int LineNo = 1;
92   for (SmallVectorImpl<StringRef>::iterator I = Lines.begin(), E = Lines.end();
93        I != E; ++I, ++LineNo) {
94     // Ignore empty lines and lines starting with "#"
95     if (I->empty() || I->startswith("#"))
96       continue;
97     // Get our prefix and unparsed regexp.
98     std::pair<StringRef, StringRef> SplitLine = I->split(":");
99     StringRef Prefix = SplitLine.first;
100     if (SplitLine.second.empty()) {
101       // Missing ':' in the line.
102       Error = (Twine("Malformed line ") + Twine(LineNo) + ": '" +
103                SplitLine.first + "'").str();
104       return false;
105     }
106
107     std::pair<StringRef, StringRef> SplitRegexp = SplitLine.second.split("=");
108     std::string Regexp = SplitRegexp.first;
109     StringRef Category = SplitRegexp.second;
110
111     // Backwards compatibility.
112     if (Prefix == "global-init") {
113       Prefix = "global";
114       Category = "init";
115     } else if (Prefix == "global-init-type") {
116       Prefix = "type";
117       Category = "init";
118     } else if (Prefix == "global-init-src") {
119       Prefix = "src";
120       Category = "init";
121     }
122
123     // See if we can store Regexp in Strings.
124     if (Regex::isLiteralERE(Regexp)) {
125       Entries[Prefix][Category].Strings.insert(Regexp);
126       continue;
127     }
128
129     // Replace * with .*
130     for (size_t pos = 0; (pos = Regexp.find("*", pos)) != std::string::npos;
131          pos += strlen(".*")) {
132       Regexp.replace(pos, strlen("*"), ".*");
133     }
134
135     // Check that the regexp is valid.
136     Regex CheckRE(Regexp);
137     std::string REError;
138     if (!CheckRE.isValid(REError)) {
139       Error = (Twine("Malformed regex in line ") + Twine(LineNo) + ": '" +
140                SplitLine.second + "': " + REError).str();
141       return false;
142     }
143
144     // Add this regexp into the proper group by its prefix.
145     if (!Regexps[Prefix][Category].empty())
146       Regexps[Prefix][Category] += "|";
147     Regexps[Prefix][Category] += "^" + Regexp + "$";
148   }
149
150   // Iterate through each of the prefixes, and create Regexs for them.
151   for (StringMap<StringMap<std::string> >::const_iterator I = Regexps.begin(),
152                                                           E = Regexps.end();
153        I != E; ++I) {
154     for (StringMap<std::string>::const_iterator II = I->second.begin(),
155                                                 IE = I->second.end();
156          II != IE; ++II) {
157       Entries[I->getKey()][II->getKey()].RegEx.reset(new Regex(II->getValue()));
158     }
159   }
160   return true;
161 }
162
163 SpecialCaseList::~SpecialCaseList() {}
164
165 bool SpecialCaseList::inSection(const StringRef Section, const StringRef Query,
166                                 const StringRef Category) const {
167   StringMap<StringMap<Entry> >::const_iterator I = Entries.find(Section);
168   if (I == Entries.end()) return false;
169   StringMap<Entry>::const_iterator II = I->second.find(Category);
170   if (II == I->second.end()) return false;
171
172   return II->getValue().match(Query);
173 }
174
175 }  // namespace llvm