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