Debian Codegraph @

js/src/irregexp/RegExpAPI.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // Copyright 2020 the V8 project authors. All rights reserved.
8 // Use of this source code is governed by a BSD-style license that can be
9 // found in the LICENSE file.
10
11 #include "irregexp/RegExpAPI.h"
12
13 #include "mozilla/ArrayUtils.h"
14 #include "mozilla/Casting.h"
15
16 #include "frontend/FrontendContext.h" // AutoReportFrontendContext
17 #include "frontend/TokenStream.h"
18 #include "gc/GC.h"
19 #include "gc/Zone.h"
20 #include "irregexp/imported/regexp-ast.h"
21 #include "irregexp/imported/regexp-bytecode-generator.h"
22 #include "irregexp/imported/regexp-compiler.h"
23 #include "irregexp/imported/regexp-interpreter.h"
24 #include "irregexp/imported/regexp-macro-assembler-arch.h"
25 #include "irregexp/imported/regexp-macro-assembler-tracer.h"
26 #include "irregexp/imported/regexp-parser.h"
27 #include "irregexp/imported/regexp-stack.h"
28 #include "irregexp/imported/regexp.h"
29 #include "irregexp/RegExpNativeMacroAssembler.h"
30 #include "irregexp/RegExpShim.h"
31 #include "jit/JitCommon.h"
32 #include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin, JS::ColumnNumberOffset
33 #include "js/friend/ErrorMessages.h" // JSMSG_*
34 #include "js/friend/StackLimits.h" // js::ReportOverRecursed
35 #include "util/StringBuilder.h"
36 #include "vm/MatchPairs.h"
37 #include "vm/PlainObject.h"
38 #include "vm/RegExpShared.h"
39
40 namespace js {
41 namespace irregexp {
42
43 using mozilla::AssertedCast;
44 using mozilla::Maybe;
45 using mozilla::Nothing;
46 using mozilla::PointerRangeSize;
47 using mozilla::Some;
48
49 using frontend::DummyTokenStream;
50 using frontend::TokenStreamAnyChars;
51
52 using v8::internal::DisallowGarbageCollection;
53 using v8::internal::HandleScope;
54 using v8::internal::InputOutputData;
55 using v8::internal::IrregexpInterpreter;
56 using v8::internal::NativeRegExpMacroAssembler;
57 using v8::internal::RegExpBytecodeGenerator;
58 using v8::internal::RegExpCapture;
59 using v8::internal::RegExpCompileData;
60 using v8::internal::RegExpCompiler;
61 using v8::internal::RegExpError;
62 using v8::internal::RegExpMacroAssembler;
63 using v8::internal::RegExpMacroAssemblerTracer;
64 using v8::internal::RegExpNode;
65 using v8::internal::RegExpParser;
66 using v8::internal::SMRegExpMacroAssembler;
67 using v8::internal::Zone;
68 using v8::internal::ZoneVector;
69
70 using V8HandleString = v8::internal::Handle<v8::internal::String>;
71 using V8HandleRegExp = v8::internal::Handle<v8::internal::IrRegExpData>;
72
73 using namespace v8::internal::regexp_compiler_constants;
74
75 static uint32_t ErrorNumber(RegExpError err) {
76 switch (err) {
77 case RegExpError::kNone:
78 return JSMSG_NOT_AN_ERROR;
79 case RegExpError::kStackOverflow:
80 return JSMSG_OVER_RECURSED;
81 case RegExpError::kAnalysisStackOverflow:
82 return JSMSG_OVER_RECURSED;
83 case RegExpError::kTooLarge:
84 return JSMSG_TOO_MANY_PARENS;
85 case RegExpError::kUnterminatedGroup:
86 return JSMSG_MISSING_PAREN;
87 case RegExpError::kUnmatchedParen:
88 return JSMSG_UNMATCHED_RIGHT_PAREN;
89 case RegExpError::kEscapeAtEndOfPattern:
90 return JSMSG_ESCAPE_AT_END_OF_REGEXP;
91 case RegExpError::kInvalidPropertyName:
92 return JSMSG_INVALID_PROPERTY_NAME;
93 case RegExpError::kInvalidEscape:
94 return JSMSG_INVALID_IDENTITY_ESCAPE;
95 case RegExpError::kInvalidDecimalEscape:
96 return JSMSG_INVALID_DECIMAL_ESCAPE;
97 case RegExpError::kInvalidUnicodeEscape:
98 return JSMSG_INVALID_UNICODE_ESCAPE;
99 case RegExpError::kNothingToRepeat:
100 return JSMSG_NOTHING_TO_REPEAT;
101 case RegExpError::kLoneQuantifierBrackets:
102 // Note: V8 reports the same error for both ']' and '}'.
103 return JSMSG_RAW_BRACKET_IN_REGEXP;
104 case RegExpError::kRangeOutOfOrder:
105 return JSMSG_NUMBERS_OUT_OF_ORDER;
106 case RegExpError::kIncompleteQuantifier:
107 return JSMSG_INCOMPLETE_QUANTIFIER;
108 case RegExpError::kInvalidQuantifier:
109 return JSMSG_INVALID_QUANTIFIER;
110 case RegExpError::kInvalidGroup:
111 return JSMSG_INVALID_GROUP;
112 case RegExpError::kRepeatedFlag:
113 return JSMSG_REPEATED_FLAG;
114 case RegExpError::kInvalidFlagGroup:
115 return JSMSG_INVALID_FLAG_GROUP;
116 case RegExpError::kMultipleFlagDashes:
117 return JSMSG_MULTIPLE_FLAG_DASHES;
118 case RegExpError::kNotLinear:
119 // V8 has an experimental non-backtracking engine. We do not
120 // support it yet.
121 MOZ_CRASH("Non-backtracking execution not supported");
122 case RegExpError::kTooManyCaptures:
123 return JSMSG_TOO_MANY_PARENS;
124 case RegExpError::kInvalidCaptureGroupName:
125 return JSMSG_INVALID_CAPTURE_NAME;
126 case RegExpError::kDuplicateCaptureGroupName:
127 return JSMSG_DUPLICATE_CAPTURE_NAME;
128 case RegExpError::kInvalidNamedReference:
129 return JSMSG_INVALID_NAMED_REF;
130 case RegExpError::kInvalidNamedCaptureReference:
131 return JSMSG_INVALID_NAMED_CAPTURE_REF;
132 case RegExpError::kInvalidClassPropertyName:
133 return JSMSG_INVALID_CLASS_PROPERTY_NAME;
134 case RegExpError::kInvalidCharacterClass:
135 return JSMSG_RANGE_WITH_CLASS_ESCAPE;
136 case RegExpError::kUnterminatedCharacterClass:
137 return JSMSG_UNTERM_CLASS;
138 case RegExpError::kOutOfOrderCharacterClass:
139 return JSMSG_BAD_CLASS_RANGE;
140
141 case RegExpError::kInvalidClassSetOperation:
142 return JSMSG_INVALID_CLASS_SET_OP;
143 case RegExpError::kInvalidCharacterInClass:
144 return JSMSG_INVALID_CHAR_IN_CLASS;
145 case RegExpError::kNegatedCharacterClassWithStrings:
146 return JSMSG_NEGATED_CLASS_WITH_STR;
147
148 case RegExpError::NumErrors:
149 MOZ_CRASH("Unreachable");
150 }
151 MOZ_CRASH("Unreachable");
152 }
153
154 Isolate* CreateIsolate(JSContext* cx) {
155 auto isolate = MakeUnique<Isolate>(cx);
156 if (!isolate || !isolate->init()) {
157 return nullptr;
158 }
159 return isolate.release();
160 }
161
162 void TraceIsolate(JSTracer* trc, Isolate* isolate) { isolate->trace(trc); }
163
164 void DestroyIsolate(Isolate* isolate) {
165 MOZ_ASSERT(isolate->liveHandles() == 0);
166 MOZ_ASSERT(isolate->livePseudoHandles() == 0);
167 js_delete(isolate);
168 }
169
170 size_t IsolateSizeOfIncludingThis(Isolate* isolate,
171 mozilla::MallocSizeOf mallocSizeOf) {
172 return isolate->sizeOfIncludingThis(mallocSizeOf);
173 }
174
175 static JS::ColumnNumberOffset ComputeColumnOffset(const Latin1Char* begin,
176 const Latin1Char* end) {
177 return JS::ColumnNumberOffset(
178 AssertedCast<uint32_t>(PointerRangeSize(begin, end)));
179 }
180
181 static JS::ColumnNumberOffset ComputeColumnOffset(const char16_t* begin,
182 const char16_t* end) {
183 return JS::ColumnNumberOffset(
184 AssertedCast<uint32_t>(unicode::CountUTF16CodeUnits(begin, end)));
185 }
186
187 // This function is varargs purely so it can call ReportCompileErrorLatin1.
188 // We never call it with additional arguments.
189 template <typename CharT>
190 static void ReportSyntaxError(TokenStreamAnyChars& ts,
191 mozilla::Maybe<uint32_t> line,
192 mozilla::Maybe<JS::ColumnNumberOneOrigin> column,
193 RegExpCompileData& result, CharT* start,
194 size_t length, ...) {
195 MOZ_ASSERT(line.isSome() == column.isSome());
196
197 Maybe<gc::AutoSuppressGC> suppressGC;
198 if (JSContext* maybeCx = ts.context()->maybeCurrentJSContext()) {
199 suppressGC.emplace(maybeCx);
200 }
201 uint32_t errorNumber = ErrorNumber(result.error);
202
203 if (errorNumber == JSMSG_OVER_RECURSED) {
204 ReportOverRecursed(ts.context());
205 return;
206 }
207
208 uint32_t offset = std::max(result.error_pos, 0);
209 MOZ_ASSERT(offset <= length);
210
211 ErrorMetadata err;
212
213 // Ordinarily this indicates whether line-of-context information can be
214 // added, but we entirely ignore that here because we create a
215 // a line of context based on the expression source.
216 uint32_t location = ts.currentToken().pos.begin;
217 if (ts.fillExceptingContext(&err, location)) {
218 JS::ColumnNumberOffset columnOffset =
219 ComputeColumnOffset(start, start + offset);
220 if (line.isSome()) {
221 // If this pattern is being checked by the frontend Parser instead
222 // of other API entry points like |new RegExp|, then the parser will
223 // have provided both a line and column pointing at the *beginning*
224 // of the RegExp literal inside the source text.
225 // We adjust the columnNumber to point to the actual syntax error
226 // inside the literal.
227 err.lineNumber = *line;
228 err.columnNumber = *column + columnOffset;
229 } else {
230 // Line breaks are not significant in pattern text in the same way as
231 // in source text, so act as though pattern text is a single line, then
232 // compute a column based on "code point" count (treating a lone
233 // surrogate as a "code point" in UTF-16). Gak.
234 err.lineNumber = 1;
235 err.columnNumber = JS::ColumnNumberOneOrigin() + columnOffset;
236 }
237 }
238
239 // For most error reporting, the line of context derives from the token
240 // stream. So when location information doesn't come from the token
241 // stream, we can't give a line of context. But here the "line of context"
242 // can be (and is) derived from the pattern text, so we can provide it no
243 // matter if the location is derived from the caller.
244
245 const CharT* windowStart =
246 (offset > ErrorMetadata::lineOfContextRadius)
247 ? start + (offset - ErrorMetadata::lineOfContextRadius)
248 : start;
249
250 const CharT* windowEnd =
251 (length - offset > ErrorMetadata::lineOfContextRadius)
252 ? start + offset + ErrorMetadata::lineOfContextRadius
253 : start + length;
254
255 size_t windowLength = PointerRangeSize(windowStart, windowEnd);
256 MOZ_ASSERT(windowLength <= ErrorMetadata::lineOfContextRadius * 2);
257
258 // Create the windowed string, not including the potential line
259 // terminator.
260 StringBuilder windowBuf(ts.context());
261 if (!windowBuf.append(windowStart, windowEnd)) {
262 return;
263 }
264
265 // The line of context must be null-terminated, and StringBuilder doesn't
266 // make that happen unless we force it to.
267 if (!windowBuf.append('\0')) {
268 return;
269 }
270
271 err.lineOfContext.reset(windowBuf.stealChars());
272 if (!err.lineOfContext) {
273 return;
274 }
275
276 err.lineLength = windowLength;
277 err.tokenOffset = offset - (windowStart - start);
278
279 va_list args;
280 va_start(args, length);
281 ReportCompileErrorLatin1VA(ts.context(), std::move(err), nullptr, errorNumber,
282 &args);
283 va_end(args);
284 }
285
286 static void ReportSyntaxError(TokenStreamAnyChars& ts,
287 RegExpCompileData& result,
288 Handle<JSAtom*> pattern) {
289 JS::AutoCheckCannotGC nogc_;
290 if (pattern->hasLatin1Chars()) {
291 ReportSyntaxError(ts, Nothing(), Nothing(), result,
292 pattern->latin1Chars(nogc_), pattern->length());
293 } else {
294 ReportSyntaxError(ts, Nothing(), Nothing(), result,
295 pattern->twoByteChars(nogc_), pattern->length());
296 }
297 }
298
299 template <typename CharT>
300 static bool CheckPatternSyntaxImpl(js::LifoAlloc& alloc,
301 JS::NativeStackLimit stackLimit,
302 const CharT* input, uint32_t inputLength,
303 JS::RegExpFlags flags,
304 RegExpCompileData* result,
305 JS::AutoAssertNoGC& nogc) {
306 LifoAllocScope allocScope(&alloc);
307 Zone zone(allocScope.alloc());
308
309 return RegExpParser::VerifyRegExpSyntax(&zone, stackLimit, input, inputLength,
310 flags, result, nogc);
311 }
312
313 bool CheckPatternSyntax(js::LifoAlloc& alloc, JS::NativeStackLimit stackLimit,
314 TokenStreamAnyChars& ts,
315 const mozilla::Range<const char16_t> chars,
316 JS::RegExpFlags flags, mozilla::Maybe<uint32_t> line,
317 mozilla::Maybe<JS::ColumnNumberOneOrigin> column) {
318 RegExpCompileData result;
319 JS::AutoAssertNoGC nogc;
320 if (!CheckPatternSyntaxImpl(alloc, stackLimit, chars.begin().get(),
321 chars.length(), flags, &result, nogc)) {
322 ReportSyntaxError(ts, line, column, result, chars.begin().get(),
323 chars.length());
324 return false;
325 }
326 return true;
327 }
328
329 bool CheckPatternSyntax(JSContext* cx, JS::NativeStackLimit stackLimit,
330 TokenStreamAnyChars& ts, Handle<JSAtom*> pattern,
331 JS::RegExpFlags flags) {
332 RegExpCompileData result;
333 JS::AutoAssertNoGC nogc(cx);
334 if (pattern->hasLatin1Chars()) {
335 if (!CheckPatternSyntaxImpl(cx->tempLifoAlloc(), stackLimit,
336 pattern->latin1Chars(nogc), pattern->length(),
337 flags, &result, nogc)) {
338 ReportSyntaxError(ts, result, pattern);
339 return false;
340 }
341 return true;
342 }
343 if (!CheckPatternSyntaxImpl(cx->tempLifoAlloc(), stackLimit,
344 pattern->twoByteChars(nogc), pattern->length(),
345 flags, &result, nogc)) {
346 ReportSyntaxError(ts, result, pattern);
347 return false;
348 }
349 return true;
350 }
351
352 // A regexp is a good candidate for Boyer-Moore if it has at least 3
353 // times as many characters as it has unique characters. Note that
354 // table lookups in irregexp are done modulo tableSize (128).
355 template <typename CharT>
356 static bool HasFewDifferentCharacters(const CharT* chars, size_t length) {
357 const uint32_t tableSize =
358 v8::internal::NativeRegExpMacroAssembler::kTableSize;
359 bool character_found[tableSize] = {};
360 uint32_t different = 0;
361 for (uint32_t i = 0; i < length; i++) {
362 uint32_t ch = chars[i] % tableSize;
363 if (!character_found[ch]) {
364 character_found[ch] = true;
365 different++;
366 // We declare a regexp low-alphabet if it has at least 3 times as many
367 // characters as it has different characters.
368 if (different * 3 > length) {
369 return false;
370 }
371 }
372 }
373 return true;
374 }
375
376 // Identifies the sort of pattern where Boyer-Moore is faster than string search
377 static bool UseBoyerMoore(Handle<JSAtom*> pattern, JS::AutoAssertNoGC& nogc) {
378 size_t length =
379 std::min(size_t(kMaxLookaheadForBoyerMoore), pattern->length());
380 if (length <= kPatternTooShortForBoyerMoore) {
381 return false;
382 }
383
384 if (pattern->hasLatin1Chars()) {
385 return HasFewDifferentCharacters(pattern->latin1Chars(nogc), length);
386 }
387 MOZ_ASSERT(pattern->hasTwoByteChars());
388 return HasFewDifferentCharacters(pattern->twoByteChars(nogc), length);
389 }
390
391 // Sample character frequency information for use in Boyer-Moore.
392 static void SampleCharacters(Handle<JSLinearString*> sample_subject,
393 RegExpCompiler& compiler) {
394 static const int kSampleSize = 128;
395 int chars_sampled = 0;
396
397 int length = sample_subject->length();
398
399 int half_way = (length - kSampleSize) / 2;
400 for (int i = std::max(0, half_way); i < length && chars_sampled < kSampleSize;
401 i++, chars_sampled++) {
402 compiler.frequency_collator()->CountCharacter(
403 sample_subject->latin1OrTwoByteChar(i));
404 }
405 }
406
407 // Recursively walking the AST for a deeply nested regexp (like
408 // `/(a(a(a(a(a(a(a(...(a)...))))))))/`) may overflow the stack while
409 // compiling. To avoid this, we use V8's implementation of the Visitor
410 // pattern to walk the AST first with an overly large stack frame.
411 class RegExpDepthCheck final : public v8::internal::RegExpVisitor {
412 public:
413 explicit RegExpDepthCheck(JSContext* cx) : cx_(cx) {}
414
415 bool check(v8::internal::RegExpTree* root) {
416 return !!root->Accept(this, nullptr);
417 }
418
419 // Leaf nodes with no children
420 #define LEAF_DEPTH(Kind) \
421 void* Visit##Kind(v8::internal::RegExp##Kind* node, void*) override { \
422 uint8_t padding[FRAME_PADDING]; \
423 dummy_ = padding; /* Prevent padding from being optimized away.*/ \
424 AutoCheckRecursionLimit recursion(cx_); \
425 return (void*)recursion.checkDontReport(cx_); \
426 }
427
428 LEAF_DEPTH(Assertion)
429 LEAF_DEPTH(Atom)
430 LEAF_DEPTH(BackReference)
431 LEAF_DEPTH(ClassSetOperand)
432 LEAF_DEPTH(ClassRanges)
433 LEAF_DEPTH(Empty)
434 LEAF_DEPTH(Text)
435 #undef LEAF_DEPTH
436
437 // Wrapper nodes with one child
438 #define WRAPPER_DEPTH(Kind) \
439 void* Visit##Kind(v8::internal::RegExp##Kind* node, void*) override { \
440 uint8_t padding[FRAME_PADDING]; \
441 dummy_ = padding; /* Prevent padding from being optimized away.*/ \
442 AutoCheckRecursionLimit recursion(cx_); \
443 if (!recursion.checkDontReport(cx_)) { \
444 return nullptr; \
445 } \
446 return node->body()->Accept(this, nullptr); \
447 }
448
449 WRAPPER_DEPTH(Capture)
450 WRAPPER_DEPTH(Group)
451 WRAPPER_DEPTH(Lookaround)
452 WRAPPER_DEPTH(Quantifier)
453 #undef WRAPPER_DEPTH
454
455 void* VisitAlternative(v8::internal::RegExpAlternative* node,
456 void*) override {
457 uint8_t padding[FRAME_PADDING];
458 dummy_ = padding; /* Prevent padding from being optimized away.*/
459 AutoCheckRecursionLimit recursion(cx_);
460 if (!recursion.checkDontReport(cx_)) {
461 return nullptr;
462 }
463 for (auto* child : *node->nodes()) {
464 if (!child->Accept(this, nullptr)) {
465 return nullptr;
466 }
467 }
468 return (void*)true;
469 }
470 void* VisitDisjunction(v8::internal::RegExpDisjunction* node,
471 void*) override {
472 uint8_t padding[FRAME_PADDING];
473 dummy_ = padding; /* Prevent padding from being optimized away.*/
474 AutoCheckRecursionLimit recursion(cx_);
475 if (!recursion.checkDontReport(cx_)) {
476 return nullptr;
477 }
478 for (auto* child : *node->alternatives()) {
479 if (!child->Accept(this, nullptr)) {
480 return nullptr;
481 }
482 }
483 return (void*)true;
484 }
485 void* VisitClassSetExpression(v8::internal::RegExpClassSetExpression* node,
486 void*) override {
487 uint8_t padding[FRAME_PADDING];
488 dummy_ = padding; /* Prevent padding from being optimized away.*/
489 AutoCheckRecursionLimit recursion(cx_);
490 if (!recursion.checkDontReport(cx_)) {
491 return nullptr;
492 }
493 for (auto* child : *node->operands()) {
494 if (!child->Accept(this, nullptr)) {
495 return nullptr;
496 }
497 }
498 return (void*)true;
499 }
500
501 private:
502 JSContext* cx_;
503 void* dummy_ = nullptr;
504
505 // This size is picked to be comfortably larger than any
506 // RegExp*::ToNode stack frame.
507 static const size_t FRAME_PADDING = 256;
508 };
509
510 enum class AssembleResult {
511 Success,
512 TooLarge,
513 OutOfMemory,
514 };
515
516 [[nodiscard]] static AssembleResult Assemble(
517 JSContext* cx, RegExpCompiler* compiler, RegExpCompileData* data,
518 MutableHandleRegExpShared re, Handle<JSAtom*> pattern, Zone* zone,
519 bool useNativeCode, bool isLatin1) {
520 // Because we create a StackMacroAssembler, this function is not allowed
521 // to GC. If needed, we allocate and throw errors in the caller.
522 jit::TempAllocator temp(&cx->tempLifoAlloc());
523 Maybe<jit::JitContext> jctx;
524 Maybe<js::jit::StackMacroAssembler> stack_masm;
525 UniquePtr<RegExpMacroAssembler> masm;
526 if (useNativeCode) {
527 NativeRegExpMacroAssembler::Mode mode =
528 isLatin1 ? NativeRegExpMacroAssembler::LATIN1
529 : NativeRegExpMacroAssembler::UC16;
530 // If we are compiling native code, we need a macroassembler,
531 // which needs a jit context.
532 jctx.emplace(cx);
533 stack_masm.emplace(cx, temp);
534 #ifdef DEBUG
535 // It would be much preferable to use `class AutoCreatedBy` here, but we
536 // may be operating without an assembler at all if `useNativeCode` is
537 // `false`, so there's no place to put such a call.
538 stack_masm.ref().pushCreator("Assemble() in RegExpAPI.cpp");
539 #endif
540 uint32_t num_capture_registers = re->pairCount() * 2;
541 masm = MakeUnique<SMRegExpMacroAssembler>(cx, stack_masm.ref(), zone, mode,
542 num_capture_registers);
543 } else {
544 masm = MakeUnique<RegExpBytecodeGenerator>(cx->isolate, zone);
545 }
546 if (!masm) {
547 ReportOutOfMemory(cx);
548 return AssembleResult::OutOfMemory;
549 }
550
551 bool isLargePattern =
552 pattern->length() > v8::internal::RegExp::kRegExpTooLargeToOptimize;
553 masm->set_slow_safe(isLargePattern);
554 if (compiler->optimize()) {
555 compiler->set_optimize(!isLargePattern);
556 }
557
558 // When matching a regexp with known maximum length that is anchored
559 // at the end, we may be able to skip the beginning of long input
560 // strings. This decision is made here because it depends on
561 // information in the AST that isn't replicated in the Node
562 // structure used inside the compiler.
563 bool is_start_anchored = data->tree->IsAnchoredAtStart();
564 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
565 int max_length = data->tree->max_match();
566 static const int kMaxBacksearchLimit = 1024;
567 if (is_end_anchored && !is_start_anchored && !re->sticky() &&
568 max_length < kMaxBacksearchLimit) {
569 masm->SetCurrentPositionFromEnd(max_length);
570 }
571
572 if (re->global()) {
573 RegExpMacroAssembler::GlobalMode mode = RegExpMacroAssembler::GLOBAL;
574 if (data->tree->min_match() > 0) {
575 mode = RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK;
576 } else if (re->unicode()) {
577 mode = RegExpMacroAssembler::GLOBAL_UNICODE;
578 }
579 masm->set_global_mode(mode);
580 }
581
582 // The masm tracer works as a thin wrapper around another macroassembler.
583 RegExpMacroAssembler* masm_ptr = masm.get();
584 #ifdef DEBUG
585 UniquePtr<RegExpMacroAssembler> tracer_masm;
586 if (jit::JitOptions.trace_regexp_assembler) {
587 tracer_masm = MakeUnique<RegExpMacroAssemblerTracer>(cx->isolate, masm_ptr);
588 masm_ptr = tracer_masm.get();
589 }
590 #endif
591
592 // Compile the regexp.
593 V8HandleString wrappedPattern(v8::internal::String(pattern), cx->isolate);
594 RegExpCompiler::CompilationResult result = compiler->Assemble(
595 cx->isolate, masm_ptr, data->node, data->capture_count, wrappedPattern);
596
597 if (useNativeCode) {
598 #ifdef DEBUG
599 // See comment referencing `pushCreator` above.
600 stack_masm.ref().popCreator();
601 #endif
602 }
603
604 if (!result.Succeeded()) {
605 MOZ_ASSERT(result.error == RegExpError::kTooLarge);
606 return AssembleResult::TooLarge;
607 }
608 if (result.code->value().isUndefined()) {
609 // SMRegExpMacroAssembler::GetCode returns undefined on OOM.
610 MOZ_ASSERT(useNativeCode);
611 return AssembleResult::OutOfMemory;
612 }
613
614 re->updateMaxRegisters(result.num_registers);
615 if (useNativeCode) {
616 // Transfer ownership of the tables from the macroassembler to the
617 // RegExpShared.
618 SMRegExpMacroAssembler::TableVector& tables =
619 static_cast<SMRegExpMacroAssembler*>(masm.get())->tables();
620 for (uint32_t i = 0; i < tables.length(); i++) {
621 if (!re->addTable(std::move(tables[i]))) {
622 ReportOutOfMemory(cx);
623 return AssembleResult::OutOfMemory;
624 }
625 }
626 re->setJitCode(v8::internal::Code::cast(*result.code).inner(), isLatin1);
627 } else {
628 // Transfer ownership of the bytecode from the HandleScope to the
629 // RegExpShared.
630 ByteArray bytecode =
631 v8::internal::ByteArray::cast(*result.code).takeOwnership(cx->isolate);
632 uint32_t length = bytecode->length();
633 re->setByteCode(bytecode.release(), isLatin1);
634 js::AddCellMemory(re, length, MemoryUse::RegExpSharedBytecode);
635 }
636
637 return AssembleResult::Success;
638 }
639
640 struct RegExpNamedCapture {
641 const ZoneVector<char16_t>* name;
642 js::Vector<uint32_t> indices;
643
644 RegExpNamedCapture(JSContext* cx, const ZoneVector<char16_t>* name)
645 : name(name), indices(cx) {}
646 };
647
648 struct RegExpNamedCaptureIndexLess {
649 bool operator()(const RegExpNamedCapture& lhs,
650 const RegExpNamedCapture& rhs) const {
651 // Every name must have at least one corresponding capture index, and all
652 // the capture indices must be distinct. This allows us to sort on the
653 // lowest capture index.
654 MOZ_ASSERT(!lhs.indices.empty());
655 MOZ_ASSERT(!rhs.indices.empty());
656 MOZ_ASSERT_IF(&lhs != &rhs, lhs.indices[0] != rhs.indices[0]);
657 return lhs.indices[0] < rhs.indices[0];
658 }
659 };
660
661 bool InitializeNamedCaptures(JSContext* cx, HandleRegExpShared re,
662 ZoneVector<RegExpCapture*>* namedCaptures) {
663 // The irregexp parser returns named capture information in the form
664 // of a ZoneVector of RegExpCaptures nodes, each of which stores the
665 // capture name and the corresponding capture index. We create a
666 // template object with a property for each capture name, and store
667 // the capture indices as a heap-allocated array.
668 uint32_t numNamedCaptures = namedCaptures->size();
669
670 // The input vector of named captures is already sorted by name, and then by
671 // capture index if there are duplicates. We iterate through the captures,
672 // creating groups for each set of indices corresponding to a name. Usually,
673 // there will be a 1:1 mapping.
674 js::Vector<RegExpNamedCapture> groups(cx);
675 if (!groups.reserve(numNamedCaptures)) {
676 js::ReportOutOfMemory(cx);
677 return false;
678 }
679 const ZoneVector<char16_t>* prevName = nullptr;
680 uint32_t numDistinctNamedCaptures = 0;
681 for (uint32_t i = 0; i < numNamedCaptures; i++) {
682 RegExpCapture* capture = (*namedCaptures)[i];
683 const ZoneVector<char16_t>* name = capture->name();
684 if (!prevName || *name != *prevName) {
685 if (!groups.emplaceBack(RegExpNamedCapture(cx, name))) {
686 js::ReportOutOfMemory(cx);
687 return false;
688 }
689 numDistinctNamedCaptures++;
690 prevName = name;
691 }
692 // Make sure we're getting the indices in the order we expect
693 MOZ_ASSERT_IF(!groups.back().indices.empty(),
694 groups.back().indices.back() < (uint32_t)capture->index());
695 if (!groups.back().indices.emplaceBack(capture->index())) {
696 js::ReportOutOfMemory(cx);
697 return false;
698 }
699 }
700
701 // The capture name map must be sorted by index.
702 std::sort(groups.begin(), groups.end(), RegExpNamedCaptureIndexLess{});
703
704 // Create a plain template object.
705 Rooted<js::PlainObject*> templateObject(
706 cx, js::NewPlainObjectWithProto(cx, nullptr, TenuredObject));
707 if (!templateObject) {
708 return false;
709 }
710
711 // Allocate the capture index array.
712 uint32_t arraySize = numNamedCaptures * sizeof(uint32_t);
713 UniquePtr<uint32_t[], JS::FreePolicy> captureIndices(
714 static_cast<uint32_t*>(js_malloc(arraySize)));
715 if (!captureIndices) {
716 js::ReportOutOfMemory(cx);
717 return false;
718 }
719
720 // Allocate the capture slice index array, if necessary. We only use this
721 // if we have duplicate named capture groups.
722 bool hasDuplicateNames = numNamedCaptures != numDistinctNamedCaptures;
723 UniquePtr<uint32_t[], JS::FreePolicy> sliceIndices;
724 if (hasDuplicateNames) {
725 arraySize = numDistinctNamedCaptures * sizeof(uint32_t);
726 sliceIndices.reset(static_cast<uint32_t*>(js_malloc(arraySize)));
727 if (!sliceIndices) {
728 js::ReportOutOfMemory(cx);
729 return false;
730 }
731 }
732
733 // Initialize the properties of the template and store capture indices.
734 RootedId id(cx);
735 RootedValue dummyString(cx, StringValue(cx->runtime()->emptyString));
736 size_t insertIndex = 0;
737
738 for (size_t i = 0; i < numDistinctNamedCaptures; ++i) {
739 RegExpNamedCapture& group = groups[i];
740 // We store the names as properties on the template object, in the order of
741 // their lowest capture index.
742 JSAtom* name = js::AtomizeChars(cx, group.name->data(), group.name->size());
743 if (!name) {
744 return false;
745 }
746 id = NameToId(name->asPropertyName());
747 if (!NativeDefineDataProperty(cx, templateObject, id, dummyString,
748 JSPROP_ENUMERATE)) {
749 return false;
750 }
751 // The slice index keeps track of the captureIndex where indices
752 // corresponding to a name start. The difference between the current slice
753 // index and the next slice index is used to calculate how many values to
754 // return in the slice. This is only needed when we have duplicate capture
755 // names, otherwise, there's a 1:1 mapping, and we don't need the extra
756 // data.
757 if (hasDuplicateNames) {
758 sliceIndices[i] = insertIndex;
759 }
760
761 for (uint32_t captureIndex : groups[i].indices) {
762 captureIndices[insertIndex++] = captureIndex;
763 }
764 }
765
766 RegExpShared::InitializeNamedCaptures(
767 cx, re, numNamedCaptures, numDistinctNamedCaptures, templateObject,
768 captureIndices.release(), sliceIndices.release());
769 return true;
770 }
771
772 bool CompilePattern(JSContext* cx, MutableHandleRegExpShared re,
773 Handle<JSLinearString*> input,
774 RegExpShared::CodeKind codeKind) {
775 Rooted<JSAtom*> pattern(cx, re->getSource());
776 JS::RegExpFlags flags = re->getFlags();
777 LifoAllocScope allocScope(&cx->tempLifoAlloc());
778 HandleScope handleScope(cx->isolate);
779 Zone zone(allocScope.alloc());
780
781 RegExpCompileData data;
782 {
783 V8HandleString wrappedPattern(v8::internal::String(pattern), cx->isolate);
784 if (!RegExpParser::ParseRegExpFromHeapString(
785 cx->isolate, &zone, wrappedPattern, flags, &data)) {
786 AutoReportFrontendContext fc(cx);
787 JS::CompileOptions options(cx);
788 DummyTokenStream dummyTokenStream(&fc, options);
789 ReportSyntaxError(dummyTokenStream, data, pattern);
790 return false;
791 }
792 }
793
794 // Avoid stack overflow while recursively walking the AST.
795 RegExpDepthCheck depthCheck(cx);
796 if (!depthCheck.check(data.tree)) {
797 JS_ReportErrorASCII(cx, "regexp too big");
798 cx->reportResourceExhaustion();
799 return false;
800 }
801
802 if (re->kind() == RegExpShared::Kind::Unparsed) {
803 // This is the first time we have compiled this regexp.
804 // First, check to see if we should use simple string search
805 // with an atom.
806 if (!flags.ignoreCase() && !flags.sticky()) {
807 Rooted<JSAtom*> searchAtom(cx);
808 if (data.simple) {
809 // The parse-tree is a single atom that is equal to the pattern.
810 searchAtom = re->getSource();
811 } else if (data.tree->IsAtom() && data.capture_count == 0) {
812 // The parse-tree is a single atom that is not equal to the pattern.
813 v8::internal::RegExpAtom* atom = data.tree->AsAtom();
814 const char16_t* twoByteChars = atom->data().begin();
815 searchAtom = AtomizeChars(cx, twoByteChars, atom->length());
816 if (!searchAtom) {
817 return false;
818 }
819 }
820 JS::AutoAssertNoGC nogc(cx);
821 if (searchAtom && !UseBoyerMoore(searchAtom, nogc)) {
822 re->useAtomMatch(searchAtom);
823 return true;
824 }
825 }
826 if (data.named_captures) {
827 if (!InitializeNamedCaptures(cx, re, data.named_captures)) {
828 return false;
829 }
830 }
831 // All fallible initialization has succeeded, so we can change state.
832 // Add one to capture_count to account for the whole-match capture.
833 uint32_t pairCount = data.capture_count + 1;
834 re->useRegExpMatch(pairCount);
835 }
836
837 MOZ_ASSERT(re->kind() == RegExpShared::Kind::RegExp);
838
839 RegExpCompiler compiler(cx->isolate, &zone, data.capture_count, flags,
840 input->hasLatin1Chars());
841
842 bool isLatin1 = input->hasLatin1Chars();
843
844 SampleCharacters(input, compiler);
845 data.node = compiler.PreprocessRegExp(&data, isLatin1);
846 if (data.error != RegExpError::kNone) {
847 MOZ_ASSERT(data.error == RegExpError::kTooLarge);
848 JS_ReportErrorASCII(cx, "regexp too big");
849 cx->reportResourceExhaustion();
850 return false;
851 }
852 data.error = AnalyzeRegExp(cx->isolate, isLatin1, flags, data.node);
853 if (data.error != RegExpError::kNone) {
854 MOZ_ASSERT(data.error == RegExpError::kAnalysisStackOverflow);
855 ReportOverRecursed(cx);
856 return false;
857 }
858
859 bool useNativeCode = codeKind == RegExpShared::CodeKind::Jitcode;
860 MOZ_ASSERT_IF(useNativeCode, IsNativeRegExpEnabled());
861
862 switch (Assemble(cx, &compiler, &data, re, pattern, &zone, useNativeCode,
863 isLatin1)) {
864 case AssembleResult::TooLarge:
865 JS_ReportErrorASCII(cx, "regexp too big");
866 cx->reportResourceExhaustion();
867 return false;
868 case AssembleResult::OutOfMemory:
869 MOZ_ASSERT(cx->isThrowingOutOfMemory());
870 return false;
871 case AssembleResult::Success:
872 break;
873 }
874 return true;
875 }
876
877 template <typename CharT>
878 RegExpRunStatus ExecuteRaw(jit::JitCode* code, const CharT* chars,
879 size_t length, size_t startIndex,
880 VectorMatchPairs* matches) {
881 InputOutputData data(chars, chars + length, startIndex, matches);
882
883 static_assert(static_cast<int32_t>(RegExpRunStatus::Error) ==
884 v8::internal::RegExp::kInternalRegExpException);
885 static_assert(static_cast<int32_t>(RegExpRunStatus::Success) ==
886 v8::internal::RegExp::kInternalRegExpSuccess);
887 static_assert(static_cast<int32_t>(RegExpRunStatus::Success_NotFound) ==
888 v8::internal::RegExp::kInternalRegExpFailure);
889
890 using RegExpCodeSignature = int (*)(InputOutputData*);
891 auto function = reinterpret_cast<RegExpCodeSignature>(code->raw());
892 {
893 JS::AutoSuppressGCAnalysis nogc;
894 return (RegExpRunStatus)CALL_GENERATED_1(function, &data);
895 }
896 }
897
898 RegExpRunStatus Interpret(JSContext* cx, MutableHandleRegExpShared re,
899 Handle<JSLinearString*> input, size_t startIndex,
900 VectorMatchPairs* matches) {
901 MOZ_ASSERT(re->getByteCode(input->hasLatin1Chars()));
902
903 HandleScope handleScope(cx->isolate);
904 V8HandleRegExp wrappedRegExp(v8::internal::IrRegExpData(re), cx->isolate);
905 V8HandleString wrappedInput(v8::internal::String(input), cx->isolate);
906
907 static_assert(static_cast<int32_t>(RegExpRunStatus::Error) ==
908 v8::internal::RegExp::kInternalRegExpException);
909 static_assert(static_cast<int32_t>(RegExpRunStatus::Success) ==
910 v8::internal::RegExp::kInternalRegExpSuccess);
911 static_assert(static_cast<int32_t>(RegExpRunStatus::Success_NotFound) ==
912 v8::internal::RegExp::kInternalRegExpFailure);
913
914 RegExpRunStatus status =
915 (RegExpRunStatus)IrregexpInterpreter::MatchForCallFromRuntime(
916 cx->isolate, wrappedRegExp, wrappedInput, matches->pairsRaw(),
917 uint32_t(matches->pairCount() * 2), uint32_t(startIndex));
918
919 MOZ_ASSERT(status == RegExpRunStatus::Error ||
920 status == RegExpRunStatus::Success ||
921 status == RegExpRunStatus::Success_NotFound);
922
923 return status;
924 }
925
926 RegExpRunStatus Execute(JSContext* cx, MutableHandleRegExpShared re,
927 Handle<JSLinearString*> input, size_t startIndex,
928 VectorMatchPairs* matches) {
929 bool latin1 = input->hasLatin1Chars();
930 jit::JitCode* jitCode = re->getJitCode(latin1);
931 bool isCompiled = !!jitCode;
932
933 // Reset the Irregexp backtrack stack if it grows during execution.
934 irregexp::RegExpStackScope stackScope(cx->isolate);
935
936 if (isCompiled) {
937 JS::AutoCheckCannotGC nogc;
938 if (latin1) {
939 return ExecuteRaw(jitCode, input->latin1Chars(nogc), input->length(),
940 startIndex, matches);
941 }
942 return ExecuteRaw(jitCode, input->twoByteChars(nogc), input->length(),
943 startIndex, matches);
944 }
945
946 return Interpret(cx, re, input, startIndex, matches);
947 }
948
949 RegExpRunStatus ExecuteForFuzzing(JSContext* cx, Handle<JSAtom*> pattern,
950 Handle<JSLinearString*> input,
951 JS::RegExpFlags flags, size_t startIndex,
952 VectorMatchPairs* matches,
953 RegExpShared::CodeKind codeKind) {
954 RootedRegExpShared re(cx, cx->zone()->regExps().get(cx, pattern, flags));
955 if (!RegExpShared::compileIfNecessary(cx, &re, input, codeKind)) {
956 return RegExpRunStatus::Error;
957 }
958 return RegExpShared::execute(cx, &re, input, startIndex, matches);
959 }
960
961 bool GrowBacktrackStack(RegExpStack* regexp_stack) {
962 return SMRegExpMacroAssembler::GrowBacktrackStack(regexp_stack);
963 }
964
965 uint32_t CaseInsensitiveCompareNonUnicode(const char16_t* substring1,
966 const char16_t* substring2,
967 size_t byteLength) {
968 return SMRegExpMacroAssembler::CaseInsensitiveCompareNonUnicode(
969 substring1, substring2, byteLength);
970 }
971
972 uint32_t CaseInsensitiveCompareUnicode(const char16_t* substring1,
973 const char16_t* substring2,
974 size_t byteLength) {
975 return SMRegExpMacroAssembler::CaseInsensitiveCompareUnicode(
976 substring1, substring2, byteLength);
977 }
978
979 bool IsCharacterInRangeArray(uint32_t c, ByteArrayData* ranges) {
980 return SMRegExpMacroAssembler::IsCharacterInRangeArray(c, ranges);
981 }
982
983 #ifdef DEBUG
984 bool IsolateShouldSimulateInterrupt(Isolate* isolate) {
985 return isolate->shouldSimulateInterrupt_ != 0;
986 }
987
988 void IsolateSetShouldSimulateInterrupt(Isolate* isolate) {
989 isolate->shouldSimulateInterrupt_ = 1;
990 }
991 void IsolateClearShouldSimulateInterrupt(Isolate* isolate) {
992 isolate->shouldSimulateInterrupt_ = 0;
993 }
994 #endif
995
996 } // namespace irregexp
997 } // namespace js