SpecialCaseList: use std::unique_ptr.
[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   StringSet<> Strings;
38   std::unique_ptr<Regex> RegEx;
39
40   bool match(StringRef Query) const {
41     return Strings.count(Query) || (RegEx && RegEx->match(Query));
42   }
43 };
44
45 SpecialCaseList::SpecialCaseList() : Entries() {}
46
47 SpecialCaseList *SpecialCaseList::create(
48     const StringRef Path, std::string &Error) {
49   if (Path.empty())
50     return new SpecialCaseList();
51   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
52       MemoryBuffer::getFile(Path);
53   if (std::error_code EC = FileOrErr.getError()) {
54     Error = (Twine("Can't open file '") + Path + "': " + EC.message()).str();
55     return nullptr;
56   }
57   return create(FileOrErr.get().get(), Error);
58 }
59
60 SpecialCaseList *SpecialCaseList::create(
61     const MemoryBuffer *MB, std::string &Error) {
62   std::unique_ptr<SpecialCaseList> SCL(new SpecialCaseList());
63   if (!SCL->parse(MB, Error))
64     return nullptr;
65   return SCL.release();
66 }
67
68 SpecialCaseList *SpecialCaseList::createOrDie(const StringRef Path) {
69   std::string Error;
70   if (SpecialCaseList *SCL = create(Path, Error))
71     return SCL;
72   report_fatal_error(Error);
73 }
74
75 bool SpecialCaseList::parse(const MemoryBuffer *MB, std::string &Error) {
76   // Iterate through each line in the blacklist file.
77   SmallVector<StringRef, 16> Lines;
78   SplitString(MB->getBuffer(), Lines, "\n\r");
79   StringMap<StringMap<std::string> > Regexps;
80   assert(Entries.empty() &&
81          "parse() should be called on an empty SpecialCaseList");
82   int LineNo = 1;
83   for (SmallVectorImpl<StringRef>::iterator I = Lines.begin(), E = Lines.end();
84        I != E; ++I, ++LineNo) {
85     // Ignore empty lines and lines starting with "#"
86     if (I->empty() || I->startswith("#"))
87       continue;
88     // Get our prefix and unparsed regexp.
89     std::pair<StringRef, StringRef> SplitLine = I->split(":");
90     StringRef Prefix = SplitLine.first;
91     if (SplitLine.second.empty()) {
92       // Missing ':' in the line.
93       Error = (Twine("Malformed line ") + Twine(LineNo) + ": '" +
94                SplitLine.first + "'").str();
95       return false;
96     }
97
98     std::pair<StringRef, StringRef> SplitRegexp = SplitLine.second.split("=");
99     std::string Regexp = SplitRegexp.first;
100     StringRef Category = SplitRegexp.second;
101
102     // Backwards compatibility.
103     if (Prefix == "global-init") {
104       Prefix = "global";
105       Category = "init";
106     } else if (Prefix == "global-init-type") {
107       Prefix = "type";
108       Category = "init";
109     } else if (Prefix == "global-init-src") {
110       Prefix = "src";
111       Category = "init";
112     }
113
114     // See if we can store Regexp in Strings.
115     if (Regex::isLiteralERE(Regexp)) {
116       Entries[Prefix][Category].Strings.insert(Regexp);
117       continue;
118     }
119
120     // Replace * with .*
121     for (size_t pos = 0; (pos = Regexp.find("*", pos)) != std::string::npos;
122          pos += strlen(".*")) {
123       Regexp.replace(pos, strlen("*"), ".*");
124     }
125
126     // Check that the regexp is valid.
127     Regex CheckRE(Regexp);
128     std::string REError;
129     if (!CheckRE.isValid(REError)) {
130       Error = (Twine("Malformed regex in line ") + Twine(LineNo) + ": '" +
131                SplitLine.second + "': " + REError).str();
132       return false;
133     }
134
135     // Add this regexp into the proper group by its prefix.
136     if (!Regexps[Prefix][Category].empty())
137       Regexps[Prefix][Category] += "|";
138     Regexps[Prefix][Category] += "^" + Regexp + "$";
139   }
140
141   // Iterate through each of the prefixes, and create Regexs for them.
142   for (StringMap<StringMap<std::string> >::const_iterator I = Regexps.begin(),
143                                                           E = Regexps.end();
144        I != E; ++I) {
145     for (StringMap<std::string>::const_iterator II = I->second.begin(),
146                                                 IE = I->second.end();
147          II != IE; ++II) {
148       Entries[I->getKey()][II->getKey()].RegEx.reset(new Regex(II->getValue()));
149     }
150   }
151   return true;
152 }
153
154 SpecialCaseList::~SpecialCaseList() {}
155
156 bool SpecialCaseList::inSection(const StringRef Section, const StringRef Query,
157                                 const StringRef Category) const {
158   StringMap<StringMap<Entry> >::const_iterator I = Entries.find(Section);
159   if (I == Entries.end()) return false;
160   StringMap<Entry>::const_iterator II = I->second.find(Category);
161   if (II == I->second.end()) return false;
162
163   return II->getValue().match(Query);
164 }
165
166 }  // namespace llvm