Skip to content

Commit

Permalink
fix(api): nvim_buf_get_text() crashes with large negative column neov…
Browse files Browse the repository at this point in the history
…im#28740

Problem:
crash when calling nvim_buf_get_text() with a large negative start_col:

    call nvim_buf_get_text(0, 0, -123456789, 0, 0, {})

Solution:
clamp start_col after subtracting it from the line length.
  • Loading branch information
vanaigr authored Sep 3, 2024
1 parent ceddaed commit d1d7d54
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 11 deletions.
14 changes: 4 additions & 10 deletions src/nvim/api/private/helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -528,21 +528,15 @@ String buf_get_text(buf_T *buf, int64_t lnum, int64_t start_col, int64_t end_col
start_col = start_col < 0 ? line_length + start_col + 1 : start_col;
end_col = end_col < 0 ? line_length + end_col + 1 : end_col;

if (start_col >= MAXCOL || end_col >= MAXCOL) {
api_set_error(err, kErrorTypeValidation, "Column index is too high");
return rv;
}
start_col = MIN(MAX(0, start_col), line_length);
end_col = MIN(MAX(0, end_col), line_length);

if (start_col > end_col) {
api_set_error(err, kErrorTypeValidation, "start_col must be less than end_col");
return rv;
}

if (start_col >= line_length) {
api_set_error(err, kErrorTypeValidation, "start_col must be less than or equal to end_col");
return rv;
}

return cstrn_as_string(&bufstr[start_col], (size_t)(end_col - start_col));
return cbuf_as_string(bufstr + start_col, (size_t)(end_col - start_col));
}

void api_free_string(String value)
Expand Down
4 changes: 3 additions & 1 deletion test/functional/api/buffer_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1891,6 +1891,8 @@ describe('api/buf', function()
eq({ '' }, get_text(0, 0, 18, 0, 20, {}))
eq({ 'ext' }, get_text(0, -2, 1, -2, 4, {}))
eq({ 'hello foo!', 'text', 'm' }, get_text(0, 0, 0, 2, 1, {}))
eq({ 'hello foo!' }, get_text(0, 0, -987654321, 0, 987654321, {}))
eq({ '' }, get_text(0, 0, -15, 0, -20, {}))
end)

it('errors on out-of-range', function()
Expand All @@ -1904,7 +1906,7 @@ describe('api/buf', function()

it('errors when start is greater than end', function()
eq("'start' is higher than 'end'", pcall_err(get_text, 0, 1, 0, 0, 0, {}))
eq('start_col must be less than end_col', pcall_err(get_text, 0, 0, 1, 0, 0, {}))
eq('start_col must be less than or equal to end_col', pcall_err(get_text, 0, 0, 1, 0, 0, {}))
end)
end)

Expand Down

0 comments on commit d1d7d54

Please sign in to comment.