Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support agent by attaching it at build time #9668

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions substratevm/mx.substratevm/mx_substratevm.py
Original file line number Diff line number Diff line change
Expand Up @@ -1736,10 +1736,15 @@ def cinterfacetutorial(args):
@mx.command(suite.name, 'javaagenttest', 'Runs tests for java agent with native image')
def java_agent_test(args):
def build_and_run(args, binary_path, native_image, agents, agents_arg):
test_cp = os.pathsep.join([classpath('com.oracle.svm.test')] + agents)
mx.log('Run agent with JVM as baseline')
test_cp = os.pathsep.join([classpath('com.oracle.svm.test')])
java_run_cp = os.pathsep.join([test_cp, mx.dependency('org.graalvm.nativeimage').classpath_repr()])
mx.run_java( agents_arg + ['--add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED',
'-cp', java_run_cp, 'com.oracle.svm.test.javaagent.AgentTest'])
test_cp = os.pathsep.join([test_cp] + agents)
native_agent_premain_options = ['-XXpremain:com.oracle.svm.test.javaagent.agent1.TestJavaAgent1:test.agent1=true', '-XXpremain:com.oracle.svm.test.javaagent.agent2.TestJavaAgent2:test.agent2=true']
image_args = ['-cp', test_cp, '-J-ea', '-J-esa', '-H:+ReportExceptionStackTraces', '-H:Class=com.oracle.svm.test.javaagent.AgentTest']
native_image(image_args + svm_experimental_options(['-H:PremainClasses=' + agents_arg]) + ['-o', binary_path] + args)
image_args = ['-cp', test_cp, '-J-ea', '-J-esa', '-H:+ReportExceptionStackTraces', '-J--add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED', '-H:Class=com.oracle.svm.test.javaagent.AgentTest']
Copy link
Member

Choose a reason for hiding this comment

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

Why do we need -J--add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I transformed class in test agent with ASM.

native_image(image_args + svm_experimental_options(agents_arg) + ['-o', binary_path] + args)
mx.run([binary_path] + native_agent_premain_options)

def build_and_test_java_agent_image(native_image, args):
Expand All @@ -1756,18 +1761,23 @@ def build_and_test_java_agent_image(native_image, args):
# Note: we are not using MX here to avoid polluting the suite.py and requiring extra build flags
mx.log("Building agent jars from " + test_classpath)
agents = []
for i in range(1, 2):
for i in range(1, 3):
Copy link
Member

Choose a reason for hiding this comment

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

I don't see the agent3 in the PR? Is it committed?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

python's range(x, y) includes x but excludes y.

agent = join(tmp_dir, "testagent%d.jar" % (i))
agent_test_classpath = join(test_classpath, 'com', 'oracle', 'svm', 'test', 'javaagent', 'agent' + str(i))
class_list = [join(test_classpath, 'com', 'oracle', 'svm', 'test', 'javaagent', 'agent' + str(i), f) for f in os.listdir(agent_test_classpath) if os.path.isfile(os.path.join(agent_test_classpath, f)) and f.endswith(".class")]
mx.run([mx.get_jdk().jar, 'cmf', join(test_classpath, 'resources', 'javaagent' + str(i), 'MANIFEST.MF'), agent] + class_list, cwd = tmp_dir)
current_dir = os.getcwd()
# Change to test classpath to create agent jar file
os.chdir(test_classpath)
Copy link
Member

Choose a reason for hiding this comment

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

Why do we need to change the dir?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Running jar cmf xxx.jar package/SomeClass.class to pack a jar file requires changing working directory to the root of class package path.

agent_test_classpath = join('com', 'oracle', 'svm', 'test', 'javaagent', 'agent' + str(i))
class_list = [join('com', 'oracle', 'svm', 'test', 'javaagent', 'agent' + str(i), f) for f in os.listdir(agent_test_classpath) if os.path.isfile(os.path.join(agent_test_classpath, f)) and f.endswith(".class")]
class_list.append(join('com', 'oracle', 'svm', 'test', 'javaagent', 'AgentPremainHelper.class'))
mx.run([mx.get_jdk().jar, 'cmf', join(test_classpath, 'resources', 'javaagent' + str(i), 'MANIFEST.MF'), agent] + class_list, cwd = test_classpath)
agents.append(agent)
os.chdir(current_dir)

