diff --git a/dd-java-agent/src/main/java/datadog/trace/bootstrap/AgentBootstrap.java b/dd-java-agent/src/main/java/datadog/trace/bootstrap/AgentBootstrap.java index 0114503447c..0d60c68ce76 100644 --- a/dd-java-agent/src/main/java/datadog/trace/bootstrap/AgentBootstrap.java +++ b/dd-java-agent/src/main/java/datadog/trace/bootstrap/AgentBootstrap.java @@ -46,8 +46,21 @@ */ public final class AgentBootstrap { static final String LIB_INJECTION_ENABLED_ENV_VAR = "DD_INJECTION_ENABLED"; + static final String LIB_INJECTION_ENABLED_SYS_PROP = "dd.injection.enabled"; static final String LIB_INJECTION_FORCE_SYS_PROP = "dd.inject.force"; + static final String LIB_INJECTION_MODE_SYS_PROP = "dd.injection.mode"; + static final String LIB_INJECTION_MODE_ATTACH = "attach"; static final String LIB_INSTRUMENTATION_SOURCE_SYS_PROP = "dd.instrumentation.source"; + static final String TELEMETRY_FORWARDER_PATH_ENV_VAR = "DD_TELEMETRY_FORWARDER_PATH"; + static final String TELEMETRY_FORWARDER_PATH_SYS_PROP = "dd.telemetry.forwarder.path"; + + /** Classes that only ship in other APM agents' jars, not in their public API artifacts. */ + static final String[] OTHER_APM_AGENT_MARKER_CLASSES = { + "io.opentelemetry.javaagent.bootstrap.AgentInitializer", + "com.newrelic.bootstrap.BootstrapAgent", + "com.singularity.ee.agent.appagent.AgentEntryPoint", // AppDynamics + "co.elastic.apm.agent.premain.AgentMain", + }; private static final Class thisClass = AgentBootstrap.class; private static final int MAX_EXCEPTION_CHAIN_LENGTH = 99; @@ -65,7 +78,7 @@ public static void agentmain(final String agentArgs, final Instrumentation inst) BootstrapInitializationTelemetry initTelemetry; try { - initTelemetry = createInitializationTelemetry(); + initTelemetry = createInitializationTelemetry(agentArgs); } catch (Throwable t) { initTelemetry = BootstrapInitializationTelemetry.noOpInstance(); } @@ -90,8 +103,8 @@ public static void agentmain(final String agentArgs, final Instrumentation inst) } } - private static BootstrapInitializationTelemetry createInitializationTelemetry() { - String forwarderPath = EnvironmentVariables.get("DD_TELEMETRY_FORWARDER_PATH"); + private static BootstrapInitializationTelemetry createInitializationTelemetry(String agentArgs) { + String forwarderPath = getTelemetryForwarderPath(agentArgs); if (forwarderPath == null) { return BootstrapInitializationTelemetry.noOpInstance(); } @@ -131,12 +144,12 @@ private static void agentmainImpl( initTelemetry.onAbort("jdk_tool"); return; } - if (shouldAbortDueToOtherJavaAgents()) { + if (shouldAbortDueToOtherJavaAgents(agentArgs, inst)) { initTelemetry.onAbort("other-java-agents"); return; } - if (getConfig(LIB_INJECTION_ENABLED_ENV_VAR)) { + if (isInjectionEnabled(agentArgs)) { recordInstrumentationSource("ssi"); } else { recordInstrumentationSource("cmd_line"); @@ -169,23 +182,83 @@ private static void agentmainImpl( } } - static boolean getConfig(String configName) { - switch (configName) { - case LIB_INJECTION_ENABLED_ENV_VAR: - return EnvironmentVariables.get(LIB_INJECTION_ENABLED_ENV_VAR) != null; - case LIB_INJECTION_FORCE_SYS_PROP: - { - String envVarName = - LIB_INJECTION_FORCE_SYS_PROP.replace('.', '_').replace('-', '_').toUpperCase(); - String injectionForceFlag = EnvironmentVariables.get(envVarName); - if (injectionForceFlag == null) { - injectionForceFlag = SystemProperties.get(LIB_INJECTION_FORCE_SYS_PROP); - } - return "true".equalsIgnoreCase(injectionForceFlag) || "1".equals(injectionForceFlag); + static boolean isInjectionEnabled(String agentArgs) { + return EnvironmentVariables.get(LIB_INJECTION_ENABLED_ENV_VAR) != null + || SystemProperties.get(LIB_INJECTION_ENABLED_SYS_PROP) != null + || getAgentArg(agentArgs, LIB_INJECTION_ENABLED_SYS_PROP) != null; + } + + static boolean isInjectionForced(String agentArgs) { + String injectionForceFlag = EnvironmentVariables.get("DD_INJECT_FORCE"); + if (injectionForceFlag == null) { + injectionForceFlag = SystemProperties.get(LIB_INJECTION_FORCE_SYS_PROP); + } + if (injectionForceFlag == null) { + injectionForceFlag = getAgentArg(agentArgs, LIB_INJECTION_FORCE_SYS_PROP); + } + return "true".equalsIgnoreCase(injectionForceFlag) || "1".equals(injectionForceFlag); + } + + static boolean isAttachMode(String agentArgs) { + String mode = SystemProperties.get(LIB_INJECTION_MODE_SYS_PROP); + if (mode == null) { + mode = getAgentArg(agentArgs, LIB_INJECTION_MODE_SYS_PROP); + } + return LIB_INJECTION_MODE_ATTACH.equalsIgnoreCase(mode); + } + + static String getTelemetryForwarderPath(String agentArgs) { + String forwarderPath = EnvironmentVariables.get(TELEMETRY_FORWARDER_PATH_ENV_VAR); + if (forwarderPath == null) { + forwarderPath = getAgentArg(agentArgs, TELEMETRY_FORWARDER_PATH_SYS_PROP); + } + return forwarderPath; + } + + /** + * Returns the trimmed value of {@code key} in comma-separated agent arguments, or {@code null} if + * it is missing or empty. + */ + static String getAgentArg(String agentArgs, String key) { + if (agentArgs == null) { + return null; + } + int length = agentArgs.length(); + int keyLength = key.length(); + int start = 0; + while (start < length) { + int end = agentArgs.indexOf(',', start); + if (end < 0) { + end = length; + } + int separator = agentArgs.indexOf('=', start); + if (separator >= 0 && separator < end) { + int keyStart = skipWhitespace(agentArgs, start, separator); + int keyEnd = trimWhitespace(agentArgs, keyStart, separator); + if (keyEnd - keyStart == keyLength + && agentArgs.regionMatches(keyStart, key, 0, keyLength)) { + int valueStart = skipWhitespace(agentArgs, separator + 1, end); + int valueEnd = trimWhitespace(agentArgs, valueStart, end); + return valueStart < valueEnd ? agentArgs.substring(valueStart, valueEnd) : null; } - default: - return false; + } + start = end + 1; + } + return null; + } + + private static int skipWhitespace(String s, int from, int to) { + while (from < to && Character.isWhitespace(s.charAt(from))) { + from++; + } + return from; + } + + private static int trimWhitespace(String s, int from, int to) { + while (to > from && Character.isWhitespace(s.charAt(to - 1))) { + to--; } + return to; } private static void recordInstrumentationSource(String source) { @@ -361,21 +434,46 @@ static boolean isJdkTool() { return false; } + static boolean shouldAbortDueToOtherJavaAgents(String agentArgs, Instrumentation inst) { + return shouldAbortDueToOtherJavaAgents(agentArgs, inst, getAgentFilesFromVMArguments()); + } + @SuppressForbidden - static boolean shouldAbortDueToOtherJavaAgents() { + static boolean shouldAbortDueToOtherJavaAgents( + String agentArgs, Instrumentation inst, List javaAgentFiles) { // We don't abort if either // * We are not using SSI // * Injection is forced - // * There is only one agent - if (!getConfig(LIB_INJECTION_ENABLED_ENV_VAR) - || getConfig(LIB_INJECTION_FORCE_SYS_PROP) - || getAgentFilesFromVMArguments().size() <= 1) { + if (!isInjectionEnabled(agentArgs) || isInjectionForced(agentArgs)) { + return false; + } + + boolean attachMode = isAttachMode(agentArgs); + if (attachMode) { + String otherAgentClass = + findLoadedClass(inst.getAllLoadedClasses(), OTHER_APM_AGENT_MARKER_CLASSES); + if (otherAgentClass != null) { + System.err.println( + "Info: another APM agent was found at runtime (found class " + + otherAgentClass + + "). Loading multiple APM/Tracing agent is not a recommended or supported configuration. " + + "Please set the environment variable DD_INJECT_FORCE or the system property dd.inject.force to TRUE to load Datadog APM/Tracing agent."); + return true; + } + } + + return hasOtherJavaAgentFiles(javaAgentFiles, attachMode ? 0 : 1); + } + + @SuppressForbidden + static boolean hasOtherJavaAgentFiles(List javaAgentFiles, int ownAgentFileCount) { + if (javaAgentFiles.size() <= ownAgentFileCount) { return false; } - // If there are 2 agents and one of them is for patching log4j, it's fine - if (getAgentFilesFromVMArguments().size() == 2) { - for (File agentFile : getAgentFilesFromVMArguments()) { + // If the only other agent is for patching log4j, it's fine + if (javaAgentFiles.size() == ownAgentFileCount + 1) { + for (File agentFile : javaAgentFiles) { if (agentFile.getName().toLowerCase().contains("log4j")) { return false; } @@ -386,7 +484,7 @@ static boolean shouldAbortDueToOtherJavaAgents() { // Formatting agent file list, Java 7 style StringBuilder agentFiles = new StringBuilder(); boolean first = true; - for (File agentFile : getAgentFilesFromVMArguments()) { + for (File agentFile : javaAgentFiles) { if (first) { first = false; } else { @@ -404,6 +502,18 @@ static boolean shouldAbortDueToOtherJavaAgents() { return true; } + static String findLoadedClass(Class[] loadedClasses, String[] classNames) { + for (Class loadedClass : loadedClasses) { + String name = loadedClass.getName(); + for (String className : classNames) { + if (className.equals(name)) { + return className; + } + } + } + return null; + } + public static void main(final String[] args) { AgentJar.main(args); } diff --git a/dd-java-agent/src/test/java/datadog/trace/bootstrap/AgentBootstrapTest.java b/dd-java-agent/src/test/java/datadog/trace/bootstrap/AgentBootstrapTest.java index 098d3a7067f..ed48073ac74 100644 --- a/dd-java-agent/src/test/java/datadog/trace/bootstrap/AgentBootstrapTest.java +++ b/dd-java-agent/src/test/java/datadog/trace/bootstrap/AgentBootstrapTest.java @@ -1,16 +1,38 @@ package datadog.trace.bootstrap; import static datadog.trace.bootstrap.AgentBootstrap.exceptionCauseChainContains; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; import java.io.IOException; +import java.lang.instrument.Instrumentation; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; class AgentBootstrapTest { private static final String IO_EXCEPTION = "java.io.IOException"; + private static final String SSI_ATTACH_ARGS = + "dd.injection.enabled=tracer,dd.injection.mode=attach," + + "dd.telemetry.forwarder.path=/opt/datadog-packages/datadog-apm-inject/stable/inject/process"; + private static final String NEW_RELIC_MARKER = "com.newrelic.bootstrap.BootstrapAgent"; + + @AfterEach + void clearSystemProperties() { + System.clearProperty(AgentBootstrap.LIB_INJECTION_ENABLED_SYS_PROP); + System.clearProperty(AgentBootstrap.LIB_INJECTION_FORCE_SYS_PROP); + System.clearProperty(AgentBootstrap.LIB_INJECTION_MODE_SYS_PROP); + } @Test void returnTrueWhenFirstExceptionInTheCauseChainIsTheSpecifiedException() { @@ -40,4 +62,230 @@ void returnFalseWhenExceptionCauseChainHasACycle() { assertFalse(exceptionCauseChainContains(ex, IO_EXCEPTION)); } + + @TableTest({ + "scenario | agentArgs | key | expected", + "null args | | dd.injection.mode | ", + "empty args | '' | dd.injection.mode | ", + "single entry | 'dd.injection.mode=attach' | dd.injection.mode | attach ", + "first entry | 'a=1,b=2,c=3' | a | 1 ", + "middle entry | 'a=1,b=2,c=3' | b | 2 ", + "last entry | 'a=1,b=2,c=3' | c | 3 ", + "missing key | 'a=1,b=2' | c | ", + "key prefix | 'dd.injection.mode.x=attach' | dd.injection.mode | ", + "key suffix | 'x.dd.injection.mode=attach' | dd.injection.mode | ", + "trimmed | ' a = 1 , b = 2 ' | b | 2 ", + "empty value | 'a=,b=2' | a | ", + "no separator | 'a,b=2' | a | ", + "separator in value | 'a=x=y,b=2' | a | x=y ", + "trailing comma | 'a=1,' | a | 1 ", + "only commas | ',,,' | a | ", + "plain arg | 'aot_training' | dd.injection.mode | " + }) + void parseAgentArg(String agentArgs, String key, String expected) { + assertEquals(expected, AgentBootstrap.getAgentArg(agentArgs, key)); + } + + @Test + void parseSsiAttachAgentArgs() { + assertEquals("tracer", AgentBootstrap.getAgentArg(SSI_ATTACH_ARGS, "dd.injection.enabled")); + assertEquals("attach", AgentBootstrap.getAgentArg(SSI_ATTACH_ARGS, "dd.injection.mode")); + assertEquals( + "/opt/datadog-packages/datadog-apm-inject/stable/inject/process", + AgentBootstrap.getTelemetryForwarderPath(SSI_ATTACH_ARGS)); + } + + @Test + void injectionNotEnabledByDefault() { + assertFalse(AgentBootstrap.isInjectionEnabled(null)); + assertFalse(AgentBootstrap.isInjectionEnabled("dd.service=foo")); + assertFalse(AgentBootstrap.isAttachMode(null)); + assertFalse(AgentBootstrap.isInjectionForced(null)); + } + + @Test + void injectionEnabledFromAgentArgs() { + assertTrue(AgentBootstrap.isInjectionEnabled(SSI_ATTACH_ARGS)); + assertTrue(AgentBootstrap.isAttachMode(SSI_ATTACH_ARGS)); + } + + @Test + void injectionEnabledFromSystemProperties() { + System.setProperty(AgentBootstrap.LIB_INJECTION_ENABLED_SYS_PROP, "tracer"); + System.setProperty(AgentBootstrap.LIB_INJECTION_MODE_SYS_PROP, "attach"); + + assertTrue(AgentBootstrap.isInjectionEnabled(null)); + assertTrue(AgentBootstrap.isAttachMode(null)); + } + + @TableTest({ + "scenario | agentArgs | expected", + "missing | 'dd.injection.enabled=tracer' | false ", + "true | 'dd.injection.enabled=tracer,dd.inject.force=true' | true ", + "TRUE | 'dd.inject.force=TRUE' | true ", + "1 | 'dd.inject.force=1' | true ", + "false | 'dd.inject.force=false' | false " + }) + void injectionForcedFromAgentArgs(String agentArgs, boolean expected) { + assertEquals(expected, AgentBootstrap.isInjectionForced(agentArgs)); + } + + @Test + void injectionForcedSystemPropertyTakesPrecedenceOverAgentArgs() { + System.setProperty(AgentBootstrap.LIB_INJECTION_FORCE_SYS_PROP, "false"); + + assertFalse(AgentBootstrap.isInjectionForced("dd.inject.force=true")); + } + + @Test + void notAttachModeForOtherModes() { + assertFalse(AgentBootstrap.isAttachMode("dd.injection.mode=exec")); + } + + @Test + void doNotAbortWithoutInjection() { + Instrumentation inst = instrumentationWithLoadedClasses(markerClass(NEW_RELIC_MARKER)); + + assertFalse( + AgentBootstrap.shouldAbortDueToOtherJavaAgents( + "dd.injection.mode=attach", inst, Collections.emptyList())); + } + + @Test + void abortWhenOtherApmAgentIsLoadedInAttachMode() { + Instrumentation inst = instrumentationWithLoadedClasses(markerClass(NEW_RELIC_MARKER)); + + assertTrue( + AgentBootstrap.shouldAbortDueToOtherJavaAgents( + SSI_ATTACH_ARGS, inst, Collections.emptyList())); + } + + @Test + void doNotAbortWhenInjectionIsForced() { + Instrumentation inst = instrumentationWithLoadedClasses(markerClass(NEW_RELIC_MARKER)); + + assertFalse( + AgentBootstrap.shouldAbortDueToOtherJavaAgents( + SSI_ATTACH_ARGS + ",dd.inject.force=true", inst, Collections.emptyList())); + } + + @TableTest({ + "scenario | agentArgs | agentFile | expected", + "attach, other agent | 'dd.injection.enabled=tracer,dd.injection.mode=attach' | other.jar | true ", + "attach, log4j patch | 'dd.injection.enabled=tracer,dd.injection.mode=attach' | log4j.jar | false ", + "exec, single agent | 'dd.injection.enabled=tracer' | dd-java-agent.jar | false " + }) + void abortOnOtherJavaAgentFileDependsOnInjectionMode( + String agentArgs, String agentFile, boolean expected) { + Instrumentation inst = instrumentationWithLoadedClasses(String.class); + + assertEquals( + expected, + AgentBootstrap.shouldAbortDueToOtherJavaAgents( + agentArgs, inst, Collections.singletonList(new File(agentFile)))); + } + + @TableTest({ + "scenario | agentFiles | ownAgentFileCount | expected", + "attach, no other agent | [] | 0 | false ", + "attach, one other agent | [other.jar] | 0 | true ", + "attach, log4j patch only | [log4j-patch.jar] | 0 | false ", + "exec, only dd agent | [dd-java-agent.jar] | 1 | false ", + "exec, one other agent | [dd-java-agent.jar, other.jar] | 1 | true ", + "exec, log4j patch | [dd-java-agent.jar, log4j.jar] | 1 | false ", + "exec, two other agents | [dd.jar, log4j.jar, other.jar] | 1 | true " + }) + void detectOtherJavaAgentFiles(List agentFiles, int ownAgentFileCount, boolean expected) { + List files = new ArrayList<>(); + for (String agentFile : agentFiles) { + files.add(new File(agentFile)); + } + + assertEquals(expected, AgentBootstrap.hasOtherJavaAgentFiles(files, ownAgentFileCount)); + } + + @Test + void findLoadedClassByName() { + Class[] loadedClasses = {String.class, AgentBootstrapTest.class}; + + assertEquals( + "java.lang.String", + AgentBootstrap.findLoadedClass(loadedClasses, new String[] {"x.Y", "java.lang.String"})); + assertNull(AgentBootstrap.findLoadedClass(loadedClasses, new String[] {"x.Y"})); + } + + @Test + void noOtherApmAgentLoaded() { + Class[] loadedClasses = {String.class, AgentBootstrapTest.class}; + + assertNull( + AgentBootstrap.findLoadedClass( + loadedClasses, AgentBootstrap.OTHER_APM_AGENT_MARKER_CLASSES)); + } + + private static Instrumentation instrumentationWithLoadedClasses(Class... loadedClasses) { + Instrumentation inst = mock(Instrumentation.class); + when(inst.getAllLoadedClasses()).thenReturn(loadedClasses); + return inst; + } + + private static Class markerClass(String name) { + try { + return new MarkerClassLoader(name).loadClass(name); + } catch (ClassNotFoundException e) { + throw new IllegalStateException(e); + } + } + + private static final class MarkerClassLoader extends ClassLoader { + private static final int JAVA_8_CLASS_VERSION = 52; + private static final int CONSTANT_UTF8 = 1; + private static final int CONSTANT_CLASS = 7; + private static final int ACC_PUBLIC_SUPER = 0x0021; + + private final String markerClass; + + MarkerClassLoader(String markerClass) { + super(null); + this.markerClass = markerClass; + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (!name.equals(this.markerClass)) { + throw new ClassNotFoundException(name); + } + byte[] bytes = emptyClass(name.replace('.', '/')); + return defineClass(name, bytes, 0, bytes.length); + } + + private static byte[] emptyClass(String internalName) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bytes); + out.writeInt(0xCAFEBABE); + out.writeShort(0); + out.writeShort(JAVA_8_CLASS_VERSION); + out.writeShort(5); + out.writeByte(CONSTANT_UTF8); + out.writeUTF(internalName); + out.writeByte(CONSTANT_CLASS); + out.writeShort(1); + out.writeByte(CONSTANT_UTF8); + out.writeUTF("java/lang/Object"); + out.writeByte(CONSTANT_CLASS); + out.writeShort(3); + out.writeShort(ACC_PUBLIC_SUPER); + out.writeShort(2); + out.writeShort(4); + out.writeShort(0); + out.writeShort(0); + out.writeShort(0); + out.writeShort(0); + return bytes.toByteArray(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + } } diff --git a/dd-smoke-tests/spring-boot-2.3-webmvc-jetty/src/test/java/datadog/smoketest/LateAttachSmokeTest.java b/dd-smoke-tests/spring-boot-2.3-webmvc-jetty/src/test/java/datadog/smoketest/LateAttachSmokeTest.java new file mode 100644 index 00000000000..f7a660da074 --- /dev/null +++ b/dd-smoke-tests/spring-boot-2.3-webmvc-jetty/src/test/java/datadog/smoketest/LateAttachSmokeTest.java @@ -0,0 +1,83 @@ +package datadog.smoketest; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import datadog.smoketest.backend.AgentBackend; +import datadog.trace.test.util.PollingConditions; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; +import org.junit.jupiter.api.extension.RegisterExtension; + +@EnabledForJreRange(min = JRE.JAVA_9) +class LateAttachSmokeTest { + private static final String SSI_ATTACH_AGENT_ARGS = + "dd.injection.enabled=tracer,dd.injection.mode=attach"; + + private static final AgentBackend BACKEND = AgentBackend.mockAgent(); + + @RegisterExtension + static final SmokeServerApp app = + SmokeServerApp.named("late-attach") + .jar(System.getProperty("datadog.smoketest.springboot.shadowJar.path")) + .noAgent() + .skipScopeContinuationCheck( + "The tracer is attached at runtime; the companion requires a -javaagent launch.") + .backend(BACKEND) + .placeholder("agent.port", () -> Integer.toString(BACKEND.port())) + .jvmArgs( + "-Ddd.trace.agent.port=${agent.port}", + "-Ddd.service.name=" + ProcessManager.SERVICE_NAME, + "-Ddd.env=" + ProcessManager.ENV, + "-Ddd.version=" + ProcessManager.VERSION) + .args("--server.port=${app.httpPort}") + .build(); + + @Test + @DisplayName("requests are traced after the tracer is attached") + void tracesAfterLateAttach() throws Exception { + assertEquals(404, app.get("/hello/not-here")); + assertEquals(0, app.traces().getTraces().size(), "no traces before the tracer is attached"); + + attachTracer("--server.port=" + app.httpPort()); + + new PollingConditions(30) + .eventually(() -> { + app.get("/hello/not-here"); + app.traces().waitForTraceCount(1, 1); + }); + } + + private static void attachTracer(String uniqueCommandLineArg) throws Exception { + String agentJar = System.getProperty("datadog.smoketest.agent.shadowJar.path"); + Class vmClass = Class.forName("com.sun.tools.attach.VirtualMachine"); + Class descriptorClass = Class.forName("com.sun.tools.attach.VirtualMachineDescriptor"); + Method displayName = descriptorClass.getMethod("displayName"); + Method id = descriptorClass.getMethod("id"); + + String pid = null; + for (Object descriptor : (List) vmClass.getMethod("list").invoke(null)) { + String[] commandLine = ((String) displayName.invoke(descriptor)).split(" "); + if (Arrays.asList(commandLine).contains(uniqueCommandLineArg)) { + pid = (String) id.invoke(descriptor); + break; + } + } + if (pid == null) { + throw new IllegalStateException("No JVM found with " + uniqueCommandLineArg); + } + + Object vm = vmClass.getMethod("attach", String.class).invoke(null, pid); + try { + vmClass + .getMethod("loadAgent", String.class, String.class) + .invoke(vm, agentJar, SSI_ATTACH_AGENT_ARGS); + } finally { + vmClass.getMethod("detach").invoke(vm); + } + } +}