1 /*
   2  * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.jfr.internal.instrument;
  27 
  28 import java.util.ArrayList;
  29 import java.util.List;
  30 
  31 import jdk.internal.module.Modules;
  32 import jdk.jfr.Event;
  33 import jdk.jfr.FlightRecorder;
  34 import jdk.jfr.events.ActiveRecordingEvent;
  35 import jdk.jfr.events.ActiveSettingEvent;
  36 import jdk.jfr.events.ErrorThrownEvent;
  37 import jdk.jfr.events.ExceptionStatisticsEvent;
  38 import jdk.jfr.events.ExceptionThrownEvent;
  39 import jdk.jfr.events.FileForceEvent;
  40 import jdk.jfr.events.FileReadEvent;
  41 import jdk.jfr.events.FileWriteEvent;
  42 import jdk.jfr.events.SocketReadEvent;
  43 import jdk.jfr.events.SocketWriteEvent;
  44 import jdk.jfr.internal.JVM;
  45 import jdk.jfr.internal.LogLevel;
  46 import jdk.jfr.internal.LogTag;
  47 import jdk.jfr.internal.Logger;
  48 import jdk.jfr.internal.RequestEngine;
  49 import jdk.jfr.internal.SecuritySupport;
  50 import jdk.jfr.internal.Utils;
  51 
  52 public final class JDKEvents {
  53 
  54     private static final Class<?>[] eventClasses = {
  55         FileForceEvent.class,
  56         FileReadEvent.class,
  57         FileWriteEvent.class,
  58         SocketReadEvent.class,
  59         SocketWriteEvent.class,
  60         ExceptionThrownEvent.class,
  61         ExceptionStatisticsEvent.class,
  62         ErrorThrownEvent.class,
  63         ActiveSettingEvent.class,
  64         ActiveRecordingEvent.class
  65     };
  66 
  67     // This is a list of the classes with instrumentation code that should be applied.
  68     private static final Class<?>[] instrumentationClasses = new Class<?>[] {
  69         FileInputStreamInstrumentor.class,
  70         FileOutputStreamInstrumentor.class,
  71         RandomAccessFileInstrumentor.class,
  72         FileChannelImplInstrumentor.class,
  73         SocketInputStreamInstrumentor.class,
  74         SocketOutputStreamInstrumentor.class,
  75         SocketChannelImplInstrumentor.class
  76     };
  77 
  78     private static final Class<?>[] targetClasses = new Class<?>[instrumentationClasses.length];
  79     private static final JVM jvm = JVM.getJVM();
  80     private static final Runnable emitExceptionStatistics = JDKEvents::emitExceptionStatistics;
  81     private static boolean initializationTriggered;
  82 
  83     @SuppressWarnings("unchecked")
  84     public synchronized static void initialize() {
  85         try {
  86             if (initializationTriggered == false) {
  87                 Module jdkJfrModule = Event.class.getModule();
  88                 Module javaBaseModule = Object.class.getModule();
  89                 Modules.addReads(javaBaseModule, jdkJfrModule);
  90                 Modules.addExports(jdkJfrModule, Utils.EVENTS_PACKAGE_NAME, javaBaseModule);
  91                 Modules.addExports(jdkJfrModule, Utils.INSTRUMENT_PACKAGE_NAME, javaBaseModule);
  92                 Modules.addExports(jdkJfrModule, Utils.HANDLERS_PACKAGE_NAME, javaBaseModule);
  93                 for (Class<?> eventClass : eventClasses) {
  94                     SecuritySupport.registerEvent((Class<? extends Event>) eventClass);
  95                 }
  96                 initializationTriggered = true;
  97                 FlightRecorder.addPeriodicEvent(ExceptionStatisticsEvent.class, emitExceptionStatistics);
  98             }
  99         } catch (Exception e) {
 100             Logger.log(LogTag.JFR_SYSTEM, LogLevel.WARN, "Could not initialize JDK events. " + e.getMessage());
 101         }
 102     }
 103 
 104     public static void addInstrumentation() {
 105         try {
 106             List<Class<?>> list = new ArrayList<>();
 107             for (int i = 0; i < instrumentationClasses.length; i++) {
 108                 JIInstrumentationTarget tgt = instrumentationClasses[i].getAnnotation(JIInstrumentationTarget.class);
 109                 Class<?> clazz = Class.forName(tgt.value());
 110                 targetClasses[i] = clazz;
 111                 list.add(clazz);
 112             }
 113             list.add(java.lang.Throwable.class);
 114             list.add(java.lang.Error.class);
 115             Logger.log(LogTag.JFR_SYSTEM, LogLevel.INFO, "Retransformed JDK classes");
 116             jvm.retransformClasses(list.toArray(new Class<?>[list.size()]));
 117         } catch (Exception e) {
 118             Logger.log(LogTag.JFR_SYSTEM, LogLevel.WARN, "Could not add instrumentation for JDK events. " + e.getMessage());
 119         }
 120     }
 121 
 122     private static void emitExceptionStatistics() {
 123         ExceptionStatisticsEvent t = new ExceptionStatisticsEvent();
 124         t.throwables = ThrowableTracer.numThrowables();
 125         t.commit();
 126     }
 127 
 128     @SuppressWarnings("deprecation")
 129     public static byte[] retransformCallback(Class<?> klass, byte[] oldBytes) throws Throwable {
 130         if (java.lang.Throwable.class == klass) {
 131             Logger.log(LogTag.JFR_SYSTEM, LogLevel.TRACE, "Instrumenting java.lang.Throwable");
 132             return ConstructorTracerWriter.generateBytes(java.lang.Throwable.class, oldBytes);
 133         }
 134 
 135         if (java.lang.Error.class == klass) {
 136             Logger.log(LogTag.JFR_SYSTEM, LogLevel.TRACE, "Instrumenting java.lang.Error");
 137             return ConstructorTracerWriter.generateBytes(java.lang.Error.class, oldBytes);
 138         }
 139 
 140         for (int i = 0; i < targetClasses.length; i++) {
 141             if (targetClasses[i].equals(klass)) {
 142                 Class<?> c = instrumentationClasses[i];
 143                 Logger.log(LogTag.JFR_SYSTEM, LogLevel.TRACE, () -> "Processing instrumentation class: " + c);
 144                 return new JIClassInstrumentation(instrumentationClasses[i], klass, oldBytes).getNewBytes();
 145             }
 146         }
 147         return oldBytes;
 148     }
 149 
 150     public static void remove() {
 151         RequestEngine.removeHook(JDKEvents::emitExceptionStatistics);
 152     }
 153 }