-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathAgentStarterImpl.java
More file actions
367 lines (335 loc) · 13.7 KB
/
Copy pathAgentStarterImpl.java
File metadata and controls
367 lines (335 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.tooling;
import io.opentelemetry.context.Context;
import io.opentelemetry.instrumentation.api.internal.ServiceLoaderUtil;
import io.opentelemetry.instrumentation.api.internal.cache.weaklockfree.WeakConcurrentMapCleaner;
import io.opentelemetry.javaagent.bootstrap.AgentInitializer;
import io.opentelemetry.javaagent.bootstrap.AgentStarter;
import io.opentelemetry.javaagent.extension.instrumentation.internal.AsmApi;
import io.opentelemetry.javaagent.tooling.config.EarlyInitAgentConfig;
import java.io.File;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;
import java.util.ServiceLoader;
import javax.annotation.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Main entry point into code that is running inside agent class loader, used reflectively from
* {@code io.opentelemetry.javaagent.bootstrap.AgentInitializer}.
*/
public class AgentStarterImpl implements AgentStarter {
private final Instrumentation instrumentation;
private final File javaagentFile;
private final boolean isSecurityManagerSupportEnabled;
@Nullable private ClassLoader extensionClassLoader;
public AgentStarterImpl(
Instrumentation instrumentation,
File javaagentFile,
boolean isSecurityManagerSupportEnabled) {
this.instrumentation = instrumentation;
this.javaagentFile = javaagentFile;
this.isSecurityManagerSupportEnabled = isSecurityManagerSupportEnabled;
}
@Override
public boolean delayStart() {
LaunchHelperClassFileTransformer transformer = new LaunchHelperClassFileTransformer();
instrumentation.addTransformer(transformer, true);
try {
Class<?> clazz = Class.forName("sun.launcher.LauncherHelper", false, null);
if (transformer.transformed) {
// LauncherHelper was loaded and got transformed
return transformer.hookInserted;
}
// LauncherHelper was already loaded before we set up transformer
instrumentation.retransformClasses(clazz);
return transformer.hookInserted;
} catch (ClassNotFoundException | UnmodifiableClassException ignored) {
return false;
} finally {
instrumentation.removeTransformer(transformer);
}
}
@Override
public void start() {
installTransformers();
extensionClassLoader = createExtensionClassLoader(getClass().getClassLoader());
// allows loading instrumenter customizers from agent and extensions
ServiceLoaderUtil.setLoadFunction(clazz -> ServiceLoader.load(clazz, extensionClassLoader));
String loggerImplementationName = EarlyInitAgentConfig.get().getLogging();
// default to the built-in stderr slf4j-simple logger
if (loggerImplementationName == null) {
loggerImplementationName = "simple";
}
LoggingCustomizer loggingCustomizer = null;
for (LoggingCustomizer customizer :
ServiceLoader.load(LoggingCustomizer.class, extensionClassLoader)) {
if (customizer.name().equalsIgnoreCase(loggerImplementationName)) {
loggingCustomizer = customizer;
break;
}
}
// unsupported logger implementation; defaulting to noop
if (loggingCustomizer == null) {
logUnrecognizedLoggerImplWarning(loggerImplementationName);
loggingCustomizer = new NoopLoggingCustomizer();
}
Throwable startupError = null;
try {
loggingCustomizer.init();
EarlyInitAgentConfig.get().logEarlyConfigErrorsIfAny();
AgentInstaller.installBytebuddyAgent(instrumentation, extensionClassLoader);
WeakConcurrentMapCleaner.start();
// LazyStorage reads system properties. Initialize it here where we have permissions to avoid
// failing permission checks when it is initialized from user code.
if (System.getSecurityManager() != null) {
Context.current();
}
} catch (Throwable t) {
// this is logged below and not rethrown to avoid logging it twice
startupError = t;
}
if (startupError == null) {
loggingCustomizer.onStartupSuccess();
} else {
loggingCustomizer.onStartupFailure(startupError);
}
}
private void installTransformers() {
// prevents loading InetAddressResolverProvider SPI before agent has started
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/7130
// https://github.com/open-telemetry/opentelemetry-java-instrumentation/issues/10921
instrumentation.addTransformer(new InetAddressClassFileTransformer(), true);
// JDK 26 prints a warning when the value of final field is changed with reflection. Here we
// remove the final modifier from the "transformations" field of ByteBuddy's
// AgentBuilder.Default class to avoid that warning, as we change that field in
// AgentBuilderUtil.
instrumentation.addTransformer(new AgentBuilderDefaultClassFileTransformer(), true);
// transforms Thread getContextClassLoader and setContextClassLoader calls in
// io.opentelemetry.sdk.metrics.internal.state.CallbackRegistration to use doPrivileged so that
// security manager wouldn't deny these calls
instrumentation.addTransformer(new CallbackRegistrationClassFileTransformer(), true);
}
@SuppressWarnings("SystemOut")
private static void logUnrecognizedLoggerImplWarning(String loggerImplementationName) {
System.err.println(
"Unrecognized value of 'otel.javaagent.logging': '"
+ loggerImplementationName
+ "'. The agent will use the no-op implementation.");
}
@Nullable
@Override
public ClassLoader getExtensionClassLoader() {
return extensionClassLoader;
}
private ClassLoader createExtensionClassLoader(ClassLoader agentClassLoader) {
return ExtensionClassLoader.getInstance(
agentClassLoader, javaagentFile, isSecurityManagerSupportEnabled);
}
private static class LaunchHelperClassFileTransformer implements ClassFileTransformer {
boolean hookInserted = false;
boolean transformed = false;
@Nullable
@Override
public byte[] transform(
ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
if (!"sun/launcher/LauncherHelper".equals(className)) {
return null;
}
transformed = true;
ClassReader cr = new ClassReader(classfileBuffer);
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv =
new ClassVisitor(AsmApi.VERSION, cw) {
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
if ("checkAndLoadMain".equals(name)) {
return new MethodVisitor(api, mv) {
@Override
public void visitCode() {
super.visitCode();
hookInserted = true;
mv.visitMethodInsn(
Opcodes.INVOKESTATIC,
Type.getInternalName(AgentInitializer.class),
"delayedStartHook",
"()V",
false);
}
};
}
return mv;
}
};
cr.accept(cv, 0);
return hookInserted ? cw.toByteArray() : null;
}
}
private static class InetAddressClassFileTransformer implements ClassFileTransformer {
boolean hookInserted = false;
@Nullable
@Override
public byte[] transform(
ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
if (!"java/net/InetAddress".equals(className)) {
return null;
}
ClassReader cr = new ClassReader(classfileBuffer);
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv =
new ClassVisitor(AsmApi.VERSION, cw) {
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
if (!"resolver".equals(name)) {
return mv;
}
return new MethodVisitor(api, mv) {
@Override
public void visitMethodInsn(
int opcode,
String ownerClassName,
String methodName,
String descriptor,
boolean isInterface) {
super.visitMethodInsn(
opcode, ownerClassName, methodName, descriptor, isInterface);
// rewrite Vm.isBooted() to AgentInitializer.isAgentStarted(Vm.isBooted())
if ("jdk/internal/misc/VM".equals(ownerClassName)
&& "isBooted".equals(methodName)) {
super.visitMethodInsn(
Opcodes.INVOKESTATIC,
Type.getInternalName(AgentInitializer.class),
"isAgentStarted",
"(Z)Z",
false);
hookInserted = true;
}
}
};
}
};
cr.accept(cv, 0);
return hookInserted ? cw.toByteArray() : null;
}
}
private static class AgentBuilderDefaultClassFileTransformer implements ClassFileTransformer {
@Nullable
@Override
public byte[] transform(
ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
if (loader != getClass().getClassLoader()
|| !"net/bytebuddy/agent/builder/AgentBuilder$Default".equals(className)) {
return null;
}
ClassReader cr = new ClassReader(classfileBuffer);
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv =
new ClassVisitor(AsmApi.VERSION, cw) {
@Override
public FieldVisitor visitField(
int access, String name, String descriptor, String signature, Object value) {
// remove final modifier
if ("transformations".equals(name) && (access & Opcodes.ACC_FINAL) != 0) {
access &= ~Opcodes.ACC_FINAL;
}
return super.visitField(access, name, descriptor, signature, value);
}
};
cr.accept(cv, 0);
return cw.toByteArray();
}
}
private static class CallbackRegistrationClassFileTransformer implements ClassFileTransformer {
@Nullable
@Override
public byte[] transform(
ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
if (loader != getClass().getClassLoader()
|| !"io/opentelemetry/sdk/metrics/internal/state/CallbackRegistration"
.equals(className)) {
return null;
}
ClassReader cr = new ClassReader(classfileBuffer);
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv =
new ClassVisitor(AsmApi.VERSION, cw) {
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
if (!"invokeCallback".equals(name) && !"<init>".equals(name)) {
return mv;
}
return new MethodVisitor(api, mv) {
@Override
public void visitMethodInsn(
int opcode,
String ownerClassName,
String methodName,
String descriptor,
boolean isInterface) {
if ("getContextClassLoader".equals(methodName)
&& Type.getInternalName(Thread.class).equals(ownerClassName)) {
super.visitMethodInsn(
Opcodes.INVOKESTATIC,
Type.getInternalName(Utils.class),
"getContextClassLoader",
"("
+ Type.getDescriptor(Thread.class)
+ ")"
+ Type.getDescriptor(ClassLoader.class),
false);
} else if ("setContextClassLoader".equals(methodName)
&& Type.getInternalName(Thread.class).equals(ownerClassName)) {
super.visitMethodInsn(
Opcodes.INVOKESTATIC,
Type.getInternalName(Utils.class),
"setContextClassLoader",
"("
+ Type.getDescriptor(Thread.class)
+ Type.getDescriptor(ClassLoader.class)
+ ")V",
false);
} else {
super.visitMethodInsn(
opcode, ownerClassName, methodName, descriptor, isInterface);
}
}
};
}
};
cr.accept(cv, 0);
return cw.toByteArray();
}
}
}