Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion cpp/src/gandiva/precompiled/string_ops.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2022,8 +2022,19 @@ gdv_int32 evaluate_return_char_length(gdv_int32 text_len, gdv_int32 actual_text_
gdv_int32 mod = (return_length - actual_text_len) % fill_actual_text_len;
gdv_int32 char_len = 0;
gdv_int32 fill_index = 0;
for (gdv_int32 i = 0; i < mod; i++) {
for (gdv_int32 i = 0; i < mod && fill_index < fill_text_len; i++) {
// step over the glyph the same way utf8_length_ignore_invalid counted it, so the
// two stay in sync and the walk never leaves the fill buffer
char_len = utf8_char_length(fill_text[fill_index]);
if (char_len == 0 || fill_index + char_len > fill_text_len) {
char_len = 1;
}
for (gdv_int32 j = 1; j < char_len; ++j) {
if ((fill_text[fill_index + j] & 0xC0) != 0x80) {
char_len = j;
break;
}
}
fill_index += char_len;
return_char_length += char_len;
}
Expand Down
29 changes: 29 additions & 0 deletions cpp/src/gandiva/precompiled/string_ops_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1664,6 +1664,35 @@ TEST(TestStringOps, TestPadMalformedUtf8KeepsValidGlyph) {
EXPECT_EQ(std::string(out_str, out_len), text_str + " ");
}

TEST(TestStringOps, TestPadMalformedUtf8FillNoOverread) {
gandiva::ExecutionContext ctx;
uint64_t ctx_ptr = reinterpret_cast<gdv_int64>(&ctx);
gdv_int32 out_len = 0;

// {0xE0, 'a', 'a'}: a 3-byte lead byte whose continuation bytes are missing.
// utf8_length_ignore_invalid() counts it as three glyphs, so the partial fill
// loop in evaluate_return_char_length() runs twice while its first step used
// to consume all three bytes and read past the end. The fill text is held in
// an exactly-sized heap buffer so any over-read trips AddressSanitizer.
const char bytes[] = {'\xE0', 'a', 'a'};
const auto fill_len = static_cast<gdv_int32>(sizeof(bytes));
std::unique_ptr<char[]> fill(new char[fill_len]);
std::memcpy(fill.get(), bytes, fill_len);
const std::string fill_str(fill.get(), fill_len);

// "ab" padded to width 7 takes 5 fill glyphs, each one byte wide here.
const std::string padding = fill_str + fill_str.substr(0, 2);

const char* out_str =
lpad_utf8_int32_utf8(ctx_ptr, "ab", 2, 7, fill.get(), fill_len, &out_len);
EXPECT_EQ(out_len, 7);
EXPECT_EQ(std::string(out_str, out_len), padding + "ab");

out_str = rpad_utf8_int32_utf8(ctx_ptr, "ab", 2, 7, fill.get(), fill_len, &out_len);
EXPECT_EQ(out_len, 7);
EXPECT_EQ(std::string(out_str, out_len), "ab" + padding);
}

TEST(TestStringOps, TestRtrim) {
gandiva::ExecutionContext ctx;
uint64_t ctx_ptr = reinterpret_cast<gdv_int64>(&ctx);
Expand Down
Loading