Skip to content
Myr

Fix undefined behavior on out-of-range array index in has() and del() (#3560)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Converting a double outside the int range to int is undefined behavior, and has() and del() did it on array indices like infinite or 1e10, which UBSan reports as "inf is outside the range of representable values of type 'int'". Only NaN was guarded against. Clamp the index to the int range in has(), as getting and setting array elements already do, and drop out-of-range indices in del() before they are converted. Such indices can never refer to an element, so has() returns false and del() leaves the array unchanged, the same as for indices past the end of the array. Valid indices deleted together with out-of-range ones, as in del(.[0, 1e10]), are still deleted.

authored by omkar bhor · committed by GitHub · parent dbbae0d · Browse files · 2 files+40 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+40 added−4 removed

  • tests:+32 added−0 removed
  • other:+8 added−4 removed

2 files+40 added−4 removed

modified:src/jv_aux.c+8 added-4 removed
258 unmodified lines
259 ret = jv_bool(jv_is_valid(elem));260 jv_free(elem);261 } else if (jv_get_kind(t) == JV_KIND_ARRAY &&262 jv_get_kind(k) == JV_KIND_NUMBER) {263 if (jvp_number_is_nan(k)) {263 double nv = jv_number_value(k);264 if (isnan(nv)) {265 jv_free(t);266 ret = jv_false();267 } else {268 if (nv < INT_MIN) nv = INT_MIN;269 if (nv > INT_MAX) nv = INT_MAX;267 jv elem = jv_array_get(t, (int)jv_number_value(k));270 jv elem = jv_array_get(t, (int)nv);271 ret = jv_bool(jv_is_valid(elem));272 jv_free(elem);273 }274 jv_free(k);
21 unmodified lines
296 jv new_array = jv_array();297 jv starts = jv_array(), ends = jv_array();298 jv_array_foreach(keys, i, key) {299 if (jv_get_kind(key) == JV_KIND_NUMBER) {297 if (jvp_number_is_nan(key)) {300 double nv = jv_number_value(key);301 if (isnan(nv) || nv < INT_MIN || nv > INT_MAX) {302 jv_free(key);299 } else if (jv_number_value(key) < 0) {303 } else if (nv < 0) {304 neg_keys = jv_array_append(neg_keys, key);305 } else {306 nonneg_keys = jv_array_append(nonneg_keys, key);307 }
546 unmodified lines
modified:tests/jq.test+32 added
1750 unmodified lines
1751has(nan)1752[0,1,2]1753false17541755has(infinite)1756[0,1,2]1757false17581759has(-infinite)1760[0,1,2]1761false17621763del(.[infinite])1764[1,2,3]1765[1,2,3]17661767del(.[-infinite])1768[1,2,3]1769[1,2,3]17701771has(1e10)1772[0,1,2]1773false17741775has(-1e10)1776[0,1,2]1777false17781779del(.[1e10])1780[1,2,3]1781[1,2,3]17821783del(.[-1e10])1784[1,2,3]1785[1,2,3]17861787keys1788[42,3,35]1789[0,1,2]1790
1031 unmodified lines