浅析android中getStrongProxyForHandle函数动态申请handle索引对应的vector内存空间
class ProcessState : public virtual RefBase
{
...
struct handle_entry {
IBinder* binder;
RefBase::weakref_type* refs;
};
...
Vector<handle_entry>mHandleToObject;//从模板定义一个大小为sizeof(handle_entry)的Vector变量mHandleToObject
...
}
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
{
const size_t N=mHandleToObject.size();//开始N等于0
if (N <= (size_t)handle) {
handle_entry e;
e.binder = NULL;//初始化该handle索引对应的结构体struct handle_entry
e.refs = NULL;
status_t err = mHandleToObject.insertAt(e, N, handle+1-N);//在Vector的最后位置,动态生长该Vector类中成员
if (err < NO_ERROR) return NULL;
}
return &mHandleToObject.editItemAt(handle);//这样将返回handle作为索引,对应的空闲struct handle_entry结构体内存空间指针
}
include/utils/Vector.h
对Vector模板进行了定义:
template<class TYPE> inline
Vector<TYPE>::Vector()
: VectorImpl(sizeof(TYPE),
((traits<TYPE>::has_trivial_ctor ? HAS_TRIVIAL_CTOR : 0)
|(traits<TYPE>::has_trivial_dtor ? HAS_TRIVIAL_DTOR : 0)
|(traits<TYPE>::has_trivial_copy ? HAS_TRIVIAL_COPY : 0)
|(traits<TYPE>::has_trivial_assign ? HAS_TRIVIAL_ASSIGN : 0))
)
{
}
template<class TYPE> inline
ssize_t vector<TYPE>::insertAt(const TYPE& item, size_t index, size_t numItems) {
return vectorimpl::insertAt(&item, index, numItems);
}
ssize_t vectorimpl::insertAt(const void* item, size_t index, size_t numItems)
{
if (index > size())//最开始等于0,所以0 > 0将不成立
return BAD_INDEX;
void* where = _grow(index, numItems);//malloc内存空间
if (where) {
if (item) {
_do_splat(where, item, numItems);
} else {
_do_construct(where, numItems);
}
}
return where ? index : (ssize_t)NO_MEMORY;
}
template<class TYPE> inline
TYPE& Vector<TYPE>::editItemAt(size_t index) {
return *( static_cast<TYPE *>(editItemLocation(index)) );
}
void* VectorImpl::editItemLocation(size_t index)
{
LOG_ASSERT(index<capacity(),
"[%p] itemLocation: index=%d, capacity=%d, count=%d",
this, (int)index, (int)capacity(), (int)mCount);
void* buffer = editArrayImpl();
if (buffer)
return reinterpret_cast<char*>(buffer) + index*mItemSize;//返回index索引对应的buffer存储空间首指针
return 0;
}
|