gpt4 book ai didi

android - 为什么 Dalvik Monitor 在 8 字节边界上对齐

转载 作者:搜寻专家 更新时间:2023-11-01 08:55:50 25 4
gpt4 key购买 nike

<code root>/dalvik/vm/Sync.cpp , 有一个 struct Monitor :

struct Monitor {
Thread* owner; /* which thread currently owns the lock? */
int lockCount; /* owner's recursive lock depth */
Object* obj; /* what object are we part of [debug only] */

Thread* waitSet; /* threads currently waiting on this monitor */

pthread_mutex_t lock;

Monitor* next;

/*
* Who last acquired this monitor, when lock sampling is enabled.
* Even when enabled, ownerMethod may be NULL.
*/
const Method* ownerMethod;
u4 ownerPc;
};

我不明白为什么Monitor对齐 8 个字节。我认为它应该对齐 4 个字节,因为其中的所有成员(即指针、intpthread_mutex_t)的长度都是 4 个字节。

最佳答案

问题没有明确显示,但通过 8 字节对齐,您可能指的是 code 的这一部分, 使用 Misaligned monitor 检查:

Monitor* dvmCreateMonitor(Object* obj)
{
Monitor* mon;
mon = (Monitor*) calloc(1, sizeof(Monitor));
if (mon == NULL) {
ALOGE("Unable to allocate monitor");
dvmAbort();
}
if (((u4)mon & 7) != 0) {
ALOGE("Misaligned monitor: %p", mon);
dvmAbort();
}

原因是Dalvik使用了瘦锁。锁是对象的 32 位值,低 3 位用于编码锁状态:一位用于瘦/胖锁状态,两位用于哈希状态。指向 Monitor 本身的指针只剩下 29 位。

来自同一个source :

The lock value itself is stored in Object.lock. The LSB of the lock encodes its state. When cleared, the lock is in the "thin" state and its bits are formatted as follows:

[31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
lock count thread id hash state 0

When set, the lock is in the "fat" state and its bits are formatted as follows:

 [31 ---- 3] [2 ---- 1] [0]
pointer hash state 1

作为引用,这里是描述薄锁定的论文:Thin Locks: Featherweight Synchronization for Java

在评论中,您询问对齐是如何完成的。 C 标准只要求分配器返回一个可用于任何类型分配的地址。来自 C99 §7.20.3(内存管理功能):

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).

默认情况下,32 位 ARM 系统上的 malloc/calloc/realloc 返回 8 字节对齐的 block 。我相信 Misaligned monitor 检查是作为防御性代码快速失败的,以防分配器被替换为不返回 8 字节对齐 block 的版本。

关于android - 为什么 Dalvik Monitor 在 8 字节边界上对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19022663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com