1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef SRC_TRACE_PROCESSOR_UTIL_REGEX_H_
18 #define SRC_TRACE_PROCESSOR_UTIL_REGEX_H_
19
20 #include <optional>
21 #include <utility>
22
23 #include "perfetto/base/build_config.h"
24 #include "perfetto/base/logging.h"
25 #include "perfetto/base/status.h"
26 #include "perfetto/ext/base/status_or.h"
27
28 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
29 #include <regex.h>
30 #endif
31
32 namespace perfetto::trace_processor::regex {
33
IsRegexSupported()34 constexpr bool IsRegexSupported() {
35 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
36 return false;
37 #else
38 return true;
39 #endif
40 }
41
42 // Implements regex parsing and regex search based on C library `regex.h`.
43 // Doesn't work on Windows.
44 class Regex {
45 public:
46 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
~Regex()47 ~Regex() {
48 if (regex_) {
49 regfree(®ex_.value());
50 }
51 }
52 Regex(const Regex&) = delete;
Regex(Regex && other)53 Regex(Regex&& other) {
54 regex_ = other.regex_;
55 other.regex_ = std::nullopt;
56 }
57 Regex& operator=(Regex&& other) {
58 this->~Regex();
59 new (this) Regex(std::move(other));
60 return *this;
61 }
62 Regex& operator=(const Regex&) = delete;
63 #endif
64
65 // Parse regex pattern. Returns error if regex pattern is invalid.
Create(const char * pattern)66 static base::StatusOr<Regex> Create(const char* pattern) {
67 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
68 regex_t regex;
69 if (regcomp(®ex, pattern, 0)) {
70 return base::ErrStatus("Regex pattern '%s' is malformed.", pattern);
71 }
72 return Regex(regex);
73 #else
74 base::ignore_result(pattern);
75 PERFETTO_FATAL("Windows regex is not supported.");
76 #endif
77 }
78
79 // Returns true if string matches the regex.
Search(const char * s)80 bool Search(const char* s) const {
81 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
82 PERFETTO_CHECK(regex_);
83 return regexec(®ex_.value(), s, 0, nullptr, 0) == 0;
84 #else
85 base::ignore_result(s);
86 PERFETTO_FATAL("Windows regex is not supported.");
87 #endif
88 }
89
90 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
91 private:
Regex(regex_t regex)92 explicit Regex(regex_t regex) : regex_(regex) {}
93
94 std::optional<regex_t> regex_;
95 #endif
96 };
97 } // namespace perfetto::trace_processor::regex
98
99 #endif // SRC_TRACE_PROCESSOR_UTIL_REGEX_H_
100