From 358378c1c073440ef830a3485e7d6cb9382e0c92 Mon Sep 17 00:00:00 2001 From: Ali Mohammad Pur Date: Wed, 11 Dec 2024 10:56:32 +0100 Subject: [PATCH] LibRegex: Pick the right target for OpCode_Repeat Repeat's 'offset' field is a bit odd in that it is treated as a negative offset, causing a backwards jump when positive; the optimizer didn't correctly model this behaviour, which caused crashes and misopts when dealing with Repeats. This commit fixes that behaviour. --- Libraries/LibRegex/RegexOptimizer.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Libraries/LibRegex/RegexOptimizer.cpp b/Libraries/LibRegex/RegexOptimizer.cpp index 821aa234241..b3d08d935c2 100644 --- a/Libraries/LibRegex/RegexOptimizer.cpp +++ b/Libraries/LibRegex/RegexOptimizer.cpp @@ -97,7 +97,8 @@ typename Regex::BasicBlockList Regex::split_basic_blocks(ByteCod break; case OpCodeId::Repeat: { // Repeat produces two blocks, one containing its repeated expr, and one after that. - auto repeat_start = state.instruction_position - static_cast(opcode).offset(); + auto& repeat = static_cast(opcode); + auto repeat_start = state.instruction_position - repeat.offset() - repeat.size(); if (repeat_start > end_of_last_block) block_boundaries.append({ end_of_last_block, repeat_start, "Repeat"sv }); block_boundaries.append({ repeat_start, state.instruction_position, "Repeat after"sv }); @@ -1221,6 +1222,7 @@ void Optimizer::append_alternation(ByteCode& target, Span alternatives ssize_t jump_offset; auto is_jump = true; auto patch_location = state.instruction_position + 1; + bool should_negate = false; switch (opcode.opcode_id()) { case OpCodeId::Jump: @@ -1243,6 +1245,7 @@ void Optimizer::append_alternation(ByteCode& target, Span alternatives break; case OpCodeId::Repeat: jump_offset = static_cast(0) - static_cast(static_cast(opcode).offset()) - static_cast(opcode.size()); + should_negate = true; break; default: is_jump = false; @@ -1272,7 +1275,10 @@ void Optimizer::append_alternation(ByteCode& target, Span alternatives intended_jump_ip); VERIFY_NOT_REACHED(); } - target[patch_location] = static_cast(*target_ip - patch_location - 1); + ssize_t target_value = *target_ip - patch_location - 1; + if (should_negate) + target_value = -target_value + 2; // from -1 to +1. + target[patch_location] = static_cast(target_value); } else { patch_locations.append({ QualifiedIP { ip.alternative_index, intended_jump_ip }, patch_location }); }