Re: [RFC] how to get the size of a malloc(9) block ?

From: jb <jb.1234abcd_at_gmail.com>
Date: Thu, 28 Nov 2013 13:33:41 +0000 (UTC)
Luigi Rizzo <rizzo <at> iet.unipi.it> writes:

> 
> in porting some linux kernel code to FreeBSD we
> stumbled upon ksize(), which returns the
> actual size of a kmalloc() block.
> 
> We could easily implement it as the first part
> of realloc(9) -- see kern/kern_malloc.c
> 
> Would it make sense to add this to the malloc(9) API ?
> The userspace equivalent seems to be
> malloc_usable_size(3) which according to the
> manpage appeared in FreeBSD 7.0

Hi,

The implementation of ksize() depends on (has non-standard behavior across)
architectures, memory allocators, page sizes, C libs, etc.

It means, ksize() exports its implementation details to the caller, and this
disqualifies it, regardless whether in kernel or user spaces.

This leads to dangerous and conflicting assertions:

malloc_usable_size(3) on Linux:
NOTES
       The value returned by malloc_usable_size()  may  be  greater  than  the
       requested  size of the allocation because of alignment and minimum size
       constraints.  Although the excess  bytes  can  be  overwritten  by  the
       application without ill effects, this is not good programming practice:
       the number of excess bytes in an allocation depends on  the  underlying
       implementation.

       The main use of this function is for debugging and introspection.

Other sources:
...
The caller may use this additional memory, even though a smaller amount of
memory was initially specified with the kmalloc call.
...

This is hair-raising:
http://lwn.net/Articles/319686/

Result ? The same code works here, but may not elsewhere.
It follows, you should remove malloc_usable_size() from user space instead.

jb
Received on Thu Nov 28 2013 - 12:34:15 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:40:44 UTC