Webkit Allocator

Apr212010

Webkit的Allocator使用的是来自google的大神Sanjay Ghemawat的,当然也可以在嵌入式
等系统中根据自己的需要使用custom allocator,webkit在google的allocator加入了类
openCV的allocate/free pair validation,在编译期间做为可选项目。从代码的注释可以
看到端倪:
// Malloc validation is a scheme whereby a tag is attached to an
// allocation which identifies how it was originally allocated.
// This allows us to verify that the freeing operation matches the
// allocation operation. If memory is allocated with operator new[]
// but freed with free or delete, this system would detect that.
// In the implementation here, the tag is an integer prepended to
// the allocation memory which is assigned one of the AllocType
// enumeration values. An alternative implementation of this
// scheme could store the tag somewhere else or ignore it.
// Users of FastMalloc don't need to know or care how this tagging
// is implemented.
再上一小段代码吧,具体在https://bugs.webkit.org/show_bug.cgi?id=20422
// This defines a type which holds an unsigned integer and is the same
// size as the minimally aligned memory allocation.
typedef unsigned long long AllocAlignmentInteger;

namespace Internal {

// Return the AllocType tag associated with the allocated block p.
inline AllocType fastMallocMatchValidationType(const void* p)
{
const AllocAlignmentInteger* type = static_cast(p) - 1;
return static_cast(*type);
}

// Return the address of the AllocType tag associated with the allocated block p.
inline AllocAlignmentInteger* fastMallocMatchValidationValue(void* p)
{
return reinterpret_cast(static_cast(p) - sizeof(AllocAlignmentInteger));
}

// Set the AllocType tag to be associaged with the allocated block p.
inline void setFastMallocMatchValidationType(void* p, AllocType allocType)
{
AllocAlignmentInteger* type = static_cast(p) - 1;
*type = static_cast(allocType);
}

// Handle a detected alloc/free mismatch. By default this calls CRASH().
void fastMallocMatchFailed(void* p);

} // namespace Internal

// This is a higher level function which is used by FastMalloc-using code.
inline void fastMallocMatchValidateMalloc(void* p, Internal::AllocType allocType)
{
if (!p)
return;

Internal::setFastMallocMatchValidationType(p, allocType);
}

// This is a higher level function which is used by FastMalloc-using code.
inline void fastMallocMatchValidateFree(void* p, Internal::AllocType allocType)
{
if (!p)
return;

if (Internal::fastMallocMatchValidationType(p) != allocType)
Internal::fastMallocMatchFailed(p);
Internal::setFastMallocMatchValidationType(p, Internal::AllocTypeMalloc); // Set it to this so that fastFree thinks it's OK.
}

#else

inline void fastMallocMatchValidateMalloc(void*, Internal::AllocType)
{
}

inline void fastMallocMatchValidateFree(void*, Internal::AllocType)
{
}

#endif