mx.log("Building images with different agent orders ")
build_and_run(args, join(tmp_dir, 'agenttest1'), native_image, agents,'com.oracle.svm.test.javaagent.agent1.TestJavaAgent1,com.oracle.svm.test.javaagent.agent2.TestJavaAgent2')
build_and_run(args, join(tmp_dir, 'agenttest1'), native_image, agents,[f'-javaagent:{agents[0]}=test.agent1=true', f'-javaagent:{agents[1]}=test.agent2=true'])

# Switch the premain sequence of agent1 and agent2
build_and_run(args, join(tmp_dir, 'agenttest2'), native_image, agents, 'com.oracle.svm.test.javaagent.agent2.TestJavaAgent2,com.oracle.svm.test.javaagent.agent1.TestJavaAgent1')
build_and_run(args, join(tmp_dir, 'agenttest2'), native_image, agents, [f'-javaagent:{agents[1]}=test.agent2=true', f'-javaagent:{agents[0]}=test.agent1=true'])

native_image_context_run(build_and_test_java_agent_image, args)

Expand Down
1 change: 1 addition & 0 deletions substratevm/mx.substratevm/suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,7 @@
"java.base" : [
"jdk.internal.misc",
"sun.security.jca",
"jdk.internal.org.objectweb.asm"
],
},
"checkstyle": "com.oracle.svm.test",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,11 @@ public boolean isClosedTypeWorld() {
return true;
}

@SuppressWarnings("unused")
Copy link
Member

Choose a reason for hiding this comment

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

