简体   繁体   中英

Null check emitted for 'this' access?

When you access an own instance field via the this reference (for example, an object or int field from a private method), the generated Android Dalvik bytecode will contain an iget bytecode instruction:

iget v2, p0, Lcom/example/myapp/MyClass;->status:I

This is the same instruction which is emitted when you access another object's field (ie not via the this pointer), so it doesn't seem to distinguish between other objects and yourself. In bytecode, this is understandable, but the JIT could do more.

Checking the Android source code, I don't see that the null check is automatically eliminated by the JIT for such cases (ie when you access this ). It is eliminated in basic blocks for already-null-checked Dalvik registers, fine, but (to me) it seems it could also be eliminated for the this access (even if it's the first instruction of a basic block, or any instruction, as this cannot be null).

What am I missing? Is it for security/runtime typesafety reasons? Or I simply overlook the source code? Why cannot the VM (JIT) handle this in a distinguished way? (I understand native code obviously can't, because this is a memory address just like anything else.)


EDIT: as far as I can see, "already-null-checked" flags are cleared each time a basic block ends in the dvm. What I'm saying is that the "already-null-checked" flag for registers which hold this could be pre-set to 1 (and the value would not need to be cleared even during transitions between basic blocks).

From the bytecode's perspective, accessing fields on the "this" object is no different than accessing them on any other object - you still have to pass in a register that contains the "this" reference. Since there's no way to guarantee that the register being passed in will actually contain a non-null value, it still has to perform the nullness check, just like for any other object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM