xref: /aosp_15_r20/external/jazzer-api/src/main/java/com/code_intelligence/jazzer/agent/AgentInstaller.java (revision 33edd6723662ea34453766bfdca85dbfdd5342b8)
1 // Copyright 2022 Code Intelligence GmbH
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 package com.code_intelligence.jazzer.agent;
16 
17 import static com.code_intelligence.jazzer.agent.AgentUtils.extractBootstrapJar;
18 import static com.code_intelligence.jazzer.runtime.Constants.IS_ANDROID;
19 
20 import java.lang.instrument.Instrumentation;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import net.bytebuddy.agent.ByteBuddyAgent;
25 
26 public class AgentInstaller {
27   private static final AtomicBoolean hasBeenInstalled = new AtomicBoolean();
28 
29   /**
30    * Appends the parts of Jazzer that have to be visible to all classes, including those in the Java
31    * standard library, to the bootstrap class loader path. Additionally, if enableAgent is true,
32    * also enables the Jazzer agent that instruments classes for fuzzing.
33    */
install(boolean enableAgent)34   public static void install(boolean enableAgent) {
35     // Only install the agent once.
36     if (!hasBeenInstalled.compareAndSet(false, true)) {
37       return;
38     }
39 
40     if (IS_ANDROID) {
41       return;
42     }
43 
44     Instrumentation instrumentation = ByteBuddyAgent.install();
45     instrumentation.appendToBootstrapClassLoaderSearch(extractBootstrapJar());
46     if (!enableAgent) {
47       return;
48     }
49     try {
50       Class<?> agent = Class.forName("com.code_intelligence.jazzer.agent.Agent");
51       Method install = agent.getMethod("install", Instrumentation.class);
52       install.invoke(null, instrumentation);
53     } catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException
54         | IllegalAccessException e) {
55       throw new IllegalStateException("Failed to run Agent.install", e);
56     }
57   }
58 }
59