SystemYou are an expert SpongePowered Mixin internals developer. You understand how mixins work at the bytecode level using ASM, and can debug, write, and optimize mixins.
You are an expert SpongePowered Mixin internals developer. You understand how mixins work at the bytecode level using ASM, and can debug, write, and optimize mixins.
User
How does LocalCapture work? How are local variables from the target method captured and passed to mixin callbacks?
Assistant
LocalCapture captures the state of local variables at the injection point and passes them to the callback method.
Usage:
java
@Mixin(MyEntity.class)publicclassMyEntityMixin {
@Inject( method = "tick", at = @At(value = "INVOKE", target = "...", ordinal = 0), locals = LocalCapture.CAPTURE_FAILHARD )privatevoidonTick(CallbackInfo ci, int localHealth, float localSpeed) {
// localHealth and localSpeed are captured from the target method
System.out.println("Health: " + localHealth + ", Speed: " + localSpeed);
}
}
How it works at bytecode level:
java
// Target method bytecode before transformation:publicvoidtick() {
inthealth=this.getHealth(); // local variable at index 1floatspeed=this.getSpeed(); // local variable at index 2// ... more codethis.playSound(...);
// ... more code
}
The mixin processor reads the target method's LocalVariableNode table to determine variable slots:
java
// During mixin application:MethodNodetargetMethod= findTargetMethod(targetNode, "tick", "()V");
// Analyze local variables at injection point
List<LocalVariableNode> locals = targetMethod.localVariables;
// For @Inject at INVOKE ordinal=0, find the instructionAbstractInsnNodeinjectPoint= findInjectionPoint(targetMethod, ...);
// Determine which locals are live at this point
Map<Integer, Type> liveLocals = analyzeLiveness(targetMethod, injectPoint);
// Generate callback with captured locals as parametersMethodNodecallbackMethod= generateCallback(mixinMethod, liveLocals);
// Insert capture code before the callback invocationInsnListcapture=newInsnList();
for (Map.Entry<Integer, Type> entry : liveLocals.entrySet()) {
capture.add(newVarInsnNode(entry.getValue().getOpcode(ILOAD), entry.getKey()));
}
insertBefore(callbackInvocation, capture);
LocalCapture.CAPTURE_FAILHARD - fail if variables can't be captured
LocalCapture.CAPTURE_FAILSOFT - try to capture, skip if unable
The CAPTURE_FAILHARD mode is recommended because missing locals cause silent bugs. The mixin processor uses ASM's LocalVariablesSorter and frame analysis to determine which locals are in scope at the injection point.