Skip to content

Commit 5c0aaba

Browse files
committed
fix: bsearch prevent overflow on mid calculation
Signed-off-by: Eloy Coto <[email protected]>
1 parent 097fc63 commit 5c0aaba

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

src/builtin.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ void *alloca (size_t);
4646
#include "jv_private.h"
4747
#include "util.h"
4848

49+
4950
#define BINOP(name) \
5051
static jv f_ ## name(jq_state *jq, jv input, jv a, jv b) { \
5152
jv_free(input); \
@@ -785,13 +786,14 @@ static jv f_sort_by_impl(jq_state *jq, jv input, jv keys) {
785786
/* If the input is not sorted, bsearch will terminate but with irrelevant results. */
786787
static jv f_bsearch(jq_state *jq, jv input, jv target) {
787788
if (jv_get_kind(input) != JV_KIND_ARRAY) {
789+
jv_free(target);
788790
return type_error(input, "cannot be searched from");
789791
}
790792
int start = 0;
791793
int end = jv_array_length(jv_copy(input));
792794
jv answer = jv_invalid();
793795
while (start < end) {
794-
int mid = (start + end) / 2;
796+
int mid = start + (end - start) / 2;
795797
int result = jv_cmp(jv_copy(target), jv_array_get(jv_copy(input), mid));
796798
if (result == 0) {
797799
answer = jv_number(mid);

tests/jq.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1559,6 +1559,10 @@ bsearch({x:1})
15591559
[{ "x": 0 },{ "x": 1 },{ "x": 2 }]
15601560
1
15611561

1562+
try ["OK", bsearch(0)] catch ["KO",.]
1563+
"aa"
1564+
["KO","string (\"aa\") cannot be searched from"]
1565+
15621566
# strptime tests are in optional.test
15631567

15641568
strftime("%Y-%m-%dT%H:%M:%SZ")

0 commit comments

Comments
 (0)