> On Jul 31, 2023, at 2:23 PM, Siddhesh Poyarekar <siddh...@gotplt.org> wrote:
> 
> On 2023-07-31 14:13, Qing Zhao wrote:
>> Okay. I see.
>> Then if the size info from the TYPE is smaller than the size info from the 
>> malloc,
>>  then based on the current code, we use the smaller one between these two,
>>  i.e, the size info from the TYPE.  (Even for the OST_MAXIMUM).
>> Is such behavior correct?
> 
> Yes, it's correct even for OST_MAXIMUM.  The smaller one between the two is 
> the more precise estimate, which is why the mode doesn't matter.
> 
>> This is for the new “counted_by” attribute and how to use it in 
>> __builtin_dynamic_object_size.
>> for example:
>> =======
>> struct annotated {
>>         size_t foo;
>>         int array[] __attribute__((counted_by (foo)));
>> };
>> #define noinline __attribute__((__noinline__))
>> #define SIZE_BUMP 2
>> /* in the following function, malloc allocated more space than the value
>>    of counted_by attribute.  Then what's the correct behavior we expect
>>    the __builtin_dynamic_object_size should have?  */
>> static struct annotated * noinline alloc_buf (int index)
>> {
>>   struct annotated *p;
>>   p = malloc(sizeof (*p) + (index + SIZE_BUMP) * sizeof (int));
>>   p->foo = index;
>>   /*when checking the observed access p->array, we have info on both
>>     observered allocation and observed access,
>>     A. from observed allocation: (index + SIZE_BUMP) * sizeof (int)
>>     B. from observed access: p->foo * sizeof (int)
>>     in the above, p->foo = index.
>>    */
>>   /* for MAXIMUM size, based on the current code, we will use the size info 
>> from the TYPE,
>>      i.e, the “counted_by” attribute, which is the smaller one.   */
>>   expect(__builtin_dynamic_object_size(p->array, 1), (p->foo) * sizeof(int));
> 
> If the counted_by is less than what is allocated, it is the more correct 
> value to return because that's what the application asked for through the 
> attribute.  If the allocated size is less, we return the allocated size 
> because in that case, despite what the application said, the actual allocated 
> size is less and hence that's the safer value.

Thanks a lot for the clear explanation. This makes good sense.
> 
> In fact in the latter case it may even make sense to emit a warning because 
> it is more likely than not to be a bug.

Agreed. 

Here is a patch from Martin on a new similar warning (-Walloc-type):  
https://gcc.gnu.org/pipermail/gcc-patches/2023-July/625172.html. 

I guess that I will also need to issue warning for such cases for the new 
attribute “counted_by”.

Qing

> Thanks,
> Sid

Reply via email to