1 /*
   2  * Copyright (c) 2016, 2019, 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.jfr.Event;
  32 import jdk.jfr.FlightRecorder;
  33 import jdk.jfr.events.ActiveRecordingEvent;
  34 import jdk.jfr.events.ActiveSettingEvent;
  35 import jdk.jfr.events.ErrorThrownEvent;
  36 import jdk.jfr.events.ExceptionStatisticsEvent;
  37 import jdk.jfr.events.ExceptionThrownEvent;
  38 import jdk.jfr.events.FileForceEvent;
  39 import jdk.jfr.events.FileReadEvent;
  40 import jdk.jfr.events.FileWriteEvent;
  41 import jdk.jfr.events.SocketReadEvent;
  42 import jdk.jfr.events.SocketWriteEvent;
  43 import jdk.jfr.internal.JVM;
  44 import jdk.jfr.internal.LogLevel;
  45 import jdk.jfr.internal.LogTag;
  46 import jdk.jfr.internal.Logger;
  47 import jdk.jfr.internal.RequestEngine;
  48 import jdk.jfr.internal.SecuritySupport;
  49 import jdk.jfr.internal.Utils;
  50 
  51 public final class JDKEvents {
  52 
  53     private static final Class<?>[] eventClasses = {
  54         FileForceEvent.class,
  55         FileReadEvent.class,
  56         FileWriteEvent.class,
  57         SocketReadEvent.class,
  58         SocketWriteEvent.class,
  59         ExceptionThrownEvent.class,
  60         ExceptionStatisticsEvent.class,
  61         ErrorThrownEvent.class,
  62         ActiveSettingEvent.class,
  63         ActiveRecordingEvent.class
  64     };
  65 
  66     // This is a list of the classes with instrumentation code that should be applied.
  67     private static final Class<?>[] instrumentationClasses = new Class<?>[] {
  68         FileInputStreamInstrumentor.class,
  69         FileOutputStreamInstrumentor.class,
  70         RandomAccessFileInstrumentor.class,
  71         FileChannelImplInstrumentor.class,
  72         SocketInputStreamInstrumentor.class,
  73         SocketOutputStreamInstrumentor.class,
  74         SocketChannelImplInstrumentor.class
  75     };
  76 
  77     private static final Class<?>[] targetClasses = new Class<?>[instrumentationClasses.length];
  78     private static final JVM jvm = JVM.getJVM();
  79     private static final Runnable emitExceptionStatistics = JDKEvents::emitExceptionStatistics;
  80     private static boolean initializationTriggered;
  81 
  82     @SuppressWarnings("unchecked")
  83     public synchronized static void initialize() {
  84         try {
  85             if (initializationTriggered == false) {
  86                 for (Class<?> eventClass : eventClasses) {
  87                     SecuritySupport.registerEvent((Class<? extends Event>) eventClass);
  88                 }
  89                 initializationTriggered = true;
  90                 FlightRecorder.addPeriodicEvent(ExceptionStatisticsEvent.class, emitExceptionStatistics);
  91             }
  92         } catch (Exception e) {
  93             Logger.log(LogTag.JFR_SYSTEM, LogLevel.WARN, "Could not initialize JDK events. " + e.getMessage());
  94         }
  95     }
  96 
  97     public static void addInstrumentation() {
  98         try {
  99             List<Class<?>> list = new ArrayList<>();
 100             for (int i = 0; i < instrumentationClasses.length; i++) {
 101                 JIInstrumentationTarget tgt = instrumentationClasses[i].getAnnotation(JIInstrumentationTarget.class);
 102                 Class<?> clazz = Class.forName(tgt.value());
 103                 targetClasses[i] = clazz;
 104                 list.add(clazz);
 105             }
 106             list.add(java.lang.Throwable.class);
 107             list.add(java.lang.Error.class);
 108             Logger.log(LogTag.JFR_SYSTEM, LogLevel.INFO, "Retransformed JDK classes");
 109             jvm.retransformClasses(list.toArray(new Class<?>[list.size()]));
 110         } catch (Exception e) {
 111             Logger.log(LogTag.JFR_SYSTEM, LogLevel.WARN, "Could not add instrumentation for JDK events. " + e.getMessage());
 112         }
 113     }
 114 
 115     private static void emitExceptionStatistics() {
 116         ExceptionStatisticsEvent t = new ExceptionStatisticsEvent();
 117         t.throwables = ThrowableTracer.numThrowables();
 118         t.commit();
 119     }
 120 
 121     @SuppressWarnings("deprecation")
 122     public static byte[] retransformCallback(Class<?> klass, byte[] oldBytes) throws Throwable {
 123         if (java.lang.Throwable.class == klass) {
 124             Logger.log(LogTag.JFR_SYSTEM, LogLevel.TRACE, "Instrumenting java.lang.Throwable");
 125             return ConstructorTracerWriter.generateBytes(java.lang.Throwable.class, oldBytes);
 126         }
 127 
 128         if (java.lang.Error.class == klass) {
 129             Logger.log(LogTag.JFR_SYSTEM, LogLevel.TRACE, "Instrumenting java.lang.Error");
 130             return ConstructorTracerWriter.generateBytes(java.lang.Error.class, oldBytes);
 131         }
 132 
 133         for (int i = 0; i < targetClasses.length; i++) {
 134             if (targetClasses[i].equals(klass)) {
 135                 Class<?> c = instrumentationClasses[i];
 136                 Logger.log(LogTag.JFR_SYSTEM, LogLevel.TRACE, () -> "Processing instrumentation class: " + c);
 137                 return new JIClassInstrumentation(instrumentationClasses[i], klass, oldBytes).getNewBytes();
 138             }
 139         }
 140         return oldBytes;
 141     }
 142 
 143     public static void remove() {
 144         RequestEngine.removeHook(JDKEvents::emitExceptionStatistics);
 145     }
 146 }