[PATCH 06/11] Sptr: avoided potentially undefined behaviour.

Alejandro Colomar alx.manpages at gmail.com
Fri Jun 17 23:15:46 UTC 2022


Hi Max

On 6/18/22 01:04, Max Romanov wrote:
> I'm sorry to be a pain,

No problem :)

  but the key thing is: ".. read from another
> object..".

In this case, ISO C uses the term object to refer to a broader concept, 
that includes any variable.

3.15/1,2:
"
object
region of data storage in the execution environment, the contents of 
which can represent values
"

> In the statement you are trying to "fix", the "base" does not 
> actually _read_ from the object (structure, to be precise), instead the 
> address of the structure itself used. In other words, "p->base" is a 
> shortcut for "(uint8_t *) p".

the region of data storage pointed to by `p->base` would be an object 
(of type uint8_t, or maybe uint8_t[]).

But the pointer itself does constitute another separate object.  And 
that object is the one that is stored in the union (the uint8_t data is 
not stored in the union, but in some other allocated memory (probably)).

Since we are reading a member of the union (and each member is an 
object, by definition, even if it's a pointer), and storing the value 
into another member of the union, that's not valid.

As pointed by @supercat in StackOverflow (in the link I provided), the 
rationale was probably to allow compilers to do some optimizations, or 
for example, copy byte by byte; in archs where the union members are 
larger than a register, this will definitely cause a bug; in archs where 
the union members fit into a register (as in our case), the code is 
likely to work, but the standard makes no guarantees about it, and a 
compiler may still do bad stuff.  It's better to be safe.

Cheers,

Alex
>> <https://stackoverflow.com/a/72652427/6872717 
-- 
Alejandro Colomar
<http://www.alejandro-colomar.es/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature
Type: application/pgp-signature
Size: 833 bytes
Desc: OpenPGP digital signature
URL: <http://mailman.nginx.org/pipermail/unit/attachments/20220618/e39c94f2/attachment.bin>


More information about the unit mailing list