Skip to content

Commit

Permalink
8329581: Java launcher no longer prints a stack trace
Browse files Browse the repository at this point in the history
8329420: Java 22 (and 23) launcher calls default constructor although main() is static
8330864: No error message when ExceptionInInitializerError thrown in static initializer

Reviewed-by: stuefe
  • Loading branch information
Sonia Zaldana Calles authored and jaikiran committed Jun 5, 2024
1 parent 789f704 commit cbb6747
Show file tree
Hide file tree
Showing 4 changed files with 341 additions and 42 deletions.
11 changes: 7 additions & 4 deletions src/java.base/share/classes/sun/launcher/LauncherHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,9 @@ private static boolean doesExtendFXApplication(Class<?> mainClass) {
return false;
}

private static boolean isStaticMain = false;
private static boolean noArgMain = false;

// Check the existence and signature of main and abort if incorrect.
private static void validateMainMethod(Class<?> mainClass) {
Method mainMethod = null;
Expand All @@ -927,19 +930,19 @@ private static void validateMainMethod(Class<?> mainClass) {
}

int mods = mainMethod.getModifiers();
boolean isStatic = Modifier.isStatic(mods);
isStaticMain = Modifier.isStatic(mods);
boolean isPublic = Modifier.isPublic(mods);
boolean noArgs = mainMethod.getParameterCount() == 0;
noArgMain = mainMethod.getParameterCount() == 0;

if (!PreviewFeatures.isEnabled()) {
if (!isStatic || !isPublic || noArgs) {
if (!isStaticMain || !isPublic || noArgMain) {
abort(null, "java.launcher.cls.error2", mainClass.getName(),
JAVAFX_APPLICATION_CLASS_NAME);
}
return;
}

if (!isStatic) {
if (!isStaticMain) {
String className = mainMethod.getDeclaringClass().getName();
if (mainClass.isMemberClass() && !Modifier.isStatic(mainClass.getModifiers())) {
abort(null, "java.launcher.cls.error7", className);
Expand Down
68 changes: 41 additions & 27 deletions src/java.base/share/native/libjli/java.c
Original file line number Diff line number Diff line change
Expand Up @@ -387,21 +387,11 @@ JLI_Launch(int argc, char ** argv, /* main argc, argv */
} \
} while (JNI_FALSE)

#define CHECK_EXCEPTION_FAIL() \
#define CHECK_EXCEPTION_NULL_FAIL(obj) \
do { \
if ((*env)->ExceptionOccurred(env)) { \
(*env)->ExceptionClear(env); \
return 0; \
} \
} while (JNI_FALSE)


#define CHECK_EXCEPTION_NULL_FAIL(mainObject) \
do { \
if ((*env)->ExceptionOccurred(env)) { \
(*env)->ExceptionClear(env); \
return 0; \
} else if (mainObject == NULL) { \
} else if (obj == NULL) { \
return 0; \
} \
} while (JNI_FALSE)
Expand All @@ -414,7 +404,7 @@ int
invokeStaticMainWithArgs(JNIEnv *env, jclass mainClass, jobjectArray mainArgs) {
jmethodID mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
"([Ljava/lang/String;)V");
CHECK_EXCEPTION_FAIL();
CHECK_EXCEPTION_NULL_FAIL(mainID);
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
return 1;
}
Expand All @@ -426,15 +416,15 @@ invokeStaticMainWithArgs(JNIEnv *env, jclass mainClass, jobjectArray mainArgs) {
int
invokeInstanceMainWithArgs(JNIEnv *env, jclass mainClass, jobjectArray mainArgs) {
jmethodID constructor = (*env)->GetMethodID(env, mainClass, "<init>", "()V");
CHECK_EXCEPTION_FAIL();
CHECK_EXCEPTION_NULL_FAIL(constructor);
jobject mainObject = (*env)->NewObject(env, mainClass, constructor);
CHECK_EXCEPTION_NULL_FAIL(mainObject);
jmethodID mainID = (*env)->GetMethodID(env, mainClass, "main",
"([Ljava/lang/String;)V");
CHECK_EXCEPTION_FAIL();
jmethodID mainID =
(*env)->GetMethodID(env, mainClass, "main", "([Ljava/lang/String;)V");
CHECK_EXCEPTION_NULL_FAIL(mainID);
(*env)->CallVoidMethod(env, mainObject, mainID, mainArgs);
return 1;
}
}

/*
* Invoke a static main without arguments. Returns 1 (true) if successful otherwise
Expand All @@ -444,7 +434,7 @@ int
invokeStaticMainWithoutArgs(JNIEnv *env, jclass mainClass) {
jmethodID mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
"()V");
CHECK_EXCEPTION_FAIL();
CHECK_EXCEPTION_NULL_FAIL(mainID);
(*env)->CallStaticVoidMethod(env, mainClass, mainID);
return 1;
}
Expand All @@ -456,12 +446,12 @@ invokeStaticMainWithoutArgs(JNIEnv *env, jclass mainClass) {
int
invokeInstanceMainWithoutArgs(JNIEnv *env, jclass mainClass) {
jmethodID constructor = (*env)->GetMethodID(env, mainClass, "<init>", "()V");
CHECK_EXCEPTION_FAIL();
CHECK_EXCEPTION_NULL_FAIL(constructor);
jobject mainObject = (*env)->NewObject(env, mainClass, constructor);
CHECK_EXCEPTION_NULL_FAIL(mainObject);
jmethodID mainID = (*env)->GetMethodID(env, mainClass, "main",
"()V");
CHECK_EXCEPTION_FAIL();
CHECK_EXCEPTION_NULL_FAIL(mainID);
(*env)->CallVoidMethod(env, mainObject, mainID);
return 1;
}
Expand All @@ -483,6 +473,11 @@ JavaMain(void* _args)
jobjectArray mainArgs;
int ret = 0;
jlong start = 0, end = 0;
jclass helperClass;
jfieldID isStaticMainField;
jboolean isStaticMain;
jfieldID noArgMainField;
jboolean noArgMain;

RegisterThread();

Expand Down Expand Up @@ -620,12 +615,31 @@ JavaMain(void* _args)
* The main method is invoked here so that extraneous java stacks are not in
* the application stack trace.
*/
if (!invokeStaticMainWithArgs(env, mainClass, mainArgs) &&
!invokeInstanceMainWithArgs(env, mainClass, mainArgs) &&
!invokeStaticMainWithoutArgs(env, mainClass) &&
!invokeInstanceMainWithoutArgs(env, mainClass)) {
ret = 1;
LEAVE();

helperClass = GetLauncherHelperClass(env);
isStaticMainField = (*env)->GetStaticFieldID(env, helperClass, "isStaticMain", "Z");
CHECK_EXCEPTION_NULL_LEAVE(isStaticMainField);
isStaticMain = (*env)->GetStaticBooleanField(env, helperClass, isStaticMainField);

noArgMainField = (*env)->GetStaticFieldID(env, helperClass, "noArgMain", "Z");
CHECK_EXCEPTION_NULL_LEAVE(noArgMainField);
noArgMain = (*env)->GetStaticBooleanField(env, helperClass, noArgMainField);

if (isStaticMain) {
if (noArgMain) {
ret = invokeStaticMainWithoutArgs(env, mainClass);
} else {
ret = invokeStaticMainWithArgs(env, mainClass, mainArgs);
}
} else {
if (noArgMain) {
ret = invokeInstanceMainWithoutArgs(env, mainClass);
} else {
ret = invokeInstanceMainWithArgs(env, mainClass, mainArgs);
}
}
if (!ret) {
CHECK_EXCEPTION_LEAVE(1);
}

/*
Expand Down
201 changes: 190 additions & 11 deletions test/jdk/tools/launcher/InstanceMainTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand All @@ -22,10 +22,14 @@
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
* @test
* @summary test execution priority of main methods
* @bug 8329420
* @summary test execution priority and behavior of main methods
* @run main InstanceMainTest
*/
public class InstanceMainTest extends TestHelper {
Expand Down Expand Up @@ -175,16 +179,191 @@ static void main() {
"""
};

public static void main(String... args) throws Exception {
private static void testMethodOrder() throws Exception {
for (String source : SOURCES) {
Files.writeString(Path.of("MainClass.java"), source);
var version = System.getProperty("java.specification.version");
var tr = doExec(javaCmd, "--enable-preview", "--source", version, "MainClass.java");
if (!tr.isOK()) {
System.err.println(source);
System.err.println(tr);
throw new AssertionError();
}
performTest(source, true, tr -> {
if (!tr.isOK()) {
System.err.println(source);
System.err.println(tr);
throw new AssertionError();
}
});
}
}

record TestCase(String sourceCode, boolean enablePreview, List<String> expectedOutput) {

public TestCase(String sourceCode, List<String> expectedOutput) {
this(sourceCode, true, expectedOutput);
}

}

private static final TestCase[] EXECUTION_ORDER = new TestCase[] {
new TestCase("""
public class MainClass {
public MainClass() {
System.out.println("Constructor called!");
}
public static void main() {
System.out.println("main called!");
}
}
""",
List.of("main called!")),
new TestCase("""
public class MainClass {
public MainClass() {
System.out.println("Constructor called!");
}
public void main() {
System.out.println("main called!");
}
}
""",
List.of("Constructor called!", "main called!"))
};

private static void testExecutionOrder() throws Exception {
for (TestCase testCase : EXECUTION_ORDER) {
performTest(testCase.sourceCode, testCase.enablePreview(), tr -> {
if (!Objects.equals(testCase.expectedOutput, tr.testOutput)) {
throw new AssertionError("Unexpected output, " +
"expected: " + testCase.expectedOutput +
", actual: " + tr.testOutput);
}
});
}
}

private static final TestCase[] EXECUTION_ERRORS = new TestCase[] {
new TestCase("""
public class MainClass {
public MainClass() {
System.out.println("Constructor called!");
if (true) throw new Error();
}
public void main(String... args) {
System.out.println("main called!");
}
}
""",
List.of("Constructor called!",
"Exception in thread \"main\" java.lang.Error",
"\tat MainClass.<init>(MainClass.java:4)")),
new TestCase("""
public class MainClass {
public MainClass() {
System.out.println("Constructor called!");
if (true) throw new Error();
}
public void main() {
System.out.println("main called!");
}
}
""",
List.of("Constructor called!",
"Exception in thread \"main\" java.lang.Error",
"\tat MainClass.<init>(MainClass.java:4)")),
new TestCase("""
public class MainClass {
static int idx;
public MainClass() {
System.out.println("Constructor called!");
if (idx++ == 0) throw new Error();
}
public void main(String... args) {
System.out.println("main called!");
}
public void main() {
System.out.println("main called!");
}
}
""",
List.of("Constructor called!",
"Exception in thread \"main\" java.lang.Error",
"\tat MainClass.<init>(MainClass.java:5)")),
new TestCase("""
public class MainClass {
static {
System.out.println("static init called!");
if (true) throw new Error();
}
public static void main(String... args) {
System.out.println("main called!");
}
}
""",
false,
List.of("static init called!",
"Exception in thread \"main\" java.lang.Error",
"\tat MainClass.<clinit>(MainClass.java:4)")),
new TestCase("""
public class MainClass {
static {
System.out.println("static init called!");
if (true) throw new Error();
}
public static void main(String... args) {
System.out.println("main called!");
}
}
""",
true,
List.of("static init called!",
"Exception in thread \"main\" java.lang.Error",
"\tat MainClass.<clinit>(MainClass.java:4)")),
new TestCase("""
public class MainClass {
static {
System.out.println("static init called!");
if (true) throw new Error();
}
public void main(String... args) {
System.out.println("main called!");
}
}
""",
true,
List.of("static init called!",
"Exception in thread \"main\" java.lang.Error",
"\tat MainClass.<clinit>(MainClass.java:4)")),
};

private static void testExecutionErrors() throws Exception {
for (TestCase testCase : EXECUTION_ERRORS) {
performTest(testCase.sourceCode, testCase.enablePreview(), tr -> {
for (int i = 0; i < testCase.expectedOutput.size(); i++) {
if (i >= tr.testOutput.size() ||
!Objects.equals(testCase.expectedOutput.get(i),
tr.testOutput.get(i))) {
throw new AssertionError("Unexpected output, " +
"expected: " + testCase.expectedOutput +
", actual: " + tr.testOutput +
", failed comparison at index: " + i);
}
}
});
}
}

private static void performTest(String source, boolean enablePreview, Consumer<TestResult> validator) throws Exception {
Path mainClass = Path.of("MainClass.java");
Files.writeString(mainClass, source);
var version = System.getProperty("java.specification.version");
var previewRuntime = enablePreview ? "--enable-preview" : "-DtestNoPreview";
var previewCompile = enablePreview ? "--enable-preview" : "-XDtestNoPreview";
var trSource = doExec(javaCmd, previewRuntime, "--source", version, "MainClass.java");
validator.accept(trSource);
compile(previewCompile, "--source", version, "MainClass.java");
String cp = mainClass.toAbsolutePath().getParent().toString();
var trCompile = doExec(javaCmd, previewRuntime, "--class-path", cp, "MainClass");
validator.accept(trCompile);
}

public static void main(String... args) throws Exception {
testMethodOrder();
testExecutionOrder();
testExecutionErrors();
}
}
Loading

1 comment on commit cbb6747

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.