5ddaabafc23dd36a99cd0b0a52ace2f67a384096
[oota-llvm.git] / lib / Transforms / Utils / 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/Transforms/Utils/SpecialCaseList.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringSet.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Regex.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/system_error.h"
31 #include <string>
32 #include <utility>
33
34 namespace llvm {
35
36 /// Represents a set of regular expressions.  Regular expressions which are
37 /// "literal" (i.e. no regex metacharacters) are stored in Strings, while all
38 /// others are represented as a single pipe-separated regex in RegEx.  The
39 /// reason for doing so is efficiency; StringSet is much faster at matching
40 /// literal strings than Regex.
41 struct SpecialCaseList::Entry {
42   StringSet<> Strings;
43   Regex *RegEx;
44
45   Entry() : RegEx(0) {}
46
47   bool match(StringRef Query) const {
48     return Strings.count(Query) || (RegEx && RegEx->match(Query));
49   }
50 };
51
52 SpecialCaseList::SpecialCaseList() : Entries() {}
53
54 SpecialCaseList::SpecialCaseList(const StringRef Path) {
55   // Validate and open blacklist file.
56   if (Path.empty()) return;
57   OwningPtr<MemoryBuffer> File;
58   if (error_code EC = MemoryBuffer::getFile(Path, File)) {
59     report_fatal_error("Can't open file '" + Path + "': " +
60                        EC.message());
61   }
62
63   std::string Error;
64   if (!parse(File.get(), Error))
65     report_fatal_error(Error);
66 }
67
68 SpecialCaseList::SpecialCaseList(const MemoryBuffer *MB) {
69   std::string Error;
70   if (!parse(MB, Error))
71     report_fatal_error(Error);
72 }
73
74 SpecialCaseList *SpecialCaseList::create(
75     const StringRef Path, std::string &Error) {
76   if (Path.empty())
77     return new SpecialCaseList();
78   OwningPtr<MemoryBuffer> File;
79   if (error_code EC = MemoryBuffer::getFile(Path, File)) {
80     Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str();
81     return 0;
82   }
83   return create(File.get(), Error);
84 }
85
86 SpecialCaseList *SpecialCaseList::create(
87     const MemoryBuffer *MB, std::string &Error) {
88   OwningPtr<SpecialCaseList> SCL(new SpecialCaseList());
89   if (!SCL->parse(MB, Error))
90     return 0;
91   return SCL.take();
92 }
93
94 SpecialCaseList *SpecialCaseList::createOrDie(const StringRef Path) {
95   std::string Error;
96   if (SpecialCaseList *SCL = create(Path, Error))
97     return SCL;
98   report_fatal_error(Error);
99 }
100
101 bool SpecialCaseList::parse(const MemoryBuffer *MB, std::string &Error) {
102   // Iterate through each line in the blacklist file.
103   SmallVector<StringRef, 16> Lines;
104   SplitString(MB->getBuffer(), Lines, "\n\r");
105   StringMap<StringMap<std::string> > Regexps;
106   assert(Entries.empty() &&
107          "parse() should be called on an empty SpecialCaseList");
108   int LineNo = 1;
109   for (SmallVectorImpl<StringRef>::iterator I = Lines.begin(), E = Lines.end();
110        I != E; ++I, ++LineNo) {
111     // Ignore empty lines and lines starting with "#"
112     if (I->empty() || I->startswith("#"))
113       continue;
114     // Get our prefix and unparsed regexp.
115     std::pair<StringRef, StringRef> SplitLine = I->split(":");
116     StringRef Prefix = SplitLine.first;
117     if (SplitLine.second.empty()) {
118       // Missing ':' in the line.
119       Error = (Twine("Malformed line ") + Twine(LineNo) + ": '" +
120                SplitLine.first + "'").str();
121       return false;
122     }
123
124     std::pair<StringRef, StringRef> SplitRegexp = SplitLine.second.split("=");
125     std::string Regexp = SplitRegexp.first;
126     StringRef Category = SplitRegexp.second;
127
128     // Backwards compatibility.
129     if (Prefix == "global-init") {
130       Prefix = "global";
131       Category = "init";
132     } else if (Prefix == "global-init-type") {
133       Prefix = "type";
134       Category = "init";
135     } else if (Prefix == "global-init-src") {
136       Prefix = "src";
137       Category = "init";
138     }
139
140     // See if we can store Regexp in Strings.
141     if (Regex::isLiteralERE(Regexp)) {
142       Entries[Prefix][Category].Strings.insert(Regexp);
143       continue;
144     }
145
146     // Replace * with .*
147     for (size_t pos = 0; (pos = Regexp.find("*", pos)) != std::string::npos;
148          pos += strlen(".*")) {
149       Regexp.replace(pos, strlen("*"), ".*");
150     }
151
152     // Check that the regexp is valid.
153     Regex CheckRE(Regexp);
154     std::string REError;
155     if (!CheckRE.isValid(REError)) {
156       Error = (Twine("Malformed regex in line ") + Twine(LineNo) + ": '" +
157                SplitLine.second + "': " + REError).str();
158       return false;
159     }
160
161     // Add this regexp into the proper group by its prefix.
162     if (!Regexps[Prefix][Category].empty())
163       Regexps[Prefix][Category] += "|";
164     Regexps[Prefix][Category] += "^" + Regexp + "$";
165   }
166
167   // Iterate through each of the prefixes, and create Regexs for them.
168   for (StringMap<StringMap<std::string> >::const_iterator I = Regexps.begin(),
169                                                           E = Regexps.end();
170        I != E; ++I) {
171     for (StringMap<std::string>::const_iterator II = I->second.begin(),
172                                                 IE = I->second.end();
173          II != IE; ++II) {
174       Entries[I->getKey()][II->getKey()].RegEx = new Regex(II->getValue());
175     }
176   }
177   return true;
178 }
179
180 SpecialCaseList::~SpecialCaseList() {
181   for (StringMap<StringMap<Entry> >::iterator I = Entries.begin(),
182                                               E = Entries.end();
183        I != E; ++I) {
184     for (StringMap<Entry>::const_iterator II = I->second.begin(),
185                                           IE = I->second.end();
186          II != IE; ++II) {
187       delete II->second.RegEx;
188     }
189   }
190 }
191
192 bool SpecialCaseList::findCategory(const Function &F,
193                                    StringRef &Category) const {
194   return findCategory(*F.getParent(), Category) ||
195          findCategory("fun", F.getName(), Category);
196 }
197
198 bool SpecialCaseList::isIn(const Function& F, const StringRef Category) const {
199   return isIn(*F.getParent(), Category) ||
200          inSectionCategory("fun", F.getName(), Category);
201 }
202
203 static StringRef GetGVTypeString(const GlobalVariable &G) {
204   // Types of GlobalVariables are always pointer types.
205   Type *GType = G.getType()->getElementType();
206   // For now we support blacklisting struct types only.
207   if (StructType *SGType = dyn_cast<StructType>(GType)) {
208     if (!SGType->isLiteral())
209       return SGType->getName();
210   }
211   return "<unknown type>";
212 }
213
214 bool SpecialCaseList::findCategory(const GlobalVariable &G,
215                                    StringRef &Category) const {
216   return findCategory(*G.getParent(), Category) ||
217          findCategory("global", G.getName(), Category) ||
218          findCategory("type", GetGVTypeString(G), Category);
219 }
220
221 bool SpecialCaseList::isIn(const GlobalVariable &G,
222                            const StringRef Category) const {
223   return isIn(*G.getParent(), Category) ||
224          inSectionCategory("global", G.getName(), Category) ||
225          inSectionCategory("type", GetGVTypeString(G), Category);
226 }
227
228 bool SpecialCaseList::findCategory(const Module &M, StringRef &Category) const {
229   return findCategory("src", M.getModuleIdentifier(), Category);
230 }
231
232 bool SpecialCaseList::isIn(const Module &M, const StringRef Category) const {
233   return inSectionCategory("src", M.getModuleIdentifier(), Category);
234 }
235
236 bool SpecialCaseList::findCategory(const StringRef Section,
237                                    const StringRef Query,
238                                    StringRef &Category) const {
239   StringMap<StringMap<Entry> >::const_iterator I = Entries.find(Section);
240   if (I == Entries.end()) return false;
241
242   for (StringMap<Entry>::const_iterator II = I->second.begin(),
243                                         IE = I->second.end();
244        II != IE; ++II) {
245     if (II->getValue().match(Query)) {
246       Category = II->first();
247       return true;
248     }
249   }
250
251   return false;
252 }
253
254 bool SpecialCaseList::inSectionCategory(const StringRef Section,
255                                         const StringRef Query,
256                                         const StringRef Category) const {
257   StringMap<StringMap<Entry> >::const_iterator I = Entries.find(Section);
258   if (I == Entries.end()) return false;
259   StringMap<Entry>::const_iterator II = I->second.find(Category);
260   if (II == I->second.end()) return false;
261
262   return II->getValue().match(Query);
263 }
264
265 }  // namespace llvm