Skip to content

Commit 1ccaa02

Browse files
committed
GH-50380: [C++][Gandiva] check offset bounds before allocating in byte_substr
Move the past-end bounds check ahead of the arena_malloc so an offset beyond text_len returns early without allocating an output buffer or risking a spurious OOM error.
1 parent ead3d73 commit 1ccaa02

1 file changed

Lines changed: 11 additions & 10 deletions

File tree

cpp/src/gandiva/precompiled/string_ops.cc

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2471,15 +2471,6 @@ const char* byte_substr_binary_int32_int32(gdv_int64 context, const char* text,
24712471
return "";
24722472
}
24732473

2474-
char* ret =
2475-
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, text_len));
2476-
2477-
if (ret == nullptr) {
2478-
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
2479-
*out_len = 0;
2480-
return "";
2481-
}
2482-
24832474
int32_t startPos = 0;
24842475
if (offset >= 0) {
24852476
startPos = offset - 1;
@@ -2488,12 +2479,22 @@ const char* byte_substr_binary_int32_int32(gdv_int64 context, const char* text,
24882479
}
24892480

24902481
// an offset past the end of the text leaves nothing to copy; without this the
2491-
// truncation below yields a negative *out_len that memcpy reads as a huge size
2482+
// truncation below yields a negative *out_len that memcpy reads as a huge size.
2483+
// check before allocating so a past-end offset needs no output buffer at all
24922484
if (startPos >= text_len) {
24932485
*out_len = 0;
24942486
return "";
24952487
}
24962488

2489+
char* ret =
2490+
reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, text_len));
2491+
2492+
if (ret == nullptr) {
2493+
gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string");
2494+
*out_len = 0;
2495+
return "";
2496+
}
2497+
24972498
// calculate end position from length and truncate to upper value bounds
24982499
if (startPos + length > text_len) {
24992500
*out_len = text_len - startPos;

0 commit comments

Comments
 (0)