Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qv4regexp.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4// TODO: verifyj critical part should be in YARR
5
6#include "qv4regexp_p.h"
7#include "qv4engine_p.h"
9#include <private/qv4mm_p.h>
10#include <runtime/VM.h>
11
12using namespace QV4;
13
14#if ENABLE(YARR_JIT)
15static constexpr qsizetype LongStringJitThreshold = 1024;
16static constexpr int LongStringJitBoost = 3;
17#endif
18
19static JSC::RegExpFlags jscFlags(quint8 flags)
20{
21 JSC::RegExpFlags jscFlags = JSC::NoFlags;
22 if (flags & CompiledData::RegExp::RegExp_Global)
23 jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagGlobal);
24 if (flags & CompiledData::RegExp::RegExp_IgnoreCase)
25 jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagIgnoreCase);
26 if (flags & CompiledData::RegExp::RegExp_Multiline)
27 jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagMultiline);
28 if (flags & CompiledData::RegExp::RegExp_Unicode)
29 jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagUnicode);
30 if (flags & CompiledData::RegExp::RegExp_Sticky)
31 jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagSticky);
32 return jscFlags;
33}
34
35RegExpCache::~RegExpCache()
36{
37 for (RegExpCache::Iterator it = begin(), e = end(); it != e; ++it) {
38 if (RegExp *re = it.value().as<RegExp>())
39 re->d()->cache = nullptr;
40 }
41}
42
44
45uint RegExp::match(const QString &string, int start, uint *matchOffsets)
46{
47 // Note that we rely on the side-effect of checkStackLimits updating
48 // cppStackLimit (which might be necessary after a thread move):
49 // hasCppStackOverflow's recheck will trigger after a move (if it
50 // didn't, we'd had overlapping stack regions, which can't be).
51 if (!isValid() || internalClass()->engine->checkStackLimits())
52 return JSC::Yarr::offsetNoMatch;
53
54#if ENABLE(YARR_JIT)
55 auto *priv = d();
56
57 auto regenerateByteCode = [](Heap::RegExp *regexp) {
58 const void* stackLimit = regexp->internalClass->engine->cppStackLimit;
59 JSC::Yarr::ErrorCode error = JSC::Yarr::ErrorCode::NoError;
60 JSC::Yarr::YarrPattern yarrPattern(WTF::String(*regexp->pattern), jscFlags(regexp->flags),
61 error, const_cast<void *>(stackLimit));
62
63 // As we successfully parsed the pattern before, we should still be able to.
64 Q_ASSERT(error == JSC::Yarr::ErrorCode::NoError);
65
66 regexp->byteCode = JSC::Yarr::byteCompile(
67 yarrPattern,
68 regexp->internalClass->engine->bumperPointerAllocator).release();
69 };
70
71 auto removeJitCode = [](Heap::RegExp *regexp) {
72 delete regexp->jitCode;
73 regexp->jitCode = nullptr;
74 regexp->jitFailed = true;
75 };
76
77 auto removeByteCode = [](Heap::RegExp *regexp) {
78 delete regexp->byteCode;
79 regexp->byteCode = nullptr;
80 };
81
82 if (!priv->jitCode) {
83
84 // Long strings count as more calls. We want the JIT to run earlier.
85 const bool longString = string.length() > LongStringJitThreshold;
86 if (longString)
87 priv->interpreterCallCount += LongStringJitBoost;
88
89 if (priv->internalClass->engine->canJIT(priv)) {
90 removeByteCode(priv);
91
92 JSC::Yarr::ErrorCode error = JSC::Yarr::ErrorCode::NoError;
93 const void* stackLimit = internalClass()->engine->cppStackLimit;
94 JSC::Yarr::YarrPattern yarrPattern(
95 WTF::String(*priv->pattern), jscFlags(priv->flags), error, const_cast<void *>(stackLimit));
96 if (!yarrPattern.m_containsBackreferences) {
97 priv->jitCode = new JSC::Yarr::YarrCodeBlock;
98 JSC::VM *vm = static_cast<JSC::VM *>(priv->internalClass->engine);
99 JSC::Yarr::jitCompile(yarrPattern, JSC::Yarr::Char16, vm, *priv->jitCode);
100 }
101
102 if (!priv->hasValidJITCode()) {
103 removeJitCode(priv);
104 regenerateByteCode(priv);
105 }
106 } else if (!longString) {
107 // Short strings do the regular post-increment to honor
108 // QV4_JIT_CALL_THRESHOLD.
109 ++priv->interpreterCallCount;
110 }
111 }
112#endif
113
114 WTF::String s(string);
115
116#if ENABLE(YARR_JIT)
117 if (priv->hasValidJITCode()) {
118 static const uint offsetJITFail = std::numeric_limits<unsigned>::max() - 1;
119 uint ret = JSC::Yarr::offsetNoMatch;
120#if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
121 char buffer[8192];
122 ret = uint(priv->jitCode->execute(s.characters16(), start, s.size(),
123 (int*)matchOffsets, buffer, 8192).start);
124#else
125 ret = uint(priv->jitCode->execute(s.characters16(), start, s.length(),
126 (int*)matchOffsets).start);
127#endif
128 if (ret != offsetJITFail)
129 return ret;
130
131 removeJitCode(priv);
132 // JIT failed. We need byteCode to run the interpreter.
133 Q_ASSERT(!priv->byteCode);
134 regenerateByteCode(priv);
135 }
136#endif // ENABLE(YARR_JIT)
137
138 return JSC::Yarr::interpret(byteCode(), s.characters16(), string.size(), start, matchOffsets);
139}
140
141QString RegExp::getSubstitution(const QString &matched, const QString &str, int position, const Value *captures, int nCaptures, const QString &replacement)
142{
143 QString result;
144
145 int matchedLength = matched.size();
146 Q_ASSERT(position >= 0 && position <= str.size());
147 int tailPos = position + matchedLength;
148 int seenDollar = -1;
149 for (int i = 0; i < replacement.size(); ++i) {
150 QChar ch = replacement.at(i);
151 if (seenDollar >= 0) {
152 if (ch.unicode() == '$') {
153 result += QLatin1Char('$');
154 } else if (ch.unicode() == '&') {
155 result += matched;
156 } else if (ch.unicode() == '`') {
157 result += str.left(position);
158 } else if (ch.unicode() == '\'') {
159 result += str.mid(tailPos);
160 } else if (ch.unicode() >= '0' && ch.unicode() <= '9') {
161 int n = ch.unicode() - '0';
162 if (i + 1 < replacement.size()) {
163 ch = replacement.at(i + 1);
164 if (ch.unicode() >= '0' && ch.unicode() <= '9') {
165 n = n*10 + (ch.unicode() - '0');
166 ++i;
167 }
168 }
169 if (n > 0 && n <= nCaptures) {
170 String *s = captures[n].stringValue();
171 if (s)
172 result += s->toQString();
173 } else {
174 for (int j = seenDollar; j <= i; ++j)
175 result += replacement.at(j);
176 }
177 } else {
178 result += QLatin1Char('$');
179 result += ch;
180 }
181 seenDollar = -1;
182 } else {
183 if (ch == QLatin1Char('$')) {
184 seenDollar = i;
185 continue;
186 }
187 result += ch;
188 }
189 }
190 if (seenDollar >= 0)
191 result += QLatin1Char('$');
192 return result;
193}
194
195Heap::RegExp *RegExp::create(
196 ExecutionEngine *engine, const QString &pattern, CompiledData::RegExp::Flags flags)
197{
198 RegExpCacheKey key(pattern, flags);
199
200 RegExpCache *cache = engine->regExpCache;
201 if (!cache)
202 cache = engine->regExpCache = new RegExpCache;
203
204 QV4::WeakValue &cachedValue = (*cache)[key];
205 if (QV4::RegExp *result = cachedValue.as<RegExp>())
206 return result->d();
207
208 Scope scope(engine);
209 Scoped<RegExp> result(scope, engine->memoryManager->alloc<RegExp>(engine, pattern, flags));
210
211 result->d()->cache = cache;
212 cachedValue.set(engine, result);
213
214 return result->d();
215}
216
217void Heap::RegExp::init(ExecutionEngine *engine, const QString &pattern, uint flags)
218{
219 Base::init();
220 this->pattern = new QString(pattern);
221 this->flags = flags;
222
223 JSC::Yarr::ErrorCode error = JSC::Yarr::ErrorCode::NoError;
224 // compare the comment in RegExp::match
225 if (engine->checkStackLimits())
226 return;
227 const void* stackLimit = internalClass->engine->cppStackLimit;
228 JSC::Yarr::YarrPattern yarrPattern(WTF::String(pattern), jscFlags(flags), error, const_cast<void *>(stackLimit));
229 if (error != JSC::Yarr::ErrorCode::NoError)
230 return;
231 subPatternCount = yarrPattern.m_numSubpatterns;
232 Q_UNUSED(engine);
233 byteCode = JSC::Yarr::byteCompile(yarrPattern, internalClass->engine->bumperPointerAllocator).release();
234 if (byteCode)
235 valid = true;
236}
237
238void Heap::RegExp::destroy()
239{
240 if (cache) {
241 RegExpCacheKey key(this);
242 cache->remove(key);
243 }
244#if ENABLE(YARR_JIT)
245 delete jitCode;
246#endif
247 delete byteCode;
248 delete pattern;
249 Base::destroy();
250}
DEFINE_MANAGED_VTABLE(RegExp)
static JSC::RegExpFlags jscFlags(quint8 flags)
Definition qv4regexp.cpp:19