Skip to content

C: Method initialization issue #1140

@xpenatan

Description

@xpenatan

While working on a PSP 3D cube rendering port, I noticed strange behavior with some constants. After simplifying the code, I found a reproducible case.

It appears that static final fields whose initializer calls a Java method can be incorrectly initialized to 0 if a native method from the same class is called very early (e.g. before any other code in main).

Minimal Reproducible Example

// MethodInitTest.java
@Include("MethodInitTest.h")
public class MethodInitTest {

    public static int GU_COLOR_SHIFT(int n) {
        return n << 2;
    }

    // This field is initialized by calling a method in the same class
    public static final int GU_COLOR_8888 = GU_COLOR_SHIFT(7);   // should be 28

    @Import(name = "testMethod")
    public static native void testMethod();
}
// MethodInitTest.h
#pragma once

void testMethod() {
    // empty for this test
}
public class TestCLauncher {

    public static void main(String[] args) {
        MethodInitTest.testMethod();
        System.out.println("GU_COLOR_8888: " + MethodInitTest.GU_COLOR_8888);
    }
}

When you call testMethod() first → GU_COLOR_8888 prints 0
When you do NOT call testMethod() → GU_COLOR_8888 prints 28 (correct)
When testMethod() is moved to another class (e.g. NativeUtils.testMethod()), the constant works and return 28.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions