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