Path: blob/master/src/hotspot/share/jfr/instrumentation/jfrEventClassTransformer.cpp
41152 views
/*1* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "jvm.h"26#include "classfile/classFileParser.hpp"27#include "classfile/classFileStream.hpp"28#include "classfile/classLoadInfo.hpp"29#include "classfile/javaClasses.inline.hpp"30#include "classfile/moduleEntry.hpp"31#include "classfile/modules.hpp"32#include "classfile/stackMapTable.hpp"33#include "classfile/symbolTable.hpp"34#include "classfile/systemDictionary.hpp"35#include "classfile/verificationType.hpp"36#include "interpreter/bytecodes.hpp"37#include "jfr/instrumentation/jfrEventClassTransformer.hpp"38#include "jfr/jfr.hpp"39#include "jfr/jni/jfrJavaSupport.hpp"40#include "jfr/jni/jfrUpcalls.hpp"41#include "jfr/recorder/checkpoint/types/traceid/jfrTraceId.inline.hpp"42#include "jfr/support/jfrJdkJfrEvent.hpp"43#include "jfr/utilities/jfrBigEndian.hpp"44#include "jfr/writers/jfrBigEndianWriter.hpp"45#include "logging/log.hpp"46#include "memory/allocation.inline.hpp"47#include "memory/resourceArea.hpp"48#include "oops/array.hpp"49#include "oops/instanceKlass.hpp"50#include "oops/klass.inline.hpp"51#include "oops/method.hpp"52#include "prims/jvmtiRedefineClasses.hpp"53#include "runtime/handles.inline.hpp"54#include "runtime/jniHandles.hpp"55#include "runtime/os.hpp"56#include "runtime/thread.inline.hpp"57#include "utilities/exceptions.hpp"58#include "utilities/globalDefinitions.hpp"59#include "utilities/macros.hpp"6061static const u2 number_of_new_methods = 5;62static const u2 number_of_new_fields = 3;63static const int extra_stream_bytes = 0x280;64static const u2 invalid_cp_index = 0;6566static const char* utf8_constants[] = {67"Code", // 068"J", // 169"commit", // 270"eventHandler", // 371"duration", // 472"begin", // 573"()V", // 674"isEnabled", // 775"()Z", // 876"end", // 977"shouldCommit", // 1078"startTime", // 11 // LAST_REQUIRED_UTF879"Ljdk/jfr/internal/handlers/EventHandler;", // 1280"Ljava/lang/Object;", // 1381"<clinit>", // 1482"jdk/jfr/FlightRecorder", // 1583"register", // 1684"(Ljava/lang/Class;)V", // 1785"StackMapTable", // 1886"Exceptions", // 1987"LineNumberTable", // 2088"LocalVariableTable", // 2189"LocalVariableTypeTable", // 2290"RuntimeVisibleAnnotation", // 2391};9293enum utf8_req_symbols {94UTF8_REQ_Code,95UTF8_REQ_J_FIELD_DESC,96UTF8_REQ_commit,97UTF8_REQ_eventHandler,98UTF8_REQ_duration,99UTF8_REQ_begin,100UTF8_REQ_EMPTY_VOID_METHOD_DESC,101UTF8_REQ_isEnabled,102UTF8_REQ_EMPTY_BOOLEAN_METHOD_DESC,103UTF8_REQ_end,104UTF8_REQ_shouldCommit,105UTF8_REQ_startTime,106NOF_UTF8_REQ_SYMBOLS107};108109enum utf8_opt_symbols {110UTF8_OPT_eventHandler_FIELD_DESC = NOF_UTF8_REQ_SYMBOLS,111UTF8_OPT_LjavaLangObject,112UTF8_OPT_clinit,113UTF8_OPT_FlightRecorder,114UTF8_OPT_register,115UTF8_OPT_CLASS_VOID_METHOD_DESC,116UTF8_OPT_StackMapTable,117UTF8_OPT_Exceptions,118UTF8_OPT_LineNumberTable,119UTF8_OPT_LocalVariableTable,120UTF8_OPT_LocalVariableTypeTable,121UTF8_OPT_RuntimeVisibleAnnotation,122NOF_UTF8_SYMBOLS123};124125static u1 empty_void_method_code_attribute[] = {1260x0,1270x0,1280x0,1290xd, // attribute len1300x0,1310x0, // max stack1320x0,1330x1, // max locals1340x0,1350x0,1360x0,1370x1, // code length138Bytecodes::_return,1390x0,1400x0, // ex table len1410x0,1420x0 // attributes_count143};144145static u1 boolean_method_code_attribute[] = {1460x0,1470x0,1480x0,1490xe,1500x0,1510x1, // max stack1520x0,1530x1, // max locals1540x0,1550x0,1560x0,1570x2,158Bytecodes::_iconst_0,159Bytecodes::_ireturn,1600x0,1610x0, // ex table len1620x0,1630x0, // attributes_count164};165166// annotation processing support167168enum { // initial annotation layout169atype_off = 0, // utf8 such as 'Ljava/lang/annotation/Retention;'170count_off = 2, // u2 such as 1 (one value)171member_off = 4, // utf8 such as 'value'172tag_off = 6, // u1 such as 'c' (type) or 'e' (enum)173e_tag_val = 'e',174e_type_off = 7, // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'175e_con_off = 9, // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'176e_size = 11, // end of 'e' annotation177c_tag_val = 'c', // payload is type178c_con_off = 7, // utf8 payload, such as 'I'179c_size = 9, // end of 'c' annotation180s_tag_val = 's', // payload is String181s_con_off = 7, // utf8 payload, such as 'Ljava/lang/String;'182s_size = 9,183min_size = 6 // smallest possible size (zero members)184};185186static int skip_annotation_value(const address, int, int); // fwd decl187188// Skip an annotation. Return >=limit if there is any problem.189static int next_annotation_index(const address buffer, int limit, int index) {190assert(buffer != NULL, "invariant");191index += 2; // skip atype192if ((index += 2) >= limit) {193return limit;194}195int nof_members = JfrBigEndian::read<u2>(buffer + index - 2);196while (--nof_members >= 0 && index < limit) {197index += 2; // skip member198index = skip_annotation_value(buffer, limit, index);199}200return index;201}202203// Skip an annotation value. Return >=limit if there is any problem.204static int skip_annotation_value(const address buffer, int limit, int index) {205assert(buffer != NULL, "invariant");206// value := switch (tag:u1) {207// case B, C, I, S, Z, D, F, J, c: con:u2;208// case e: e_class:u2 e_name:u2;209// case s: s_con:u2;210// case [: do(nval:u2) {value};211// case @: annotation;212// case s: s_con:u2;213// }214if ((index += 1) >= limit) {215return limit;216}217const u1 tag = buffer[index - 1];218switch (tag) {219case 'B':220case 'C':221case 'I':222case 'S':223case 'Z':224case 'D':225case 'F':226case 'J':227case 'c':228case 's':229index += 2; // skip con or s_con230break;231case 'e':232index += 4; // skip e_class, e_name233break;234case '[':235{236if ((index += 2) >= limit) {237return limit;238}239int nof_values = JfrBigEndian::read<u2>(buffer + index - 2);240while (--nof_values >= 0 && index < limit) {241index = skip_annotation_value(buffer, limit, index);242}243}244break;245case '@':246index = next_annotation_index(buffer, limit, index);247break;248default:249return limit; // bad tag byte250}251return index;252}253254static const u2 number_of_elements_offset = (u2)2;255static const u2 element_name_offset = (u2)(number_of_elements_offset + 2);256static const u2 element_name_size = (u2)2;257static const u2 value_type_relative_offset = (u2)2;258static const u2 value_relative_offset = (u2)(value_type_relative_offset + 1);259260// see JVMS - 4.7.16. The RuntimeVisibleAnnotations Attribute261262class AnnotationElementIterator : public StackObj {263private:264const InstanceKlass* _ik;265const address _buffer;266const u2 _limit; // length of annotation267mutable u2 _current; // element268mutable u2 _next; // element269u2 value_index() const {270return JfrBigEndian::read<u2>(_buffer + _current + value_relative_offset);271}272273public:274AnnotationElementIterator(const InstanceKlass* ik, address buffer, u2 limit) : _ik(ik),275_buffer(buffer),276_limit(limit),277_current(element_name_offset),278_next(element_name_offset) {279assert(_buffer != NULL, "invariant");280assert(_next == element_name_offset, "invariant");281assert(_current == element_name_offset, "invariant");282}283284bool has_next() const {285return _next < _limit;286}287288void move_to_next() const {289assert(has_next(), "invariant");290_current = _next;291if (_next < _limit) {292_next = skip_annotation_value(_buffer, _limit, _next + element_name_size);293}294assert(_next <= _limit, "invariant");295assert(_current <= _limit, "invariant");296}297298u2 number_of_elements() const {299return JfrBigEndian::read<u2>(_buffer + number_of_elements_offset);300}301302const Symbol* name() const {303assert(_current < _next, "invariant");304return _ik->constants()->symbol_at(JfrBigEndian::read<u2>(_buffer + _current));305}306307char value_type() const {308return JfrBigEndian::read<u1>(_buffer + _current + value_type_relative_offset);309}310311jint read_int() const {312return _ik->constants()->int_at(value_index());313}314315bool read_bool() const {316return read_int() != 0;317}318};319320class AnnotationIterator : public StackObj {321private:322const InstanceKlass* _ik;323// ensure _limit field is declared before _buffer324u2 _limit; // length of annotations array325const address _buffer;326mutable u2 _current; // annotation327mutable u2 _next; // annotation328329public:330AnnotationIterator(const InstanceKlass* ik, AnnotationArray* ar) : _ik(ik),331_limit(ar != NULL ? ar->length() : 0),332_buffer(_limit > 2 ? ar->adr_at(2) : NULL),333_current(0),334_next(0) {335if (_buffer != NULL) {336_limit -= 2; // subtract sizeof(u2) number of annotations field337}338}339bool has_next() const {340return _next < _limit;341}342343void move_to_next() const {344assert(has_next(), "invariant");345_current = _next;346if (_next < _limit) {347_next = next_annotation_index(_buffer, _limit, _next);348}349assert(_next <= _limit, "invariant");350assert(_current <= _limit, "invariant");351}352const AnnotationElementIterator elements() const {353assert(_current < _next, "invariant");354return AnnotationElementIterator(_ik, _buffer + _current, _next - _current);355}356const Symbol* type() const {357assert(_buffer != NULL, "invariant");358assert(_current < _limit, "invariant");359return _ik->constants()->symbol_at(JfrBigEndian::read<u2>(_buffer + _current));360}361};362363static const char value_name[] = "value";364static bool has_annotation(const InstanceKlass* ik, const Symbol* annotation_type, bool& value) {365assert(annotation_type != NULL, "invariant");366AnnotationArray* class_annotations = ik->class_annotations();367if (class_annotations == NULL) {368return false;369}370371const AnnotationIterator annotation_iterator(ik, class_annotations);372while (annotation_iterator.has_next()) {373annotation_iterator.move_to_next();374if (annotation_iterator.type() == annotation_type) {375// target annotation found376static const Symbol* value_symbol =377SymbolTable::probe(value_name, sizeof value_name - 1);378assert(value_symbol != NULL, "invariant");379const AnnotationElementIterator element_iterator = annotation_iterator.elements();380while (element_iterator.has_next()) {381element_iterator.move_to_next();382if (value_symbol == element_iterator.name()) {383// "value" element384assert('Z' == element_iterator.value_type(), "invariant");385value = element_iterator.read_bool();386return true;387}388}389}390}391return false;392}393394// Evaluate to the value of the first found Symbol* annotation type.395// Searching moves upwards in the klass hierarchy in order to support396// inherited annotations in addition to the ability to override.397static bool annotation_value(const InstanceKlass* ik, const Symbol* annotation_type, bool& value) {398assert(ik != NULL, "invariant");399assert(annotation_type != NULL, "invariant");400assert(JdkJfrEvent::is_a(ik), "invariant");401if (has_annotation(ik, annotation_type, value)) {402return true;403}404InstanceKlass* const super = InstanceKlass::cast(ik->super());405return super != NULL && JdkJfrEvent::is_a(super) ? annotation_value(super, annotation_type, value) : false;406}407408static const char jdk_jfr_module_name[] = "jdk.jfr";409410static bool java_base_can_read_jdk_jfr() {411static bool can_read = false;412if (can_read) {413return true;414}415static Symbol* jdk_jfr_module_symbol = NULL;416if (jdk_jfr_module_symbol == NULL) {417jdk_jfr_module_symbol = SymbolTable::probe(jdk_jfr_module_name, sizeof jdk_jfr_module_name - 1);418if (jdk_jfr_module_symbol == NULL) {419return false;420}421}422assert(jdk_jfr_module_symbol != NULL, "invariant");423ModuleEntryTable* const table = Modules::get_module_entry_table(Handle());424assert(table != NULL, "invariant");425const ModuleEntry* const java_base_module = table->javabase_moduleEntry();426if (java_base_module == NULL) {427return false;428}429assert(java_base_module != NULL, "invariant");430ModuleEntry* const jdk_jfr_module = table->lookup_only(jdk_jfr_module_symbol);431if (jdk_jfr_module == NULL) {432return false;433}434assert(jdk_jfr_module != NULL, "invariant");435if (java_base_module->can_read(jdk_jfr_module)) {436can_read = true;437}438return can_read;439}440441static const char registered_constant[] = "Ljdk/jfr/Registered;";442443// Evaluate to the value of the first found "Ljdk/jfr/Registered;" annotation.444// Searching moves upwards in the klass hierarchy in order to support445// inherited annotations in addition to the ability to override.446static bool should_register_klass(const InstanceKlass* ik, bool& untypedEventHandler) {447assert(ik != NULL, "invariant");448assert(JdkJfrEvent::is_a(ik), "invariant");449assert(!untypedEventHandler, "invariant");450static const Symbol* registered_symbol = NULL;451if (registered_symbol == NULL) {452registered_symbol = SymbolTable::probe(registered_constant, sizeof registered_constant - 1);453if (registered_symbol == NULL) {454untypedEventHandler = true;455return false;456}457}458assert(registered_symbol != NULL, "invariant");459bool value = false; // to be set by annotation_value460untypedEventHandler = !(annotation_value(ik, registered_symbol, value) || java_base_can_read_jdk_jfr());461return value;462}463464/*465* Map an utf8 constant back to its CONSTANT_UTF8_INFO466*/467static u2 utf8_info_index(const InstanceKlass* ik, const Symbol* const target, TRAPS) {468assert(target != NULL, "invariant");469const ConstantPool* cp = ik->constants();470const int cp_len = cp->length();471for (u2 index = 1; index < cp_len; ++index) {472const constantTag tag = cp->tag_at(index);473if (tag.is_utf8()) {474const Symbol* const utf8_sym = cp->symbol_at(index);475assert(utf8_sym != NULL, "invariant");476if (utf8_sym == target) {477return index;478}479}480}481// not in constant pool482return invalid_cp_index;483}484485#ifdef ASSERT486static bool is_index_within_range(u2 index, u2 orig_cp_len, u2 new_cp_entries_len) {487return index > 0 && index < orig_cp_len + new_cp_entries_len;488}489#endif490491static u2 add_utf8_info(JfrBigEndianWriter& writer, const char* utf8_constant, u2 orig_cp_len, u2& new_cp_entries_len) {492assert(utf8_constant != NULL, "invariant");493writer.write<u1>(JVM_CONSTANT_Utf8);494writer.write_utf8_u2_len(utf8_constant);495assert(writer.is_valid(), "invariant");496// return index for the added utf8 info497return orig_cp_len + new_cp_entries_len++;498}499500static u2 add_method_ref_info(JfrBigEndianWriter& writer,501u2 cls_name_index,502u2 method_index,503u2 desc_index,504u2 orig_cp_len,505u2& number_of_new_constants,506TRAPS) {507assert(cls_name_index != invalid_cp_index, "invariant");508assert(method_index != invalid_cp_index, "invariant");509assert(desc_index != invalid_cp_index, "invariant");510assert(is_index_within_range(cls_name_index, orig_cp_len, number_of_new_constants), "invariant");511assert(is_index_within_range(method_index, orig_cp_len, number_of_new_constants), "invariant");512assert(is_index_within_range(desc_index, orig_cp_len, number_of_new_constants), "invariant");513writer.write<u1>(JVM_CONSTANT_Class);514writer.write<u2>(cls_name_index);515const u2 cls_entry_index = orig_cp_len + number_of_new_constants;516++number_of_new_constants;517writer.write<u1>(JVM_CONSTANT_NameAndType);518writer.write<u2>(method_index);519writer.write<u2>(desc_index);520const u2 nat_entry_index = orig_cp_len + number_of_new_constants;521++number_of_new_constants;522writer.write<u1>(JVM_CONSTANT_Methodref);523writer.write<u2>(cls_entry_index);524writer.write<u2>(nat_entry_index);525// post-increment number_of_new_constants526// value returned is the index to the added method_ref527return orig_cp_len + number_of_new_constants++;528}529530static u2 add_flr_register_method_constants(JfrBigEndianWriter& writer,531const u2* utf8_indexes,532u2 orig_cp_len,533u2& number_of_new_constants,534TRAPS) {535assert(utf8_indexes != NULL, "invariant");536return add_method_ref_info(writer,537utf8_indexes[UTF8_OPT_FlightRecorder],538utf8_indexes[UTF8_OPT_register],539utf8_indexes[UTF8_OPT_CLASS_VOID_METHOD_DESC],540orig_cp_len,541number_of_new_constants,542THREAD);543}544545/*546* field_info {547* u2 access_flags;548* u2 name_index;549* u2 descriptor_index;550* u2 attributes_count;551* attribute_info attributes[attributes_count];552* }553*/554static jlong add_field_info(JfrBigEndianWriter& writer, u2 name_index, u2 desc_index, bool is_static = false) {555assert(name_index != invalid_cp_index, "invariant");556assert(desc_index != invalid_cp_index, "invariant");557DEBUG_ONLY(const jlong start_offset = writer.current_offset();)558writer.write<u2>(JVM_ACC_SYNTHETIC | JVM_ACC_PRIVATE | (is_static ? JVM_ACC_STATIC : JVM_ACC_TRANSIENT)); // flags559writer.write(name_index);560writer.write(desc_index);561writer.write((u2)0x0); // attributes_count562assert(writer.is_valid(), "invariant");563DEBUG_ONLY(assert(start_offset + 8 == writer.current_offset(), "invariant");)564return writer.current_offset();565}566567static u2 add_field_infos(JfrBigEndianWriter& writer, const u2* utf8_indexes, bool untypedEventHandler) {568assert(utf8_indexes != NULL, "invariant");569add_field_info(writer,570utf8_indexes[UTF8_REQ_eventHandler],571untypedEventHandler ? utf8_indexes[UTF8_OPT_LjavaLangObject] : utf8_indexes[UTF8_OPT_eventHandler_FIELD_DESC],572true); // static573574add_field_info(writer,575utf8_indexes[UTF8_REQ_startTime],576utf8_indexes[UTF8_REQ_J_FIELD_DESC]);577578add_field_info(writer,579utf8_indexes[UTF8_REQ_duration],580utf8_indexes[UTF8_REQ_J_FIELD_DESC]);581582return number_of_new_fields;583}584585/*586* method_info {587* u2 access_flags;588* u2 name_index;589* u2 descriptor_index;590* u2 attributes_count;591* attribute_info attributes[attributes_count];592* }593*594* Code_attribute {595* u2 attribute_name_index;596* u4 attribute_length;597* u2 max_stack;598* u2 max_locals;599* u4 code_length;600* u1 code[code_length];601* u2 exception_table_length;602* { u2 start_pc;603* u2 end_pc;604* u2 handler_pc;605* u2 catch_type;606* } exception_table[exception_table_length];607* u2 attributes_count;608* attribute_info attributes[attributes_count];609* }610*/611612static jlong add_method_info(JfrBigEndianWriter& writer,613u2 name_index,614u2 desc_index,615u2 code_index,616const u1* const code,617const size_t code_len) {618assert(name_index > 0, "invariant");619assert(desc_index > 0, "invariant");620assert(code_index > 0, "invariant");621DEBUG_ONLY(const jlong start_offset = writer.current_offset();)622writer.write<u2>(JVM_ACC_SYNTHETIC | JVM_ACC_PUBLIC); // flags623writer.write(name_index);624writer.write(desc_index);625writer.write<u2>(0x1); // attributes_count ; 1 for "Code" attribute626assert(writer.is_valid(), "invariant");627DEBUG_ONLY(assert(start_offset + 8 == writer.current_offset(), "invariant");)628// Code attribute629writer.write(code_index); // "Code"630writer.write_bytes(code, code_len);631DEBUG_ONLY(assert((start_offset + 8 + 2 + (jlong)code_len) == writer.current_offset(), "invariant");)632return writer.current_offset();633}634635/*636* On return, the passed stream will be positioned637* just after the constant pool section in the classfile638* and the cp length is returned.639*640* Stream should come in at the start position.641*/642static u2 position_stream_after_cp(const ClassFileStream* stream) {643assert(stream != NULL, "invariant");644assert(stream->current_offset() == 0, "invariant");645stream->skip_u4_fast(2); // 8 bytes skipped646const u2 cp_len = stream->get_u2_fast();647assert(cp_len > 0, "invariant");648// now spin the stream position to just after the constant pool649for (u2 index = 1; index < cp_len; ++index) {650const u1 tag = stream->get_u1_fast(); // cp tag651switch (tag) {652case JVM_CONSTANT_Class:653case JVM_CONSTANT_String: {654stream->skip_u2_fast(1); // skip 2 bytes655continue;656}657case JVM_CONSTANT_Fieldref:658case JVM_CONSTANT_Methodref:659case JVM_CONSTANT_InterfaceMethodref:660case JVM_CONSTANT_Integer:661case JVM_CONSTANT_Float:662case JVM_CONSTANT_NameAndType:663case JVM_CONSTANT_InvokeDynamic: {664stream->skip_u4_fast(1); // skip 4 bytes665continue;666}667case JVM_CONSTANT_Long:668case JVM_CONSTANT_Double: {669stream->skip_u4_fast(2); // skip 8 bytes670// Skip entry following eigth-byte constant, see JVM book p. 98671++index;672continue;673}674case JVM_CONSTANT_Utf8: {675u2 utf8_length = stream->get_u2_fast();676stream->skip_u1_fast(utf8_length); // skip 2 + len bytes677continue;678}679case JVM_CONSTANT_MethodHandle:680case JVM_CONSTANT_MethodType: {681if (tag == JVM_CONSTANT_MethodHandle) {682stream->skip_u1_fast(1);683stream->skip_u2_fast(1); // skip 3 bytes684}685else if (tag == JVM_CONSTANT_MethodType) {686stream->skip_u2_fast(1); // skip 3 bytes687}688}689continue;690case JVM_CONSTANT_Dynamic:691stream->skip_u2_fast(1);692stream->skip_u2_fast(1);693continue;694default:695assert(false, "error in skip logic!");696break;697} // end switch(tag)698}699return cp_len;700}701702/*703* On return, the passed stream will be positioned704* just after the fields section in the classfile705* and the number of fields will be returned.706*707* Stream should come in positioned just before fields_count708*/709static u2 position_stream_after_fields(const ClassFileStream* stream) {710assert(stream != NULL, "invariant");711assert(stream->current_offset() > 0, "invariant");712// fields len713const u2 orig_fields_len = stream->get_u2_fast();714// fields715for (u2 i = 0; i < orig_fields_len; ++i) {716stream->skip_u2_fast(3);717const u2 attrib_info_len = stream->get_u2_fast();718for (u2 j = 0; j < attrib_info_len; ++j) {719stream->skip_u2_fast(1);720const u4 attrib_len = stream->get_u4_fast();721stream->skip_u1_fast(attrib_len);722}723}724return orig_fields_len;725}726727/*728* On return, the passed stream will be positioned729* just after the methods section in the classfile730* and the number of methods will be returned.731*732* Stream should come in positioned just before methods_count733*/734static u2 position_stream_after_methods(JfrBigEndianWriter& writer,735const ClassFileStream* stream,736const u2* utf8_indexes,737bool register_klass,738const Method* clinit_method,739u4& orig_method_len_offset) {740assert(stream != NULL, "invariant");741assert(stream->current_offset() > 0, "invariant");742assert(utf8_indexes != NULL, "invariant");743// We will come back to this location when we744// know how many methods there will be.745writer.reserve(sizeof(u2));746const u2 orig_methods_len = stream->get_u2_fast();747// Move copy position past original method_count748// in order to not copy the original count749orig_method_len_offset += sizeof(u2);750for (u2 i = 0; i < orig_methods_len; ++i) {751const u4 method_offset = stream->current_offset();752stream->skip_u2_fast(1); // Access Flags753const u2 name_index = stream->get_u2_fast(); // Name index754stream->skip_u2_fast(1); // Descriptor index755const u2 attributes_count = stream->get_u2_fast();756for (u2 j = 0; j < attributes_count; ++j) {757stream->skip_u2_fast(1);758const u4 attrib_len = stream->get_u4_fast();759stream->skip_u1_fast(attrib_len);760}761if (clinit_method != NULL && name_index == clinit_method->name_index()) {762// The method just parsed is an existing <clinit> method.763// If the class has the @Registered(false) annotation, i.e. marking a class764// for opting out from automatic registration, then we do not need to do anything.765if (!register_klass) {766continue;767}768// Automatic registration with the jfr system is acccomplished769// by pre-pending code to the <clinit> method of the class.770// We will need to re-create a new <clinit> in a later step.771// For now, ensure that this method is excluded from the methods772// being copied.773writer.write_bytes(stream->buffer() + orig_method_len_offset,774method_offset - orig_method_len_offset);775assert(writer.is_valid(), "invariant");776777// Update copy position to skip copy of <clinit> method778orig_method_len_offset = stream->current_offset();779}780}781return orig_methods_len;782}783784static u2 add_method_infos(JfrBigEndianWriter& writer, const u2* utf8_indexes) {785assert(utf8_indexes != NULL, "invariant");786add_method_info(writer,787utf8_indexes[UTF8_REQ_begin],788utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC],789utf8_indexes[UTF8_REQ_Code],790empty_void_method_code_attribute,791sizeof(empty_void_method_code_attribute));792793assert(writer.is_valid(), "invariant");794795add_method_info(writer,796utf8_indexes[UTF8_REQ_end],797utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC],798utf8_indexes[UTF8_REQ_Code],799empty_void_method_code_attribute,800sizeof(empty_void_method_code_attribute));801802assert(writer.is_valid(), "invariant");803804add_method_info(writer,805utf8_indexes[UTF8_REQ_commit],806utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC],807utf8_indexes[UTF8_REQ_Code],808empty_void_method_code_attribute,809sizeof(empty_void_method_code_attribute));810811assert(writer.is_valid(), "invariant");812813add_method_info(writer,814utf8_indexes[UTF8_REQ_isEnabled],815utf8_indexes[UTF8_REQ_EMPTY_BOOLEAN_METHOD_DESC],816utf8_indexes[UTF8_REQ_Code],817boolean_method_code_attribute,818sizeof(boolean_method_code_attribute));819820assert(writer.is_valid(), "invariant");821822add_method_info(writer,823utf8_indexes[UTF8_REQ_shouldCommit],824utf8_indexes[UTF8_REQ_EMPTY_BOOLEAN_METHOD_DESC],825utf8_indexes[UTF8_REQ_Code],826boolean_method_code_attribute,827sizeof(boolean_method_code_attribute));828assert(writer.is_valid(), "invariant");829return number_of_new_methods;830}831832static void adjust_exception_table(JfrBigEndianWriter& writer, u2 bci_adjustment_offset, const Method* method, TRAPS) {833const u2 ex_table_length = method != NULL ? (u2)method->exception_table_length() : 0;834writer.write<u2>(ex_table_length); // Exception table length835if (ex_table_length > 0) {836assert(method != NULL, "invariant");837const ExceptionTableElement* const ex_elements = method->exception_table_start();838for (int i = 0; i < ex_table_length; ++i) {839assert(ex_elements != NULL, "invariant");840writer.write<u2>(ex_elements[i].start_pc + bci_adjustment_offset);841writer.write<u2>(ex_elements[i].end_pc + bci_adjustment_offset);842writer.write<u2>(ex_elements[i].handler_pc + bci_adjustment_offset);843writer.write<u2>(ex_elements[i].catch_type_index); // no adjustment844}845}846}847848enum StackMapFrameTypes {849SAME_FRAME_BEGIN = 0,850SAME_FRAME_END = 63,851SAME_LOCALS_1_STACK_ITEM_FRAME_BEGIN = 64,852SAME_LOCALS_1_STACK_ITEM_FRAME_END = 127,853SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247,854CHOP_FRAME_BEGIN = 248,855CHOP_FRAME_END = 250,856SAME_FRAME_EXTENDED = 251,857APPEND_FRAME_BEGIN = 252,858APPEND_FRAME_END = 254,859FULL_FRAME = 255860};861862static void adjust_stack_map(JfrBigEndianWriter& writer,863Array<u1>* stack_map,864const u2* utf8_indexes,865u2 bci_adjustment_offset,866TRAPS) {867assert(stack_map != NULL, "invariant");868assert(utf8_indexes != NULL, "invariant");869writer.write<u2>(utf8_indexes[UTF8_OPT_StackMapTable]);870const jlong stack_map_attrib_len_offset = writer.current_offset();871writer.reserve(sizeof(u4));872StackMapStream stream(stack_map);873const u2 stack_map_entries = stream.get_u2(THREAD);874// number of entries875writer.write<u2>(stack_map_entries); // new stack map entry added876const u1 frame_type = stream.get_u1(THREAD);877// SAME_FRAME and SAME_LOCALS_1_STACK_ITEM_FRAME encode878// their offset_delta into the actual frame type itself.879// If such a frame type is the first frame, then we transform880// it to a SAME_FRAME_EXTENDED or a SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED frame.881// This is done in order to not overflow frame types accidentally882// when adjusting the offset_delta. In changing the frame types,883// we can work with an explicit u2 offset_delta field (like the other frame types)884if (frame_type <= SAME_FRAME_END) {885writer.write<u1>(SAME_FRAME_EXTENDED);886writer.write<u2>(frame_type + bci_adjustment_offset);887} else if (frame_type >= SAME_LOCALS_1_STACK_ITEM_FRAME_BEGIN &&888frame_type <= SAME_LOCALS_1_STACK_ITEM_FRAME_END) {889writer.write<u1>(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED);890writer.write<u2>((frame_type - SAME_LOCALS_1_STACK_ITEM_FRAME_BEGIN) + bci_adjustment_offset);891} else if (frame_type >= SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {892// SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED to FULL_FRAME893// has a u2 offset_delta field894writer.write<u1>(frame_type);895writer.write<u2>(stream.get_u2(THREAD) + bci_adjustment_offset);896} else {897assert(false, "stackMapFrame type is invalid");898}899900while (!stream.at_end()) {901writer.write<u1>(stream.get_u1(THREAD));902}903904u4 stack_map_attrib_len = writer.current_offset() - stack_map_attrib_len_offset;905// the stack_map_table_attributes_length value is exclusive906stack_map_attrib_len -= sizeof(u4);907writer.write_at_offset(stack_map_attrib_len, stack_map_attrib_len_offset);908}909910static void adjust_line_number_table(JfrBigEndianWriter& writer,911const u2* utf8_indexes,912u4 bci_adjustement_offset,913const Method* method,914TRAPS) {915assert(utf8_indexes != NULL, "invariant");916assert(method != NULL, "invariant");917assert(method->has_linenumber_table(), "invariant");918writer.write(utf8_indexes[UTF8_OPT_LineNumberTable]);919const jlong lnt_attributes_length_offset = writer.current_offset();920writer.reserve(sizeof(u4));921const jlong lnt_attributes_entries_offset = writer.current_offset();922writer.reserve(sizeof(u2));923u1* lnt = method->compressed_linenumber_table();924CompressedLineNumberReadStream lnt_stream(lnt);925u2 line_number_table_entries = 0;926while (lnt_stream.read_pair()) {927++line_number_table_entries;928const u2 bci = (u2)lnt_stream.bci();929writer.write<u2>(bci + (u2)bci_adjustement_offset);930writer.write<u2>((u2)lnt_stream.line());931}932writer.write_at_offset(line_number_table_entries, lnt_attributes_entries_offset);933u4 lnt_table_attributes_len = writer.current_offset() - lnt_attributes_length_offset;934// the line_number_table_attributes_length value is exclusive935lnt_table_attributes_len -= sizeof(u4);936writer.write_at_offset(lnt_table_attributes_len, lnt_attributes_length_offset);937}938939// returns the number of lvtt entries940static u2 adjust_local_variable_table(JfrBigEndianWriter& writer,941const u2* utf8_indexes,942u2 bci_adjustment_offset,943const Method* method,944TRAPS) {945assert(utf8_indexes != NULL, "invariant");946assert(method != NULL, "invariant");947assert(method->has_localvariable_table(), "invariant");948writer.write<u2>(utf8_indexes[UTF8_OPT_LocalVariableTable]);949const jlong lvt_attributes_length_offset = writer.current_offset();950writer.reserve(sizeof(u4));951const int lvt_len = method->localvariable_table_length();952writer.write<u2>((u2)lvt_len);953const LocalVariableTableElement* table = method->localvariable_table_start();954assert(table != NULL, "invariant");955u2 num_lvtt_entries = 0;956for (int i = 0; i < lvt_len; ++i) {957writer.write<u2>(table[i].start_bci + bci_adjustment_offset);958writer.write<u2>(table[i].length);959writer.write<u2>(table[i].name_cp_index);960writer.write<u2>(table[i].descriptor_cp_index);961writer.write<u2>(table[i].slot);962if (table[i].signature_cp_index > 0) {963++num_lvtt_entries;964}965}966u4 lvt_table_attributes_len = writer.current_offset() - lvt_attributes_length_offset;967// the lvt_table_attributes_length value is exclusive968lvt_table_attributes_len -= sizeof(u4);969writer.write_at_offset(lvt_table_attributes_len, lvt_attributes_length_offset);970return num_lvtt_entries;971}972973static void adjust_local_variable_type_table(JfrBigEndianWriter& writer,974const u2* utf8_indexes,975u2 bci_adjustment_offset,976u2 num_lvtt_entries,977const Method* method,978TRAPS) {979assert(num_lvtt_entries > 0, "invariant");980writer.write<u2>(utf8_indexes[UTF8_OPT_LocalVariableTypeTable]);981const jlong lvtt_attributes_length_offset = writer.current_offset();982writer.reserve(sizeof(u4));983writer.write<u2>(num_lvtt_entries);984const LocalVariableTableElement* table = method->localvariable_table_start();985assert(table != NULL, "invariant");986const int lvt_len = method->localvariable_table_length();987for (int i = 0; i < lvt_len; ++i) {988if (table[i].signature_cp_index > 0) {989writer.write<u2>(table[i].start_bci + bci_adjustment_offset);990writer.write<u2>(table[i].length);991writer.write<u2>(table[i].name_cp_index);992writer.write<u2>(table[i].signature_cp_index);993writer.write<u2>(table[i].slot);994}995}996u4 lvtt_table_attributes_len = writer.current_offset() - lvtt_attributes_length_offset;997// the lvtt_table_attributes_length value is exclusive998lvtt_table_attributes_len -= sizeof(u4);999writer.write_at_offset(lvtt_table_attributes_len, lvtt_attributes_length_offset);1000}10011002static void adjust_code_attributes(JfrBigEndianWriter& writer,1003const u2* utf8_indexes,1004u2 bci_adjustment_offset,1005const Method* clinit_method,1006TRAPS) {1007// "Code" attributes1008assert(utf8_indexes != NULL, "invariant");1009const jlong code_attributes_offset = writer.current_offset();1010writer.reserve(sizeof(u2));1011u2 number_of_code_attributes = 0;1012if (clinit_method != NULL) {1013Array<u1>* stack_map = clinit_method->stackmap_data();1014if (stack_map != NULL) {1015++number_of_code_attributes;1016adjust_stack_map(writer, stack_map, utf8_indexes, bci_adjustment_offset, THREAD);1017assert(writer.is_valid(), "invariant");1018}1019if (clinit_method != NULL && clinit_method->has_linenumber_table()) {1020++number_of_code_attributes;1021adjust_line_number_table(writer, utf8_indexes, bci_adjustment_offset, clinit_method, THREAD);1022assert(writer.is_valid(), "invariant");1023}1024if (clinit_method != NULL && clinit_method->has_localvariable_table()) {1025++number_of_code_attributes;1026const u2 num_of_lvtt_entries = adjust_local_variable_table(writer, utf8_indexes, bci_adjustment_offset, clinit_method, THREAD);1027assert(writer.is_valid(), "invariant");1028if (num_of_lvtt_entries > 0) {1029++number_of_code_attributes;1030adjust_local_variable_type_table(writer, utf8_indexes, bci_adjustment_offset, num_of_lvtt_entries, clinit_method, THREAD);1031assert(writer.is_valid(), "invariant");1032}1033}1034}10351036// Store the number of code_attributes1037writer.write_at_offset(number_of_code_attributes, code_attributes_offset);1038}10391040static jlong insert_clinit_method(const InstanceKlass* ik,1041const ClassFileParser& parser,1042JfrBigEndianWriter& writer,1043u2 orig_constant_pool_len,1044const u2* utf8_indexes,1045const u2 register_method_ref_index,1046const Method* clinit_method,1047TRAPS) {1048assert(utf8_indexes != NULL, "invariant");1049// The injected code length is always this value.1050// This is to ensure that padding can be done1051// where needed and to simplify size calculations.1052static const u2 injected_code_length = 8;1053const u2 name_index = utf8_indexes[UTF8_OPT_clinit];1054assert(name_index != invalid_cp_index, "invariant");1055const u2 desc_index = utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC];1056const u2 max_stack = MAX2(clinit_method != NULL ? clinit_method->verifier_max_stack() : 1, 1);1057const u2 max_locals = MAX2(clinit_method != NULL ? clinit_method->max_locals() : 0, 0);1058const u2 orig_bytecodes_length = clinit_method != NULL ? (u2)clinit_method->code_size() : 0;1059const address orig_bytecodes = clinit_method != NULL ? clinit_method->code_base() : NULL;1060const u2 new_code_length = injected_code_length + orig_bytecodes_length;1061DEBUG_ONLY(const jlong start_offset = writer.current_offset();)1062writer.write<u2>(JVM_ACC_STATIC); // flags1063writer.write<u2>(name_index);1064writer.write<u2>(desc_index);1065writer.write<u2>((u2)0x1); // attributes_count // "Code"1066assert(writer.is_valid(), "invariant");1067DEBUG_ONLY(assert(start_offset + 8 == writer.current_offset(), "invariant");)1068// "Code" attribute1069writer.write<u2>(utf8_indexes[UTF8_REQ_Code]); // "Code"1070const jlong code_attribute_length_offset = writer.current_offset();1071writer.reserve(sizeof(u4));1072writer.write<u2>(max_stack); // max stack1073writer.write<u2>(max_locals); // max locals1074writer.write<u4>((u4)new_code_length); // code length10751076/* BEGIN CLINIT CODE */10771078// Note the use of ldc_w here instead of ldc.1079// This is to handle all values of "this_class_index"1080writer.write<u1>((u1)Bytecodes::_ldc_w);1081writer.write<u2>((u2)parser.this_class_index()); // load constant "this class"1082writer.write<u1>((u1)Bytecodes::_invokestatic);1083// invoke "FlightRecorder.register(Ljava/lang/Class;")1084writer.write<u2>(register_method_ref_index);1085if (clinit_method == NULL) {1086writer.write<u1>((u1)Bytecodes::_nop);1087writer.write<u1>((u1)Bytecodes::_return);1088} else {1089// If we are pre-pending to original code,1090// do padding to minimize disruption to the original.1091// It might have dependencies on 4-byte boundaries1092// i.e. lookupswitch and tableswitch instructions1093writer.write<u1>((u1)Bytecodes::_nop);1094writer.write<u1>((u1)Bytecodes::_nop);1095// insert original clinit code1096writer.write_bytes(orig_bytecodes, orig_bytecodes_length);1097}10981099/* END CLINIT CODE */11001101assert(writer.is_valid(), "invariant");1102adjust_exception_table(writer, injected_code_length, clinit_method, THREAD);1103assert(writer.is_valid(), "invariant");1104adjust_code_attributes(writer, utf8_indexes, injected_code_length, clinit_method, THREAD);1105assert(writer.is_valid(), "invariant");1106u4 code_attribute_len = writer.current_offset() - code_attribute_length_offset;1107// the code_attribute_length value is exclusive1108code_attribute_len -= sizeof(u4);1109writer.write_at_offset(code_attribute_len, code_attribute_length_offset);1110return writer.current_offset();1111}11121113// Caller needs ResourceMark1114static ClassFileStream* create_new_bytes_for_event_klass(const InstanceKlass* ik, const ClassFileParser& parser, TRAPS) {1115DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));1116static const u2 public_final_flag_mask = JVM_ACC_PUBLIC | JVM_ACC_FINAL;1117const ClassFileStream* const orig_stream = parser.clone_stream();1118const int orig_stream_length = orig_stream->length();1119// allocate an identically sized buffer1120u1* const new_buffer = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, u1, orig_stream_length);1121if (new_buffer == NULL) {1122return NULL;1123}1124assert(new_buffer != NULL, "invariant");1125// memcpy the entire [B1126memcpy(new_buffer, orig_stream->buffer(), orig_stream_length);1127const u2 orig_cp_len = position_stream_after_cp(orig_stream);1128assert(orig_cp_len > 0, "invariant");1129assert(orig_stream->current_offset() > 0, "invariant");1130orig_stream->skip_u2_fast(3); // access_flags, this_class_index, super_class_index1131const u2 iface_len = orig_stream->get_u2_fast();1132orig_stream->skip_u2_fast(iface_len);1133// fields len1134const u2 orig_fields_len = orig_stream->get_u2_fast();1135// fields1136for (u2 i = 0; i < orig_fields_len; ++i) {1137orig_stream->skip_u2_fast(3);1138const u2 attrib_info_len = orig_stream->get_u2_fast();1139for (u2 j = 0; j < attrib_info_len; ++j) {1140orig_stream->skip_u2_fast(1);1141const u4 attrib_len = orig_stream->get_u4_fast();1142orig_stream->skip_u1_fast(attrib_len);1143}1144}1145// methods1146const u2 orig_methods_len = orig_stream->get_u2_fast();1147for (u2 i = 0; i < orig_methods_len; ++i) {1148const u4 access_flag_offset = orig_stream->current_offset();1149const u2 flags = orig_stream->get_u2_fast();1150// Rewrite JVM_ACC_FINAL -> JVM_ACC_PUBLIC1151if (public_final_flag_mask == flags) {1152JfrBigEndianWriter accessflagsrewriter(new_buffer + access_flag_offset, sizeof(u2));1153accessflagsrewriter.write<u2>(JVM_ACC_PUBLIC);1154assert(accessflagsrewriter.is_valid(), "invariant");1155}1156orig_stream->skip_u2_fast(2);1157const u2 attributes_count = orig_stream->get_u2_fast();1158for (u2 j = 0; j < attributes_count; ++j) {1159orig_stream->skip_u2_fast(1);1160const u4 attrib_len = orig_stream->get_u4_fast();1161orig_stream->skip_u1_fast(attrib_len);1162}1163}1164return new ClassFileStream(new_buffer, orig_stream_length, NULL, ClassFileStream::verify);1165}11661167// Attempt to locate an existing UTF8_INFO mapping the utf8_constant.1168// If no UTF8_INFO exists, add (append) a new one to the constant pool.1169static u2 find_or_add_utf8_info(JfrBigEndianWriter& writer,1170const InstanceKlass* ik,1171const char* const utf8_constant,1172u2 orig_cp_len,1173u2& added_cp_entries,1174TRAPS) {1175assert(utf8_constant != NULL, "invariant");1176TempNewSymbol utf8_sym = SymbolTable::new_symbol(utf8_constant);1177// lookup existing1178const int utf8_orig_idx = utf8_info_index(ik, utf8_sym, THREAD);1179if (utf8_orig_idx != invalid_cp_index) {1180// existing constant pool entry found1181return utf8_orig_idx;1182}1183// no existing match, need to add a new utf8 cp entry1184assert(invalid_cp_index == utf8_orig_idx, "invariant");1185// add / append new1186return add_utf8_info(writer, utf8_constant, orig_cp_len, added_cp_entries);1187}11881189/*1190* This routine will resolve the required utf8_constants array1191* to their constant pool indexes (mapping to their UTF8_INFO's)1192* Only if a constant is actually needed and does not already exist1193* will it be added.1194*1195* The passed in indexes array will be populated with the resolved indexes.1196* The number of newly added constant pool entries is returned.1197*/1198static u2 resolve_utf8_indexes(JfrBigEndianWriter& writer,1199const InstanceKlass* ik,1200u2* const utf8_indexes,1201u2 orig_cp_len,1202const Method* clinit_method,1203bool register_klass,1204bool untypedEventHandler,1205TRAPS) {1206assert(utf8_indexes != NULL, "invariant");1207u2 added_cp_entries = 0;1208// resolve all required symbols1209for (u2 index = 0; index < NOF_UTF8_REQ_SYMBOLS; ++index) {1210utf8_indexes[index] = find_or_add_utf8_info(writer, ik, utf8_constants[index], orig_cp_len, added_cp_entries, THREAD);1211}12121213// resolve optional constants1214utf8_indexes[UTF8_OPT_eventHandler_FIELD_DESC] = untypedEventHandler ? invalid_cp_index :1215find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_eventHandler_FIELD_DESC], orig_cp_len, added_cp_entries, THREAD);12161217utf8_indexes[UTF8_OPT_LjavaLangObject] = untypedEventHandler ?1218find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_LjavaLangObject], orig_cp_len, added_cp_entries, THREAD) : invalid_cp_index;12191220if (register_klass) {1221utf8_indexes[UTF8_OPT_clinit] =1222find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_clinit], orig_cp_len, added_cp_entries, THREAD);1223utf8_indexes[UTF8_OPT_FlightRecorder] =1224find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_FlightRecorder], orig_cp_len, added_cp_entries, THREAD);1225utf8_indexes[UTF8_OPT_register] =1226find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_register], orig_cp_len, added_cp_entries, THREAD);1227utf8_indexes[UTF8_OPT_CLASS_VOID_METHOD_DESC] =1228find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_CLASS_VOID_METHOD_DESC], orig_cp_len, added_cp_entries, THREAD);1229} else {1230utf8_indexes[UTF8_OPT_clinit] = invalid_cp_index;1231utf8_indexes[UTF8_OPT_FlightRecorder] = invalid_cp_index;1232utf8_indexes[UTF8_OPT_register] = invalid_cp_index;1233utf8_indexes[UTF8_OPT_CLASS_VOID_METHOD_DESC] = invalid_cp_index;1234}12351236if (clinit_method != NULL && clinit_method->has_stackmap_table()) {1237utf8_indexes[UTF8_OPT_StackMapTable] =1238find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_StackMapTable], orig_cp_len, added_cp_entries, THREAD);1239} else {1240utf8_indexes[UTF8_OPT_StackMapTable] = invalid_cp_index;1241}12421243if (clinit_method != NULL && clinit_method->has_linenumber_table()) {1244utf8_indexes[UTF8_OPT_LineNumberTable] =1245find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_LineNumberTable], orig_cp_len, added_cp_entries, THREAD);1246} else {1247utf8_indexes[UTF8_OPT_LineNumberTable] = invalid_cp_index;1248}12491250if (clinit_method != NULL && clinit_method->has_localvariable_table()) {1251utf8_indexes[UTF8_OPT_LocalVariableTable] =1252find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_LocalVariableTable], orig_cp_len, added_cp_entries, THREAD);1253utf8_indexes[UTF8_OPT_LocalVariableTypeTable] =1254find_or_add_utf8_info(writer, ik, utf8_constants[UTF8_OPT_LocalVariableTypeTable], orig_cp_len, added_cp_entries, THREAD);1255} else {1256utf8_indexes[UTF8_OPT_LocalVariableTable] = invalid_cp_index;1257utf8_indexes[UTF8_OPT_LocalVariableTypeTable] = invalid_cp_index;1258}12591260return added_cp_entries;1261}12621263static u1* new_bytes_for_lazy_instrumentation(const InstanceKlass* ik,1264const ClassFileParser& parser,1265jint& size_of_new_bytes,1266TRAPS) {1267assert(ik != NULL, "invariant");1268// If the class already has a clinit method1269// we need to take that into account1270const Method* clinit_method = ik->class_initializer();1271bool untypedEventHandler = false;1272const bool register_klass = should_register_klass(ik, untypedEventHandler);1273const ClassFileStream* const orig_stream = parser.clone_stream();1274const int orig_stream_size = orig_stream->length();1275assert(orig_stream->current_offset() == 0, "invariant");1276const u2 orig_cp_len = position_stream_after_cp(orig_stream);1277assert(orig_cp_len > 0, "invariant");1278assert(orig_stream->current_offset() > 0, "invariant");1279// Dimension and allocate a working byte buffer1280// to be used in building up a modified class [B.1281const jint new_buffer_size = extra_stream_bytes + orig_stream_size;1282u1* const new_buffer = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, u1, new_buffer_size);1283if (new_buffer == NULL) {1284log_error(jfr, system) ("Thread local allocation (native) for " SIZE_FORMAT1285" bytes failed in JfrClassAdapter::on_klass_creation", (size_t)new_buffer_size);1286return NULL;1287}1288assert(new_buffer != NULL, "invariant");1289// [B wrapped in a big endian writer1290JfrBigEndianWriter writer(new_buffer, new_buffer_size);1291assert(writer.current_offset() == 0, "invariant");1292const u4 orig_access_flag_offset = orig_stream->current_offset();1293// Copy original stream from the beginning up to AccessFlags1294// This means the original constant pool contents are copied unmodified1295writer.write_bytes(orig_stream->buffer(), orig_access_flag_offset);1296assert(writer.is_valid(), "invariant");1297assert(writer.current_offset() == (intptr_t)orig_access_flag_offset, "invariant"); // same positions1298// Our writer now sits just after the last original constant pool entry.1299// I.e. we are in a good position to append new constant pool entries1300// This array will contain the resolved indexes1301// in order to reference UTF8_INFO's needed1302u2 utf8_indexes[NOF_UTF8_SYMBOLS];1303// Resolve_utf8_indexes will be conservative in attempting to1304// locate an existing UTF8_INFO; it will only append constants1305// that is absolutely required1306u2 number_of_new_constants =1307resolve_utf8_indexes(writer, ik, utf8_indexes, orig_cp_len, clinit_method, register_klass, untypedEventHandler, THREAD);1308// UTF8_INFO entries now added to the constant pool1309// In order to invoke a method we would need additional1310// constants, JVM_CONSTANT_Class, JVM_CONSTANT_NameAndType1311// and JVM_CONSTANT_Methodref.1312const u2 flr_register_method_ref_index =1313register_klass ?1314add_flr_register_method_constants(writer,1315utf8_indexes,1316orig_cp_len,1317number_of_new_constants,1318THREAD) : invalid_cp_index;13191320// New constant pool entries added and all UTF8_INFO indexes resolved1321// Now update the class file constant_pool_count with an updated count1322writer.write_at_offset<u2>(orig_cp_len + number_of_new_constants, 8);1323assert(writer.is_valid(), "invariant");1324orig_stream->skip_u2_fast(3); // access_flags, this_class_index, super_class_index1325const u2 iface_len = orig_stream->get_u2_fast(); // interfaces1326orig_stream->skip_u2_fast(iface_len);1327const u4 orig_fields_len_offset = orig_stream->current_offset();1328// Copy from AccessFlags up to and including interfaces1329writer.write_bytes(orig_stream->buffer() + orig_access_flag_offset,1330orig_fields_len_offset - orig_access_flag_offset);1331assert(writer.is_valid(), "invariant");1332const jlong new_fields_len_offset = writer.current_offset();1333const u2 orig_fields_len = position_stream_after_fields(orig_stream);1334u4 orig_method_len_offset = orig_stream->current_offset();1335// Copy up to and including fields1336writer.write_bytes(orig_stream->buffer() + orig_fields_len_offset, orig_method_len_offset - orig_fields_len_offset);1337assert(writer.is_valid(), "invariant");1338// We are sitting just after the original number of field_infos1339// so this is a position where we can add (append) new field_infos1340const u2 number_of_new_fields = add_field_infos(writer, utf8_indexes, untypedEventHandler);1341assert(writer.is_valid(), "invariant");1342const jlong new_method_len_offset = writer.current_offset();1343// Additional field_infos added, update classfile fields_count1344writer.write_at_offset<u2>(orig_fields_len + number_of_new_fields, new_fields_len_offset);1345assert(writer.is_valid(), "invariant");1346// Our current location is now at classfile methods_count1347const u2 orig_methods_len = position_stream_after_methods(writer,1348orig_stream,1349utf8_indexes,1350register_klass,1351clinit_method,1352orig_method_len_offset);1353const u4 orig_attributes_count_offset = orig_stream->current_offset();1354// Copy existing methods1355writer.write_bytes(orig_stream->buffer() + orig_method_len_offset, orig_attributes_count_offset - orig_method_len_offset);1356assert(writer.is_valid(), "invariant");1357// We are sitting just after the original number of method_infos1358// so this is a position where we can add (append) new method_infos1359u2 number_of_new_methods = add_method_infos(writer, utf8_indexes);13601361// We have just added the new methods.1362//1363// What about the state of <clinit>?1364// We would need to do:1365// 1. Nothing (@Registered(false) annotation)1366// 2. Build up a new <clinit> - and if the original class already contains a <clinit>,1367// merging will be neccessary.1368//1369if (register_klass) {1370insert_clinit_method(ik, parser, writer, orig_cp_len, utf8_indexes, flr_register_method_ref_index, clinit_method, THREAD);1371}1372number_of_new_methods += clinit_method != NULL ? 0 : register_klass ? 1 : 0;1373// Update classfile methods_count1374writer.write_at_offset<u2>(orig_methods_len + number_of_new_methods, new_method_len_offset);1375assert(writer.is_valid(), "invariant");1376// Copy last remaining bytes1377writer.write_bytes(orig_stream->buffer() + orig_attributes_count_offset, orig_stream_size - orig_attributes_count_offset);1378assert(writer.is_valid(), "invariant");1379assert(writer.current_offset() > orig_stream->length(), "invariant");1380size_of_new_bytes = (jint)writer.current_offset();1381return new_buffer;1382}13831384static void log_pending_exception(oop throwable) {1385assert(throwable != NULL, "invariant");1386oop msg = java_lang_Throwable::message(throwable);1387if (msg != NULL) {1388char* text = java_lang_String::as_utf8_string(msg);1389if (text != NULL) {1390log_error(jfr, system) ("%s", text);1391}1392}1393}13941395static bool should_force_instrumentation() {1396return !JfrOptionSet::allow_event_retransforms() || JfrEventClassTransformer::is_force_instrumentation();1397}13981399static ClassFileStream* create_new_bytes_for_subklass(const InstanceKlass* ik, const ClassFileParser& parser, JavaThread* t) {1400assert(JdkJfrEvent::is_a(ik), "invariant");1401DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(t));1402jint size_of_new_bytes = 0;1403const u1* new_bytes = new_bytes_for_lazy_instrumentation(ik, parser, size_of_new_bytes, t);1404if (new_bytes == NULL) {1405return NULL;1406}1407assert(new_bytes != NULL, "invariant");1408assert(size_of_new_bytes > 0, "invariant");14091410bool force_instrumentation = should_force_instrumentation();1411if (Jfr::is_recording() || force_instrumentation) {1412jint size_instrumented_data = 0;1413unsigned char* instrumented_data = NULL;1414const jclass super = (jclass)JNIHandles::make_local(ik->super()->java_mirror());1415JfrUpcalls::new_bytes_eager_instrumentation(JfrTraceId::load_raw(ik),1416force_instrumentation,1417super,1418size_of_new_bytes,1419new_bytes,1420&size_instrumented_data,1421&instrumented_data,1422t);1423if (t->has_pending_exception()) {1424log_pending_exception(t->pending_exception());1425t->clear_pending_exception();1426return NULL;1427}1428assert(instrumented_data != NULL, "invariant");1429assert(size_instrumented_data > 0, "invariant");1430return new ClassFileStream(instrumented_data, size_instrumented_data, NULL, ClassFileStream::verify);1431}1432return new ClassFileStream(new_bytes, size_of_new_bytes, NULL, ClassFileStream::verify);1433}14341435static bool cache_bytes(InstanceKlass* ik, ClassFileStream* new_stream, InstanceKlass* new_ik, TRAPS) {1436assert(ik != NULL, "invariant");1437assert(new_ik != NULL, "invariant");1438assert(new_ik->name() != NULL, "invariant");1439assert(new_stream != NULL, "invariant");1440assert(!HAS_PENDING_EXCEPTION, "invariant");1441static const bool can_retransform = JfrOptionSet::allow_retransforms();1442if (!can_retransform) {1443return true;1444}1445const jint stream_len = new_stream->length();1446JvmtiCachedClassFileData* p =1447(JvmtiCachedClassFileData*)NEW_C_HEAP_ARRAY_RETURN_NULL(u1, offset_of(JvmtiCachedClassFileData, data) + stream_len, mtInternal);1448if (p == NULL) {1449log_error(jfr, system)("Allocation using C_HEAP_ARRAY for " SIZE_FORMAT1450" bytes failed in JfrClassAdapter::on_klass_creation", (size_t)offset_of(JvmtiCachedClassFileData, data) + stream_len);1451return false;1452}1453p->length = stream_len;1454memcpy(p->data, new_stream->buffer(), stream_len);1455new_ik->set_cached_class_file(p);1456JvmtiCachedClassFileData* const cached_class_data = ik->get_cached_class_file();1457if (cached_class_data != NULL) {1458os::free(cached_class_data);1459ik->set_cached_class_file(NULL);1460}1461return true;1462}14631464static InstanceKlass* create_new_instance_klass(InstanceKlass* ik, ClassFileStream* stream, TRAPS) {1465assert(stream != NULL, "invariant");1466ResourceMark rm(THREAD);1467ClassLoaderData* const cld = ik->class_loader_data();1468Handle pd(THREAD, ik->protection_domain());1469Symbol* const class_name = ik->name();1470const char* const klass_name = class_name != NULL ? class_name->as_C_string() : "";1471ClassLoadInfo cl_info(pd);1472ClassFileParser new_parser(stream,1473class_name,1474cld,1475&cl_info,1476ClassFileParser::INTERNAL, // internal visibility1477THREAD);1478if (HAS_PENDING_EXCEPTION) {1479log_pending_exception(PENDING_EXCEPTION);1480CLEAR_PENDING_EXCEPTION;1481return NULL;1482}1483const ClassInstanceInfo* cl_inst_info = cl_info.class_hidden_info_ptr();1484InstanceKlass* const new_ik = new_parser.create_instance_klass(false, *cl_inst_info, THREAD);1485if (HAS_PENDING_EXCEPTION) {1486log_pending_exception(PENDING_EXCEPTION);1487CLEAR_PENDING_EXCEPTION;1488return NULL;1489}1490assert(new_ik != NULL, "invariant");1491assert(new_ik->name() != NULL, "invariant");1492assert(strncmp(ik->name()->as_C_string(), new_ik->name()->as_C_string(), strlen(ik->name()->as_C_string())) == 0, "invariant");1493return cache_bytes(ik, stream, new_ik, THREAD) ? new_ik : NULL;1494}14951496static void rewrite_klass_pointer(InstanceKlass*& ik, InstanceKlass* new_ik, ClassFileParser& parser, TRAPS) {1497assert(ik != NULL, "invariant");1498assert(new_ik != NULL, "invariant");1499assert(new_ik->name() != NULL, "invariant");1500assert(JdkJfrEvent::is(new_ik) || JdkJfrEvent::is_subklass(new_ik), "invariant");1501assert(!HAS_PENDING_EXCEPTION, "invariant");1502// assign original InstanceKlass* back onto "its" parser object for proper destruction1503parser.set_klass_to_deallocate(ik);1504// now rewrite original pointer to newly created InstanceKlass1505ik = new_ik;1506}15071508static bool is_retransforming(const InstanceKlass* ik, TRAPS) {1509assert(ik != NULL, "invariant");1510assert(JdkJfrEvent::is_a(ik), "invariant");1511Symbol* const name = ik->name();1512assert(name != NULL, "invariant");1513Handle class_loader(THREAD, ik->class_loader());1514Handle protection_domain(THREAD, ik->protection_domain());1515return SystemDictionary::find_instance_klass(name, class_loader, protection_domain) != NULL;1516}15171518// target for JFR_ON_KLASS_CREATION hook1519void JfrEventClassTransformer::on_klass_creation(InstanceKlass*& ik, ClassFileParser& parser, TRAPS) {1520assert(ik != NULL, "invariant");1521if (JdkJfrEvent::is(ik)) {1522ResourceMark rm(THREAD);1523HandleMark hm(THREAD);1524ClassFileStream* new_stream = create_new_bytes_for_event_klass(ik, parser, THREAD);1525if (new_stream == NULL) {1526log_error(jfr, system)("JfrClassAdapter: unable to create ClassFileStream");1527return;1528}1529assert(new_stream != NULL, "invariant");1530InstanceKlass* new_ik = create_new_instance_klass(ik, new_stream, THREAD);1531if (new_ik == NULL) {1532log_error(jfr, system)("JfrClassAdapter: unable to create InstanceKlass");1533return;1534}1535assert(new_ik != NULL, "invariant");1536// We now need to explicitly tag the replaced klass as the jdk.jfr.Event klass1537assert(!JdkJfrEvent::is(new_ik), "invariant");1538JdkJfrEvent::tag_as(new_ik);1539assert(JdkJfrEvent::is(new_ik), "invariant");1540rewrite_klass_pointer(ik, new_ik, parser, THREAD);1541return;1542}1543assert(JdkJfrEvent::is_subklass(ik), "invariant");1544if (ik->is_abstract() || is_retransforming(ik, THREAD)) {1545// abstract and scratch classes are not instrumented1546return;1547}1548ResourceMark rm(THREAD);1549HandleMark hm(THREAD);1550ClassFileStream* const new_stream = create_new_bytes_for_subklass(ik, parser, THREAD);1551if (NULL == new_stream) {1552log_error(jfr, system)("JfrClassAdapter: unable to create ClassFileStream");1553return;1554}1555assert(new_stream != NULL, "invariant");1556InstanceKlass* new_ik = create_new_instance_klass(ik, new_stream, THREAD);1557if (new_ik == NULL) {1558log_error(jfr, system)("JfrClassAdapter: unable to create InstanceKlass");1559return;1560}1561assert(new_ik != NULL, "invariant");1562// would have been tagged already as a subklass during the normal process of traceid assignment1563assert(JdkJfrEvent::is_subklass(new_ik), "invariant");1564traceid id = ik->trace_id();1565ik->set_trace_id(0);1566new_ik->set_trace_id(id);1567rewrite_klass_pointer(ik, new_ik, parser, THREAD);1568}15691570static bool _force_instrumentation = false;1571void JfrEventClassTransformer::set_force_instrumentation(bool force_instrumentation) {1572_force_instrumentation = force_instrumentation;1573}15741575bool JfrEventClassTransformer::is_force_instrumentation() {1576return _force_instrumentation;1577}157815791580