Re: [PATCH v2 1/3] Use unsigned ints in regcache_map_entry

Simon Marchi
2018-06-21T17:32:24Z

On 2018-06-21 11:34 AM, Simon Marchi wrote:
> On 2018-06-21 11:19 AM, Alan Hayward wrote:
>> I originally wrote this for just the _part functions and then I rejected
>> it. The problem as I see it with this is that, mostly all the code calling
>> these functions today are using ints.
>>
>> So, to keep it safe we should really update all the callers too. For example,
>> one picked at random:
>>
>> --- a/gdb/m32c-tdep.c
>> +++ b/gdb/m32c-tdep.c
>> @@ -443,9 +443,9 @@ m32c_find_part (struct m32c_reg *reg, int *offset_p, int *len_p)
>> bits, read the value of the REG->n'th element. */
>> static enum register_status
>> m32c_part_read (struct m32c_reg *reg, readable_regcache *cache, gdb_byte *buf)
>> {
>> - int offset, len;
>> + unsigned int offset, len;
>>
>> memset (buf, 0, TYPE_LENGTH (reg->type));
>> m32c_find_part (reg, &offset, &len);
>> return cache->cooked_read_part (reg->rx->num, offset, len, buf);
>>
>> And without checking, I’m not sure m32c_find_part can guarantee unsigned.
>>
>> Without those changes all we are doing is losing some assert protection.
>
> Fair enough, I'm fine with keeping the ints and the >= 0 asserts. It was just
> a tiny itch :).
>
> Simon
>

I thought about it a bit more, and we indeed probably need as many assertions
with unsigned types as we do with signed types, I was wrong thinking it would
simplify things.

Let's say a caller miscalculate "offset" and it ends up being -2 (0xfffffffe as an
unsigned int) and length is 4.
The assertion

gdb_assert (offset + len <= reg_size)

will not catch it, since (offset + len) will still be 2 (after the overflow). So
we would need to check that offset and len are within reg_size individually, as well
as their sum:

gdb_assert (offset <= reg_size);
gdb_assert (len <= reg_size);
gdb_assert (offset + len <= reg_size);

And that is equivalent to what we would need with signed types:

gdb_assert (offset >= 0);
gdb_assert (len >= 0);
gdb_assert (offset + len <= reg_size);

So in the end, I think you can forget changing things to unsigned, since it
doesn't really add value... sorry for the noise.

Simon