Please use the following instead:
public boolean isFromJavaAgent(@SuppressWarnings("unused") Class<?> clazz) {

public boolean isFromJavaAgent(Class<?> clazz) {
return false;
}

/**
* Helpers to determine what analysis actions should be taken for a given Multi-Method version.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@

import static jdk.vm.ci.common.JVMCIError.unimplemented;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.oracle.graal.pointsto.constraints.UnresolvedElementException;
import com.oracle.graal.pointsto.meta.AnalysisUniverse;
import com.oracle.graal.pointsto.util.GraalAccess;

import jdk.graal.compiler.api.replacements.SnippetReflectionProvider;
Expand All @@ -41,6 +43,7 @@
import jdk.vm.ci.meta.JavaType;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.meta.ResolvedJavaType;
import jdk.vm.ci.meta.UnresolvedJavaMethod;

public class WrappedConstantPool implements ConstantPool, ConstantPoolPatch {

Expand Down Expand Up @@ -117,7 +120,26 @@ public JavaMethod lookupMethod(int cpi, int opcode) {
@Override
public JavaMethod lookupMethod(int cpi, int opcode, ResolvedJavaMethod caller) {
try {
return universe.lookupAllowUnresolved(wrapped.lookupMethod(cpi, opcode, OriginalMethodProvider.getOriginalMethod(caller)));
JavaMethod ret = universe.lookupAllowUnresolved(wrapped.lookupMethod(cpi, opcode, OriginalMethodProvider.getOriginalMethod(caller)));
Copy link
Member

@vjovanov vjovanov Sep 12, 2024

Choose a reason for hiding this comment

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

For which classes does this happen? Can you provide a concrete example?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 has dependency on org.junit.Assert.

At build time, TestJavaAgent1 is loaded by appClassloader as part of java agent, while org.junit.Assert is loaded by NativeImageClassloader because its jar is specified by -cp. Therefore, appClassloader:TestJavaAgent1 depends on NativeImageClassloader:Assert. The following error is thrown during building:

Error: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.

Error encountered while parsing com.oracle.svm.test.javaagent.agent1.TestJavaAgent1.premain(TestJavaAgent1.java:48)
Parsing context:
   at static root method.(Unknown Source)

Detailed message:

Caused by: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.
Error encountered while parsing com.oracle.svm.test.javaagent.agent1.TestJavaAgent1.premain(TestJavaAgent1.java:48)
Parsing context:
   at static root method.(Unknown Source)

Detailed message:

        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.constraints.UnsupportedFeatures.report(UnsupportedFeatures.java:126)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:867)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:593)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:555)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:544)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:731)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.start(NativeImageGeneratorRunner.java:151)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:99)
Caused by: com.oracle.graal.pointsto.constraints.UnresolvedElementException: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.reportUnresolvedElement(SharedGraphBuilderPhase.java:604)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.reportUnresolvedElement(SharedGraphBuilderPhase.java:598)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedType(SharedGraphBuilderPhase.java:490)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedMethod(SharedGraphBuilderPhase.java:518)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedInvoke(SharedGraphBuilderPhase.java:411)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.genInvokeStatic(BytecodeParser.java:1864)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.genInvokeStatic(BytecodeParser.java:1843)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.processBytecode(BytecodeParser.java:5807)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.iterateBytecodesForBlock(BytecodeParser.java:3769)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.iterateBytecodesForBlock(SharedGraphBuilderPhase.java:954)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.handleBytecodeBlock(BytecodeParser.java:3729)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.processBlock(BytecodeParser.java:3576)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.build(BytecodeParser.java:1162)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.build(SharedGraphBuilderPhase.java:205)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.buildRootMethod(BytecodeParser.java:1054)
        at jdk.graal.compiler/jdk.graal.compiler.java.GraphBuilderPhase$Instance.run(GraphBuilderPhase.java:103)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase.run(SharedGraphBuilderPhase.java:157)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.run(Phase.java:49)
        at jdk.graal.compiler/jdk.graal.compiler.phases.BasePhase.apply(BasePhase.java:468)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.apply(Phase.java:42)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.apply(Phase.java:38)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.AnalysisParsedGraph.parseBytecode(AnalysisParsedGraph.java:144)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.lambda$parseGraph$5(AnalysisMethod.java:986)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.setGraph(AnalysisMethod.java:1002)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.parseGraph(AnalysisMethod.java:986)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.ensureGraphParsedHelper(AnalysisMethod.java:958)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.ensureGraphParsed(AnalysisMethod.java:937)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.parse(MethodTypeFlowBuilder.java:190)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.apply(MethodTypeFlowBuilder.java:658)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.createFlowsGraph(MethodTypeFlow.java:167)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.ensureFlowsGraphCreated(MethodTypeFlow.java:152)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.getOrCreateMethodFlowsGraphInfo(MethodTypeFlow.java:110)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.typestate.DefaultAnalysisPolicy.staticRootMethodGraph(DefaultAnalysisPolicy.java:208)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.PointsToAnalysis.lambda$addRootMethod$1(PointsToAnalysis.java:339)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.AbstractAnalysisEngine$1.run(AbstractAnalysisEngine.java:338)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.util.CompletionExecutor.executeCommand(CompletionExecutor.java:166)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.util.CompletionExecutor.lambda$executeService$0(CompletionExecutor.java:152)
        at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1423)
        at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387)
        at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1312)
        at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1843)
        at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1808)
        at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:188)
Caused by: com.oracle.graal.pointsto.constraints.UnresolvedElementException: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.reportUnresolvedElement(SharedGraphBuilderPhase.java:604)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.reportUnresolvedElement(SharedGraphBuilderPhase.java:598)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedType(SharedGraphBuilderPhase.java:490)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedMethod(SharedGraphBuilderPhase.java:518)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedInvoke(SharedGraphBuilderPhase.java:411)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.genInvokeStatic(BytecodeParser.java:1864)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.genInvokeStatic(BytecodeParser.java:1843)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.processBytecode(BytecodeParser.java:5807)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.iterateBytecodesForBlock(BytecodeParser.java:3769)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.iterateBytecodesForBlock(SharedGraphBuilderPhase.java:954)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.handleBytecodeBlock(BytecodeParser.java:3729)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.processBlock(BytecodeParser.java:3576)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.build(BytecodeParser.java:1162)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.build(SharedGraphBuilderPhase.java:205)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.buildRootMethod(BytecodeParser.java:1054)
        at jdk.graal.compiler/jdk.graal.compiler.java.GraphBuilderPhase$Instance.run(GraphBuilderPhase.java:103)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase.run(SharedGraphBuilderPhase.java:157)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.run(Phase.java:49)
        at jdk.graal.compiler/jdk.graal.compiler.phases.BasePhase.apply(BasePhase.java:468)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.apply(Phase.java:42)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.apply(Phase.java:38)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.AnalysisParsedGraph.parseBytecode(AnalysisParsedGraph.java:144)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.lambda$parseGraph$5(AnalysisMethod.java:986)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.setGraph(AnalysisMethod.java:1002)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.parseGraph(AnalysisMethod.java:986)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.ensureGraphParsedHelper(AnalysisMethod.java:958)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.ensureGraphParsed(AnalysisMethod.java:937)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.parse(MethodTypeFlowBuilder.java:190)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.apply(MethodTypeFlowBuilder.java:658)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.createFlowsGraph(MethodTypeFlow.java:167)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.ensureFlowsGraphCreated(MethodTypeFlow.java:152)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.getOrCreateMethodFlowsGraphInfo(MethodTypeFlow.java:110)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.typestate.DefaultAnalysisPolicy.staticRootMethodGraph(DefaultAnalysisPolicy.java:208)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.PointsToAnalysis.lambda$addRootMethod$1(PointsToAnalysis.java:339)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.AbstractAnalysisEngine$1.run(AbstractAnalysisEngine.java:338)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.util.CompletionExecutor.executeCommand(CompletionExecutor.java:166)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.util.CompletionExecutor.lambda$executeService$0(CompletionExecutor.java:152)
        at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1423)
        at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387)
        at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1312)
        at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1843)
        at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1808)
        at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:188)
Internal exception: com.oracle.svm.core.util.UserError$UserException: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.
Error encountered while parsing com.oracle.svm.test.javaagent.agent1.TestJavaAgent1.premain(TestJavaAgent1.java:48)
Parsing context:
   at static root method.(Unknown Source)

Detailed message:

        at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.UserError.abort(UserError.java:97)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.FallbackFeature.reportAsFallback(FallbackFeature.java:248)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:872)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:593)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:555)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:544)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:731)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.start(NativeImageGeneratorRunner.java:151)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:99)
Caused by: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.
Error encountered while parsing com.oracle.svm.test.javaagent.agent1.TestJavaAgent1.premain(TestJavaAgent1.java:48)
Parsing context:
   at static root method.(Unknown Source)

Detailed message:

        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.constraints.UnsupportedFeatures.report(UnsupportedFeatures.java:126)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:867)
        ... 6 more
Caused by: com.oracle.graal.pointsto.constraints.UnresolvedElementException: Discovered unresolved type during parsing: org.junit.Assert. This error is reported at image build time because class com.oracle.svm.test.javaagent.agent1.TestJavaAgent1 is registered for linking at image build time by system default.
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.reportUnresolvedElement(SharedGraphBuilderPhase.java:604)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.reportUnresolvedElement(SharedGraphBuilderPhase.java:598)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedType(SharedGraphBuilderPhase.java:490)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedMethod(SharedGraphBuilderPhase.java:518)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.handleUnresolvedInvoke(SharedGraphBuilderPhase.java:411)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.genInvokeStatic(BytecodeParser.java:1864)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.genInvokeStatic(BytecodeParser.java:1843)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.processBytecode(BytecodeParser.java:5807)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.iterateBytecodesForBlock(BytecodeParser.java:3769)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.iterateBytecodesForBlock(SharedGraphBuilderPhase.java:954)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.handleBytecodeBlock(BytecodeParser.java:3729)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.processBlock(BytecodeParser.java:3576)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.build(BytecodeParser.java:1162)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase$SharedBytecodeParser.build(SharedGraphBuilderPhase.java:205)
        at jdk.graal.compiler/jdk.graal.compiler.java.BytecodeParser.buildRootMethod(BytecodeParser.java:1054)
        at jdk.graal.compiler/jdk.graal.compiler.java.GraphBuilderPhase$Instance.run(GraphBuilderPhase.java:103)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.phases.SharedGraphBuilderPhase.run(SharedGraphBuilderPhase.java:157)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.run(Phase.java:49)
        at jdk.graal.compiler/jdk.graal.compiler.phases.BasePhase.apply(BasePhase.java:468)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.apply(Phase.java:42)
        at jdk.graal.compiler/jdk.graal.compiler.phases.Phase.apply(Phase.java:38)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.AnalysisParsedGraph.parseBytecode(AnalysisParsedGraph.java:144)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.lambda$parseGraph$5(AnalysisMethod.java:986)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.setGraph(AnalysisMethod.java:1002)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.parseGraph(AnalysisMethod.java:986)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.ensureGraphParsedHelper(AnalysisMethod.java:958)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.meta.AnalysisMethod.ensureGraphParsed(AnalysisMethod.java:937)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.parse(MethodTypeFlowBuilder.java:190)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.apply(MethodTypeFlowBuilder.java:658)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.createFlowsGraph(MethodTypeFlow.java:167)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.ensureFlowsGraphCreated(MethodTypeFlow.java:152)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.flow.MethodTypeFlow.getOrCreateMethodFlowsGraphInfo(MethodTypeFlow.java:110)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.typestate.DefaultAnalysisPolicy.staticRootMethodGraph(DefaultAnalysisPolicy.java:208)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.PointsToAnalysis.lambda$addRootMethod$1(PointsToAnalysis.java:339)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.AbstractAnalysisEngine$1.run(AbstractAnalysisEngine.java:338)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.util.CompletionExecutor.executeCommand(CompletionExecutor.java:166)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.util.CompletionExecutor.lambda$executeService$0(CompletionExecutor.java:152)
        at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1423)
        at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387)
        at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1312)
        at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1843)
        at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1808)
        at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:188)

This doesn't happen in JVM because both TestJavaAgent1 and Assert are loaded by appClassloader in JVM mode.

Copy link
Member

Choose a reason for hiding this comment

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

@cstancu : please have a look at the code part below.

/**
* The java agent classes are loaded by appClassloader, but their dependencies could be
* loaded by NativeImageClassloader. So if the required method could not be resolved, we
* look further into classes loaded by nativeImageClassloader.
*/
if (ret instanceof UnresolvedJavaMethod && universe.hostVM().isFromJavaAgent(OriginalClassProvider.getJavaClass(caller.getDeclaringClass()))) {
UnresolvedJavaMethod unresolvedResult = (UnresolvedJavaMethod) ret;
String className = unresolvedResult.format("%H");
String methodNameWithSignature = unresolvedResult.format("%n(%P)");
try {
Class<?> loadedClass = ((AnalysisUniverse) universe).getConcurrentAnalysisAccess().findClassByName(className);
ResolvedJavaType resolvedType = ((AnalysisUniverse) universe).getOriginalMetaAccess().lookupJavaType(loadedClass);
ResolvedJavaMethod resolvedMethod = Arrays.stream(resolvedType.getDeclaredMethods(false)).filter(m -> m.format("%n(%P)").equals(methodNameWithSignature)).findFirst().get();
return universe.lookupAllowUnresolved(resolvedMethod);
} catch (Exception e) {
// Could not get the resolved method, get to the unresolved path
}
}
return ret;
} catch (Throwable ex) {
Throwable cause = ex;
if (ex instanceof ExceptionInInitializerError && ex.getCause() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,12 @@ public String[] retrievePremainArgs(String[] args) {

public void invokePremain() {
for (PremainMethod premainMethod : premainMethods) {

Object[] args = premainMethod.args;
if (premainOptions.containsKey(premainMethod.className)) {
args[0] = premainOptions.get(premainMethod.className);
}
try {
Object[] args = premainMethod.args;
// options set at runtime can override options set at build time
if (premainOptions.containsKey(premainMethod.className)) {
args[0] = premainOptions.get(premainMethod.className);
}
// premain method must be static
premainMethod.method.invoke(null, args);
} catch (Throwable t) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ protected void onValueUpdate(EconomicMap<OptionKey<?>, Object> values, String ol
public static OptionEnabledHandler<Boolean> imageLayerEnabledHandler;
public static OptionEnabledHandler<Boolean> imageLayerCreateEnabledHandler;

@APIOption(name = "-javaagent", valueSeparator = ':')//
@Option(help = "Enable the specified java agent in native image. Usage: -javaagent:<jarpath>[=<options>]. It's the same as using javaagent in JVM", type = User, stability = OptionStability.EXPERIMENTAL)//
Copy link
Member

Choose a reason for hiding this comment

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

This option needs a longer explanation because its behavior is not the same as on HotSpot:

  • the Java agent is used during the image build
  • premain of the Java agent is re-executed at run-time

public static final HostedOptionKey<AccumulatingLocatableMultiOptionValue.Strings> JavaAgent = new HostedOptionKey<>(AccumulatingLocatableMultiOptionValue.Strings.build());
Copy link
Member

Choose a reason for hiding this comment

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

This partially conflicts with the basic JVMTI runtime support that was merged a couple weeks ago (see #9558). I will need to think about that a bit and I will try to come up with an approach to unify the JVMTI build- and runtime support.

Copy link
Member

Choose a reason for hiding this comment

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

Where does the conflict come from? Feels to me that with javaagent transformations happen mostly at build time (except the premain), while JVMTI provides hooks for run-time events.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I don't think there is a conflict, as you said they are working on different phases. Class transformation has nothing to do with JVMTI events.

Copy link
Member

Choose a reason for hiding this comment

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

Both JVMTI and Java agents can be used to instrument Java classes. I was worried about those approaches conflicting. However, I think that you are right, this probably shouldn't result in worse situations than on HotSpot. Besides that, the same restrictions apply to both instrumentation approaches, so there is also no difference in terms of behavior there:

  • It is impossible to instrument most of the GraalVM-internal classes.
  • It is impossible to instrument certain JDK code (e.g., code that native image calls internally in low-level code, such as Throwable, java.lang.String, ...)
  • It is impossible to instrument code that Native Image substitutes (@TargetClass and similar annotations)


@Fold
public static boolean getSourceLevelDebug() {
return SourceLevelDebug.getValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@ private static <T> String oR(OptionKey<T> option) {
final String oHInspectServerContentPath = oH(PointstoOptions.InspectServerContentPath);
final String oHDeadlockWatchdogInterval = oH(SubstrateOptions.DeadlockWatchdogInterval);

final String oHJavaAgent = oH(SubstrateOptions.JavaAgent);

final Map<String, String> imageBuilderEnvironment = new HashMap<>();
private final ArrayList<String> imageBuilderArgs = new ArrayList<>();
private final LinkedHashSet<Path> imageBuilderModulePath = new LinkedHashSet<>();
Expand Down Expand Up @@ -1415,6 +1417,7 @@ private List<String> getAgentArguments() {
String agentOptions = "";
List<ArgumentEntry> traceClassInitializationOpts = getHostedOptionArgumentValues(imageBuilderArgs, oHTraceClassInitialization);
List<ArgumentEntry> traceObjectInstantiationOpts = getHostedOptionArgumentValues(imageBuilderArgs, oHTraceObjectInstantiation);
List<ArgumentEntry> javaAgentOpts = getHostedOptionArgumentValues(imageBuilderArgs, oHJavaAgent);
if (!traceClassInitializationOpts.isEmpty()) {
agentOptions = getAgentOptions(traceClassInitializationOpts, "c");
}
Expand All @@ -1433,6 +1436,12 @@ private List<String> getAgentArguments() {
args.add("-agentlib:native-image-diagnostics-agent=" + agentOptions);
}

if (!javaAgentOpts.isEmpty()) {
for (ArgumentEntry javaAgentOpt : javaAgentOpts) {
args.add("-javaagent:" + javaAgentOpt.value);
}
}

return args;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
package com.oracle.svm.hosted;

import com.oracle.svm.core.PreMainSupport;
import com.oracle.svm.core.SubstrateOptions;
import com.oracle.svm.core.feature.AutomaticallyRegisteredFeature;
import com.oracle.svm.core.feature.InternalFeature;
import com.oracle.svm.core.option.AccumulatingLocatableMultiOptionValue;
Expand All @@ -39,10 +40,12 @@
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.hosted.Feature;

import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;

/**
* This feature supports instrumentation in native image.
Expand Down Expand Up @@ -73,10 +76,10 @@ public void afterRegistration(AfterRegistrationAccess access) {
FeatureImpl.AfterRegistrationAccessImpl a = (FeatureImpl.AfterRegistrationAccessImpl) access;
cl = a.getImageClassLoader().getClassLoader();
ImageSingletons.add(PreMainSupport.class, preMainSupport = new PreMainSupport());
if (Options.PremainClasses.hasBeenSet()) {
List<String> premains = Options.PremainClasses.getValue().values();
for (String premain : premains) {
addPremainClass(premain);
if (SubstrateOptions.JavaAgent.hasBeenSet()) {
List<String> agentOptions = SubstrateOptions.JavaAgent.getValue().values();
for (String agentOption : agentOptions) {
addPremainClass(agentOption);
}
}
}
Expand All @@ -94,12 +97,34 @@ public void afterRegistration(AfterRegistrationAccess access) {
* is absent. <br>
* So this method looks for them in the same order.
*/
private void addPremainClass(String premainClass) {
private void addPremainClass(String javaagentOption) {
int separatorIndex = javaagentOption.indexOf("=");
Copy link
Member

Choose a reason for hiding this comment

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

You can probably use SubstrateUtil.split(...) instead.

String agent;
String premainClass = null;
String options = "";
// Get the agent file
if (separatorIndex == -1) {
agent = javaagentOption;
} else {
agent = javaagentOption.substring(0, separatorIndex);
options = javaagentOption.substring(separatorIndex + 1);
}
// Read MANIFEST in agent jar
try {
JarFile agentJarFile = new JarFile(agent);
premainClass = agentJarFile.getManifest().getMainAttributes().getValue("Premain-Class");
Copy link
Member

@vjovanov vjovanov Sep 12, 2024

Choose a reason for hiding this comment

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

What happens when there is no Manifest? There should be a special error message for that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

At this moment, the java agent has been already loaded and run by JVM.
If there is no Manifest, the JVM can't get started with -javaagent.
But in the proxy agent case, the actual agent will be loaded by -cp, we should check the existence of Manifest then.

Copy link
Member

@christianhaeubl christianhaeubl Sep 24, 2024

Choose a reason for hiding this comment

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

So, HotSpot already executed the method PremainClass.premain during the image build but native image should execute the same method again at run-time?

I think that this will only work for a very small number of Java agents (i.e., agents that contain Native Image-specific logic or that hardly execute any code in premain). If so, then I don't think that we should register the premain method automatically and use an opt-in approach instead.

Ideally, the agent manifest would contained some information to identify if the premain method supports re-execution at run-time. Alternatively, we could execute a different method as the Java agent probably needs to explicitly support native image anyways?

} catch (IOException e) {
// This shall not happen, because at this moment GraalVM is running with -javaagent.
Copy link
Member

Choose a reason for hiding this comment

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

This should never happen because the image build process (HotSpot) already loaded the agent during startup.

// If the agent doesn't exist, the JVM shall fail to start.
UserError.abort(e, "Can't read the agent jar %s. Please check option %s", agent,
Copy link
Member

Choose a reason for hiding this comment

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

throw UserError...

SubstrateOptionsParser.commandArgument(SubstrateOptions.JavaAgent, ""));
}

try {
Class<?> clazz = Class.forName(premainClass, false, cl);
Method premain = null;
List<Object> args = new ArrayList<>();
args.add(""); // First argument is options which will be set at runtime
args.add(options); // First argument is options which will be set at runtime
Copy link
Member

Choose a reason for hiding this comment

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

Can the options be overridden at run time?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes. Options set at runtime can override the build time options.

try {
premain = clazz.getDeclaredMethod("premain", String.class, Instrumentation.class);
args.add(new PreMainSupport.NativeImageNoOpRuntimeInstrumentation());
Expand All @@ -108,13 +133,13 @@ private void addPremainClass(String premainClass) {
premain = clazz.getDeclaredMethod("premain", String.class);
} catch (NoSuchMethodException e1) {
UserError.abort(e1, "Can't register agent premain method, because can't find the premain method from the given class %s. Please check your %s setting.", premainClass,
SubstrateOptionsParser.commandArgument(Options.PremainClasses, ""));
SubstrateOptionsParser.commandArgument(SubstrateOptions.JavaAgent, ""));
}
}
preMainSupport.registerPremainMethod(premainClass, premain, args.toArray(new Object[0]));
} catch (ClassNotFoundException e) {
UserError.abort(e, "Can't register agent premain method, because the given class %s is not found. Please check your %s setting.", premainClass,
SubstrateOptionsParser.commandArgument(Options.PremainClasses, ""));
SubstrateOptionsParser.commandArgument(SubstrateOptions.JavaAgent, ""));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1087,4 +1087,17 @@ public Set<AnalysisMethod> loadOpenTypeWorldDispatchTableMethods(AnalysisType ty
// return OpenTypeWorldFeature.loadDispatchTable(type);
return Set.of();
}

@Override
public boolean isFromJavaAgent(Class<?> clazz) {
if (SubstrateOptions.JavaAgent.hasBeenSet()) {
try {
String classLocation = clazz.getProtectionDomain().getCodeSource().getLocation().getFile();
return SubstrateOptions.JavaAgent.getValue().values().stream().map(s -> s.split("=")[0]).anyMatch(s -> s.equals(classLocation));
} catch (Exception e) {
return false;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,20 @@ private static void testPremainSequence() {
}
}

private static void testInstrumentation() {
// The return value of getCounter() should be changed by agent
Assert.assertEquals(11, getCounter());
}

private static int getCounter() {
return 10;
}

public static void main(String[] args) {
testPremain();
testAgentOptions();
testPremainSequence();
testInstrumentation();
System.out.println("Finished running Agent test.");
}
}
Loading