Skip to content

Commit

Permalink
fix: bsearch prevent overflow on mid calculation
Browse files Browse the repository at this point in the history
Signed-off-by: Eloy Coto <[email protected]>
  • Loading branch information
eloycoto committed Feb 29, 2024
1 parent 95cbcc5 commit df31443
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ void *alloca (size_t);
#include "jv_private.h"
#include "util.h"


#define BINOP(name) \
static jv f_ ## name(jq_state *jq, jv input, jv a, jv b) { \
jv_free(input); \
Expand Down Expand Up @@ -785,13 +786,14 @@ static jv f_sort_by_impl(jq_state *jq, jv input, jv keys) {
/* If the input is not sorted, bsearch will terminate but with irrelevant results. */
static jv f_bsearch(jq_state *jq, jv input, jv target) {
if (jv_get_kind(input) != JV_KIND_ARRAY) {
jv_free(target);
return type_error(input, "cannot be searched from");
}
int start = 0;
int end = jv_array_length(jv_copy(input));
jv answer = jv_invalid();
while (start < end) {
int mid = (start + end) / 2;
int mid = start + (end - start) / 2;
int result = jv_cmp(jv_copy(target), jv_array_get(jv_copy(input), mid));
if (result == 0) {
answer = jv_number(mid);
Expand Down
4 changes: 4 additions & 0 deletions tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -1559,6 +1559,10 @@ bsearch({x:1})
[{ "x": 0 },{ "x": 1 },{ "x": 2 }]
1

try ["OK", bsearch(0)] catch ["KO",.]
"aa"
["KO","string (\"aa\") cannot be searched from"]

# strptime tests are in optional.test

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

0 comments on commit df31443

Please sign in to comment.