LLVM 22.0.0git
SpecialCaseList.cpp
Go to the documentation of this file.
1//===-- SpecialCaseList.cpp - special case list for sanitizers ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This is a utility class for instrumentation passes (like AddressSanitizer
10// or ThreadSanitizer) to avoid instrumenting some functions or global
11// variables, or to instrument some functions or global variables in a specific
12// way, based on a user-supplied list.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/STLExtras.h"
21#include <stdio.h>
22#include <string>
23#include <system_error>
24#include <utility>
25
26namespace llvm {
27
29 bool UseGlobs) {
30 if (Pattern.empty())
32 Twine("Supplied ") +
33 (UseGlobs ? "glob" : "regex") + " was blank");
34
35 if (!UseGlobs) {
36 // Replace * with .*
37 auto Regexp = Pattern.str();
38 for (size_t pos = 0; (pos = Regexp.find('*', pos)) != std::string::npos;
39 pos += strlen(".*")) {
40 Regexp.replace(pos, strlen("*"), ".*");
41 }
42
43 Regexp = (Twine("^(") + StringRef(Regexp) + ")$").str();
44
45 // Check that the regexp is valid.
46 Regex CheckRE(Regexp);
47 std::string REError;
48 if (!CheckRE.isValid(REError))
50
51 RegExes.emplace_back(std::make_pair(
52 std::make_unique<Regex>(std::move(CheckRE)), LineNumber));
53
54 return Error::success();
55 }
56
57 auto Glob = std::make_unique<Matcher::Glob>();
58 Glob->Name = Pattern.str();
59 Glob->LineNo = LineNumber;
60 // We must be sure to use the string in `Glob` rather than the provided
61 // reference which could be destroyed before match() is called
62 if (auto Err = GlobPattern::create(Glob->Name, /*MaxSubPatterns=*/1024)
63 .moveInto(Glob->Pattern))
64 return Err;
65 Globs.push_back(std::move(Glob));
66 return Error::success();
67}
68
70 for (const auto &Glob : reverse(Globs))
71 if (Glob->Pattern.match(Query))
72 return Glob->LineNo;
73 for (const auto &[Regex, LineNumber] : reverse(RegExes))
74 if (Regex->match(Query))
75 return LineNumber;
76 return 0;
77}
78
79// TODO: Refactor this to return Expected<...>
80std::unique_ptr<SpecialCaseList>
81SpecialCaseList::create(const std::vector<std::string> &Paths,
82 llvm::vfs::FileSystem &FS, std::string &Error) {
83 std::unique_ptr<SpecialCaseList> SCL(new SpecialCaseList());
84 if (SCL->createInternal(Paths, FS, Error))
85 return SCL;
86 return nullptr;
87}
88
89std::unique_ptr<SpecialCaseList> SpecialCaseList::create(const MemoryBuffer *MB,
90 std::string &Error) {
91 std::unique_ptr<SpecialCaseList> SCL(new SpecialCaseList());
92 if (SCL->createInternal(MB, Error))
93 return SCL;
94 return nullptr;
95}
96
97std::unique_ptr<SpecialCaseList>
98SpecialCaseList::createOrDie(const std::vector<std::string> &Paths,
100 std::string Error;
101 if (auto SCL = create(Paths, FS, Error))
102 return SCL;
104}
105
106bool SpecialCaseList::createInternal(const std::vector<std::string> &Paths,
107 vfs::FileSystem &VFS, std::string &Error) {
108 for (size_t i = 0; i < Paths.size(); ++i) {
109 const auto &Path = Paths[i];
111 VFS.getBufferForFile(Path);
112 if (std::error_code EC = FileOrErr.getError()) {
113 Error = (Twine("can't open file '") + Path + "': " + EC.message()).str();
114 return false;
115 }
116 std::string ParseError;
117 if (!parse(i, FileOrErr.get().get(), ParseError)) {
118 Error = (Twine("error parsing file '") + Path + "': " + ParseError).str();
119 return false;
120 }
121 }
122 return true;
123}
124
126 std::string &Error) {
127 if (!parse(0, MB, Error))
128 return false;
129 return true;
130}
131
133SpecialCaseList::addSection(StringRef SectionStr, unsigned FileNo,
134 unsigned LineNo, bool UseGlobs) {
135 Sections.emplace_back(SectionStr, FileNo);
136 auto &Section = Sections.back();
137
138 if (auto Err = Section.SectionMatcher->insert(SectionStr, LineNo, UseGlobs)) {
140 "malformed section at line " + Twine(LineNo) +
141 ": '" + SectionStr +
142 "': " + toString(std::move(Err)));
143 }
144
145 return &Section;
146}
147
148bool SpecialCaseList::parse(unsigned FileIdx, const MemoryBuffer *MB,
149 std::string &Error) {
150 Section *CurrentSection;
151 if (auto Err = addSection("*", FileIdx, 1).moveInto(CurrentSection)) {
152 Error = toString(std::move(Err));
153 return false;
154 }
155
156 // In https://reviews.llvm.org/D154014 we added glob support and planned to
157 // remove regex support in patterns. We temporarily support the original
158 // behavior using regexes if "#!special-case-list-v1" is the first line of the
159 // file. For more details, see
160 // https://discourse.llvm.org/t/use-glob-instead-of-regex-for-specialcaselists/71666
161 bool UseGlobs = !MB->getBuffer().starts_with("#!special-case-list-v1\n");
162
163 for (line_iterator LineIt(*MB, /*SkipBlanks=*/true, /*CommentMarker=*/'#');
164 !LineIt.is_at_eof(); LineIt++) {
165 unsigned LineNo = LineIt.line_number();
166 StringRef Line = LineIt->trim();
167 if (Line.empty())
168 continue;
169
170 // Save section names
171 if (Line.starts_with("[")) {
172 if (!Line.ends_with("]")) {
173 Error =
174 ("malformed section header on line " + Twine(LineNo) + ": " + Line)
175 .str();
176 return false;
177 }
178
179 if (auto Err = addSection(Line.drop_front().drop_back(), FileIdx, LineNo,
180 UseGlobs)
181 .moveInto(CurrentSection)) {
182 Error = toString(std::move(Err));
183 return false;
184 }
185 continue;
186 }
187
188 // Get our prefix and unparsed glob.
189 auto [Prefix, Postfix] = Line.split(":");
190 if (Postfix.empty()) {
191 // Missing ':' in the line.
192 Error = ("malformed line " + Twine(LineNo) + ": '" + Line + "'").str();
193 return false;
194 }
195
196 auto [Pattern, Category] = Postfix.split("=");
197 auto &Entry = CurrentSection->Entries[Prefix][Category];
198 if (auto Err = Entry.insert(Pattern, LineNo, UseGlobs)) {
199 Error =
200 (Twine("malformed ") + (UseGlobs ? "glob" : "regex") + " in line " +
201 Twine(LineNo) + ": '" + Pattern + "': " + toString(std::move(Err)))
202 .str();
203 return false;
204 }
205 }
206 return true;
207}
208
210
212 StringRef Query, StringRef Category) const {
213 auto [FileIdx, LineNo] = inSectionBlame(Section, Prefix, Query, Category);
214 return LineNo;
215}
216
217std::pair<unsigned, unsigned>
219 StringRef Query, StringRef Category) const {
220 for (const auto &S : reverse(Sections)) {
221 if (S.SectionMatcher->match(Section)) {
222 unsigned Blame = inSectionBlame(S.Entries, Prefix, Query, Category);
223 if (Blame)
224 return {S.FileIdx, Blame};
225 }
226 }
227 return NotFound;
228}
229
231 StringRef Prefix, StringRef Query,
232 StringRef Category) const {
233 SectionEntries::const_iterator I = Entries.find(Prefix);
234 if (I == Entries.end())
235 return 0;
236 StringMap<Matcher>::const_iterator II = I->second.find(Category);
237 if (II == I->second.end())
238 return 0;
239
240 return II->getValue().match(Query);
241}
242
243} // namespace llvm
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
This file contains some templates that are useful if you are working with the STL at all.
Defines the virtual file system interface vfs::FileSystem.
Represents either an error or a value T.
Definition: ErrorOr.h:56
reference get()
Definition: ErrorOr.h:149
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
LLVM_ABI bool match(StringRef S) const
static LLVM_ABI Expected< GlobPattern > create(StringRef Pat, std::optional< size_t > MaxSubPatterns={})
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:52
StringRef getBuffer() const
Definition: MemoryBuffer.h:71
LLVM_ABI bool isValid(std::string &Error) const
isValid - returns the error encountered during regex compilation, if any.
Definition: Regex.cpp:69
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition: Regex.cpp:83
std::vector< std::pair< std::unique_ptr< Regex >, unsigned > > RegExes
LLVM_ABI unsigned match(StringRef Query) const
std::vector< std::unique_ptr< Matcher::Glob > > Globs
LLVM_ABI Error insert(StringRef Pattern, unsigned LineNumber, bool UseRegex)
std::vector< Section > Sections
static constexpr std::pair< unsigned, unsigned > NotFound
LLVM_ABI std::pair< unsigned, unsigned > inSectionBlame(StringRef Section, StringRef Prefix, StringRef Query, StringRef Category=StringRef()) const
Returns the file index and the line number <FileIdx, LineNo> corresponding to the special case list e...
LLVM_ABI bool createInternal(const std::vector< std::string > &Paths, vfs::FileSystem &VFS, std::string &Error)
static LLVM_ABI std::unique_ptr< SpecialCaseList > createOrDie(const std::vector< std::string > &Paths, llvm::vfs::FileSystem &FS)
Parses the special case list entries from files.
static LLVM_ABI std::unique_ptr< SpecialCaseList > create(const std::vector< std::string > &Paths, llvm::vfs::FileSystem &FS, std::string &Error)
Parses the special case list entries from files.
LLVM_ABI ~SpecialCaseList()
LLVM_ABI Expected< Section * > addSection(StringRef SectionStr, unsigned FileIdx, unsigned LineNo, bool UseGlobs=true)
LLVM_ABI bool parse(unsigned FileIdx, const MemoryBuffer *MB, std::string &Error)
Parses just-constructed SpecialCaseList entries from a memory buffer.
LLVM_ABI bool inSection(StringRef Section, StringRef Prefix, StringRef Query, StringRef Category=StringRef()) const
Returns true, if special case list contains a line.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:269
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:34
bool is_at_eof() const
Return true if we've reached EOF or are an "end" iterator.
Definition: LineIterator.h:63
The virtual file system interface.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false, bool IsText=true)
This is a convenience method that opens a file, gets its content and then closes the file.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1305
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
const char * toString(DWARFSectionKind Kind)
std::unique_ptr< Matcher > SectionMatcher
Definition: regcomp.c:186