dalvik/vm/oo/Object.h
是你的朋友吗?评论为struct Object
says:
/*
* There are three types of objects:
* Class objects - an instance of java.lang.Class
* Array objects - an object created with a "new array" instruction
* Data objects - an object that is neither of the above
*
* We also define String objects. At present they're equivalent to
* DataObject, but that may change. (Either way, they make some of the
* code more obvious.)
*
* All objects have an Object header followed by type-specific data.
*/
java.lang.Class
物体是特殊的;它们的布局是由ClassObject
结构体Object.h
。数组对象很简单:
struct ArrayObject : Object {
/* number of elements; immutable after init */
u4 length;
/*
* Array contents; actual size is (length * sizeof(type)). This is
* declared as u8 so that the compiler inserts any necessary padding
* (e.g. for EABI); the actual allocation may be smaller than 8 bytes.
*/
u8 contents[1];
};
对于数组,宽度为vm/oo/Array.cpp
。布尔值的宽度为 1,对象的宽度为sizeof(Object*)
长度(通常为 4),所有其他基本类型都有其预期(压缩)长度。
数据对象非常简单:
/*
* Data objects have an Object header followed by their instance data.
*/
struct DataObject : Object {
/* variable #of u4 slots; u8 uses 2 slots */
u4 instanceData[1];
};
的布局DataObject
(所有非 Class 类实例)受以下约束computeFieldOffsets
in vm/oo/Class.cpp
。根据那里的评论:
/*
* Assign instance fields to u4 slots.
*
* The top portion of the instance field area is occupied by the superclass
* fields, the bottom by the fields for this class.
*
* "long" and "double" fields occupy two adjacent slots. On some
* architectures, 64-bit quantities must be 64-bit aligned, so we need to
* arrange fields (or introduce padding) to ensure this. We assume the
* fields of the topmost superclass (i.e. Object) are 64-bit aligned, so
* we can just ensure that the offset is "even". To avoid wasting space,
* we want to move non-reference 32-bit fields into gaps rather than
* creating pad words.
*
* In the worst case we will waste 4 bytes, but because objects are
* allocated on >= 64-bit boundaries, those bytes may well be wasted anyway
* (assuming this is the most-derived class).
*
* Pad words are not represented in the field table, so the field table
* itself does not change size.
*
* The number of field slots determines the size of the object, so we
* set that here too.
*
* This function feels a little more complicated than I'd like, but it
* has the property of moving the smallest possible set of fields, which
* should reduce the time required to load a class.
*
* NOTE: reference fields *must* come first, or precacheReferenceOffsets()
* will break.
*/
因此,超类字段首先出现(像往常一样),然后是引用类型字段,最后是单个 32 位字段(如果可用,并且如果需要填充,因为有奇数个 32 位引用字段),然后是 64 - 位字段。接下来是常规 32 位字段。请注意,所有字段都是 32 位或 64 位(填充了较短的原语)。特别是,此时,VM 不会使用少于 4 个字节来存储字节/字符/短/布尔字段,尽管理论上它当然可以支持这一点。
请注意,所有这些都是基于阅读提交时的 Dalvik 源代码43241340
(2013 年 2 月 6 日)。由于虚拟机的这方面似乎没有公开记录,因此您不应依赖它作为虚拟机对象布局的稳定描述:它可能会随着时间的推移而改变。