Re: [PATCH 01/14] Fix latent bug in dwarf2_find_containing_comp_unit

Simon Marchi
2020-02-19T03:42:30Z

On 2020-02-15 11:54 a.m., Tom Tromey wrote:
> dwarf2_find_containing_comp_unit has this in its binary search:
>
> if (mid_cu->is_dwz > offset_in_dwz
> || (mid_cu->is_dwz == offset_in_dwz
> && mid_cu->sect_off + mid_cu->length >= sect_off))
> high = mid;
>
> The intent here is to determine whether SECT_OFF appears in or before
> MID_CU.
>
> I believe this has an off-by-one error, and that the check should use
> ">" rather than ">=". If the two side are equal, then SECT_OFF
> actually appears at the start of the next CU.
>
> I've had this patch kicking around for ages but I forget how I found
> the problem.
>
> gdb/ChangeLog
> 2020-02-15 Tom Tromey <tom@tromey.com>
>
> * dwarf2/read.c (dwarf2_find_containing_comp_unit): Use ">", not
> ">=", in binary search.
> ---
> gdb/ChangeLog | 5 +++++
> gdb/dwarf2/read.c | 2 +-
> 2 files changed, 6 insertions(+), 1 deletion(-)
>
> diff --git a/gdb/dwarf2/read.c b/gdb/dwarf2/read.c
> index e74383e01dc..e373cc0af2c 100644
> --- a/gdb/dwarf2/read.c
> +++ b/gdb/dwarf2/read.c
> @@ -24171,7 +24171,7 @@ dwarf2_find_containing_comp_unit (sect_offset sect_off,
> mid_cu = dwarf2_per_objfile->all_comp_units[mid];
> if (mid_cu->is_dwz > offset_in_dwz
> || (mid_cu->is_dwz == offset_in_dwz
> - && mid_cu->sect_off + mid_cu->length >= sect_off))
> + && mid_cu->sect_off + mid_cu->length > sect_off))
> high = mid;
> else
> low = mid + 1;

I can only convince myself of these things by plugging in real numbers. So let's say
mid_cu's range is [100,150[, so 150 bytes long, and we are looking for sect_off == 150.
150 is outside (just after) mid_cu's range, so the right answer will be the cu just
after this one.

Without your change, we would have gone in the "if", and therefore excluded the right
answer. With your change, we would have gone in the "else", and therefore chosen the
range with the right answer. So that looks correct to me.

I'm going to ask if you thought about a way to test this. I don't think writing a typical
test case for this is feasible. By refactoring the code a bit, we could maybe factor out the
meat of this function into one that operates on an std::vector<dwarf2_per_cu_data> instead
of on a dwarf2_per_objfile. It should then be feasible to create an std::vector with
dwarf2_per_cu_data elements out of thin air to unit-test the function, including edge
cases like this.

Also, do you understand what's the logic with this dwz stuff? Is it that all the CUs
coming from a dwz file are at the end of the list, or something like that?

Simon