1 /*
   2  * Copyright (c) 2013, 2023, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciMethodData.hpp"
  27 #include "ci/ciReplay.hpp"
  28 #include "ci/ciSymbol.hpp"
  29 #include "ci/ciKlass.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/javaClasses.hpp"
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "compiler/compilationPolicy.hpp"
  35 #include "compiler/compileBroker.hpp"
  36 #include "compiler/compilerDefinitions.inline.hpp"
  37 #include "interpreter/linkResolver.hpp"
  38 #include "jvm.h"
  39 #include "memory/allocation.inline.hpp"
  40 #include "memory/oopFactory.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "oops/constantPool.inline.hpp"
  43 #include "oops/cpCache.inline.hpp"
  44 #include "oops/fieldStreams.inline.hpp"
  45 #include "oops/klass.inline.hpp"
  46 #include "oops/method.inline.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/resolvedIndyEntry.hpp"
  49 #include "prims/jvmtiExport.hpp"
  50 #include "prims/methodHandles.hpp"
  51 #include "runtime/fieldDescriptor.inline.hpp"
  52 #include "runtime/globals_extension.hpp"
  53 #include "runtime/handles.inline.hpp"
  54 #include "runtime/java.hpp"
  55 #include "runtime/jniHandles.inline.hpp"
  56 #include "runtime/threads.hpp"
  57 #include "utilities/copy.hpp"
  58 #include "utilities/macros.hpp"
  59 #include "utilities/utf8.hpp"
  60 
  61 // ciReplay
  62 
  63 typedef struct _ciMethodDataRecord {
  64   const char* _klass_name;
  65   const char* _method_name;
  66   const char* _signature;
  67 
  68   int _state;
  69   int _invocation_counter;
  70 
  71   intptr_t* _data;
  72   char*     _orig_data;
  73   Klass**   _classes;
  74   Method**  _methods;
  75   int*      _classes_offsets;
  76   int*      _methods_offsets;
  77   int       _data_length;
  78   int       _orig_data_length;
  79   int       _classes_length;
  80   int       _methods_length;
  81 } ciMethodDataRecord;
  82 
  83 typedef struct _ciMethodRecord {
  84   const char* _klass_name;
  85   const char* _method_name;
  86   const char* _signature;
  87 
  88   int _instructions_size;
  89   int _interpreter_invocation_count;
  90   int _interpreter_throwout_count;
  91   int _invocation_counter;
  92   int _backedge_counter;
  93 } ciMethodRecord;
  94 
  95 typedef struct _ciInstanceKlassRecord {
  96   const InstanceKlass* _klass;
  97   jobject _java_mirror; // Global handle to java mirror to prevent unloading
  98 } ciInstanceKlassRecord;
  99 
 100 typedef struct _ciInlineRecord {
 101   const char* _klass_name;
 102   const char* _method_name;
 103   const char* _signature;
 104 
 105   int _inline_depth;
 106   int _inline_bci;
 107   bool _inline_late;
 108 } ciInlineRecord;
 109 
 110 class  CompileReplay;
 111 static CompileReplay* replay_state;
 112 
 113 class CompileReplay : public StackObj {
 114  private:
 115   FILE*   _stream;
 116   Thread* _thread;
 117   Handle  _protection_domain;
 118   bool    _protection_domain_initialized;
 119   Handle  _loader;
 120   int     _version;
 121 
 122   GrowableArray<ciMethodRecord*>     _ci_method_records;
 123   GrowableArray<ciMethodDataRecord*> _ci_method_data_records;
 124   GrowableArray<ciInstanceKlassRecord*> _ci_instance_klass_records;
 125 
 126   // Use pointer because we may need to return inline records
 127   // without destroying them.
 128   GrowableArray<ciInlineRecord*>*    _ci_inline_records;
 129 
 130   const char* _error_message;
 131 
 132   char* _bufptr;
 133   char* _buffer;
 134   int   _buffer_length;
 135 
 136   // "compile" data
 137   ciKlass* _iklass;
 138   Method*  _imethod;
 139   int      _entry_bci;
 140   int      _comp_level;
 141 
 142  public:
 143   CompileReplay(const char* filename, TRAPS) {
 144     _thread = THREAD;
 145     _loader = Handle(_thread, SystemDictionary::java_system_loader());
 146     _protection_domain = Handle();
 147     _protection_domain_initialized = false;
 148 
 149     _stream = os::fopen(filename, "rt");
 150     if (_stream == nullptr) {
 151       fprintf(stderr, "ERROR: Can't open replay file %s\n", filename);
 152     }
 153 
 154     _ci_inline_records = nullptr;
 155     _error_message = nullptr;
 156 
 157     _buffer_length = 32;
 158     _buffer = NEW_RESOURCE_ARRAY(char, _buffer_length);
 159     _bufptr = _buffer;
 160 
 161     _imethod = nullptr;
 162     _iklass  = nullptr;
 163     _entry_bci  = 0;
 164     _comp_level = 0;
 165     _version = 0;
 166 
 167     test();
 168   }
 169 
 170   ~CompileReplay() {
 171     if (_stream != nullptr) fclose(_stream);
 172   }
 173 
 174   void test() {
 175     strcpy(_buffer, "1 2 foo 4 bar 0x9 \"this is it\"");
 176     _bufptr = _buffer;
 177     assert(parse_int("test") == 1, "what");
 178     assert(parse_int("test") == 2, "what");
 179     assert(strcmp(parse_string(), "foo") == 0, "what");
 180     assert(parse_int("test") == 4, "what");
 181     assert(strcmp(parse_string(), "bar") == 0, "what");
 182     assert(parse_intptr_t("test") == 9, "what");
 183     assert(strcmp(parse_quoted_string(), "this is it") == 0, "what");
 184   }
 185 
 186   bool had_error() {
 187     return _error_message != nullptr || _thread->has_pending_exception();
 188   }
 189 
 190   bool can_replay() {
 191     return !(_stream == nullptr || had_error());
 192   }
 193 
 194   void report_error(const char* msg) {
 195     _error_message = msg;
 196   }
 197 
 198   int parse_int(const char* label) {
 199     if (had_error()) {
 200       return 0;
 201     }
 202 
 203     int v = 0;
 204     int read;
 205     if (sscanf(_bufptr, "%i%n", &v, &read) != 1) {
 206       report_error(label);
 207     } else {
 208       _bufptr += read;
 209     }
 210     return v;
 211   }
 212 
 213   intptr_t parse_intptr_t(const char* label) {
 214     if (had_error()) {
 215       return 0;
 216     }
 217 
 218     intptr_t v = 0;
 219     int read;
 220     if (sscanf(_bufptr, INTPTR_FORMAT "%n", &v, &read) != 1) {
 221       report_error(label);
 222     } else {
 223       _bufptr += read;
 224     }
 225     return v;
 226   }
 227 
 228   void skip_ws() {
 229     // Skip any leading whitespace
 230     while (*_bufptr == ' ' || *_bufptr == '\t') {
 231       _bufptr++;
 232     }
 233   }
 234 
 235   // Ignore the rest of the line
 236   void skip_remaining() {
 237     _bufptr = &_bufptr[strlen(_bufptr)]; // skip ahead to terminator
 238   }
 239 
 240   char* scan_and_terminate(char delim) {
 241     char* str = _bufptr;
 242     while (*_bufptr != delim && *_bufptr != '\0') {
 243       _bufptr++;
 244     }
 245     if (*_bufptr != '\0') {
 246       *_bufptr++ = '\0';
 247     }
 248     if (_bufptr == str) {
 249       // nothing here
 250       return nullptr;
 251     }
 252     return str;
 253   }
 254 
 255   char* parse_string() {
 256     if (had_error()) return nullptr;
 257 
 258     skip_ws();
 259     return scan_and_terminate(' ');
 260   }
 261 
 262   char* parse_quoted_string() {
 263     if (had_error()) return nullptr;
 264 
 265     skip_ws();
 266 
 267     if (*_bufptr == '"') {
 268       _bufptr++;
 269       return scan_and_terminate('"');
 270     } else {
 271       return scan_and_terminate(' ');
 272     }
 273   }
 274 
 275   char* parse_escaped_string() {
 276     char* result = parse_quoted_string();
 277     if (result != nullptr) {
 278       unescape_string(result);
 279     }
 280     return result;
 281   }
 282 
 283   // Look for the tag 'tag' followed by an
 284   bool parse_tag_and_count(const char* tag, int& length) {
 285     const char* t = parse_string();
 286     if (t == nullptr) {
 287       return false;
 288     }
 289 
 290     if (strcmp(tag, t) != 0) {
 291       report_error(tag);
 292       return false;
 293     }
 294     length = parse_int("parse_tag_and_count");
 295     return !had_error();
 296   }
 297 
 298   // Parse a sequence of raw data encoded as bytes and return the
 299   // resulting data.
 300   char* parse_data(const char* tag, int& length) {
 301     int read_size = 0;
 302     if (!parse_tag_and_count(tag, read_size)) {
 303       return nullptr;
 304     }
 305 
 306     int actual_size = sizeof(MethodData::CompilerCounters);
 307     char *result = NEW_RESOURCE_ARRAY(char, actual_size);
 308     int i = 0;
 309     if (read_size != actual_size) {
 310       tty->print_cr("Warning: ciMethodData parsing sees MethodData size %i in file, current is %i", read_size,
 311                     actual_size);
 312       // Replay serializes the entire MethodData, but the data is at the end.
 313       // If the MethodData instance size has changed, we can pad or truncate in the beginning
 314       int padding = actual_size - read_size;
 315       if (padding > 0) {
 316         // pad missing data with zeros
 317         tty->print_cr("- Padding MethodData");
 318         for (; i < padding; i++) {
 319           result[i] = 0;
 320         }
 321       } else if (padding < 0) {
 322         // drop some data
 323         tty->print_cr("- Truncating MethodData");
 324         for (int j = 0; j < -padding; j++) {
 325           int val = parse_int("data");
 326           // discard val
 327         }
 328       }
 329     }
 330 
 331     assert(i < actual_size, "At least some data must remain to be copied");
 332     for (; i < actual_size; i++) {
 333       int val = parse_int("data");
 334       result[i] = val;
 335     }
 336     length = actual_size;
 337     return result;
 338   }
 339 
 340   // Parse a standard chunk of data emitted as:
 341   //   'tag' <length> # # ...
 342   // Where each # is an intptr_t item
 343   intptr_t* parse_intptr_data(const char* tag, int& length) {
 344     if (!parse_tag_and_count(tag, length)) {
 345       return nullptr;
 346     }
 347 
 348     intptr_t* result = NEW_RESOURCE_ARRAY(intptr_t, length);
 349     for (int i = 0; i < length; i++) {
 350       skip_ws();
 351       intptr_t val = parse_intptr_t("data");
 352       result[i] = val;
 353     }
 354     return result;
 355   }
 356 
 357   // Parse a possibly quoted version of a symbol into a symbolOop
 358   Symbol* parse_symbol() {
 359     const char* str = parse_escaped_string();
 360     if (str != nullptr) {
 361       Symbol* sym = SymbolTable::new_symbol(str);
 362       return sym;
 363     }
 364     return nullptr;
 365   }
 366 
 367   bool parse_terminator() {
 368     char* terminator = parse_string();
 369     if (terminator != nullptr && strcmp(terminator, ";") == 0) {
 370       return true;
 371     }
 372     return false;
 373   }
 374 
 375   // Parse a special hidden klass location syntax
 376   // syntax: @bci <klass> <name> <signature> <bci> <location>* ;
 377   // syntax: @cpi <klass> <cpi> <location>* ;
 378   Klass* parse_cp_ref(TRAPS) {
 379     JavaThread* thread = THREAD;
 380     oop obj = nullptr;
 381     char* ref = parse_string();
 382     if (strcmp(ref, "bci") == 0) {
 383       Method* m = parse_method(CHECK_NULL);
 384       if (m == nullptr) {
 385         return nullptr;
 386       }
 387 
 388       InstanceKlass* ik = m->method_holder();
 389       const constantPoolHandle cp(Thread::current(), ik->constants());
 390 
 391       // invokedynamic or invokehandle
 392 
 393       methodHandle caller(Thread::current(), m);
 394       int bci = parse_int("bci");
 395       if (m->validate_bci(bci) != bci) {
 396         report_error("bad bci");
 397         return nullptr;
 398       }
 399 
 400       ik->link_class(CHECK_NULL);
 401 
 402       Bytecode_invoke bytecode = Bytecode_invoke_check(caller, bci);
 403       if (!Bytecodes::is_defined(bytecode.code()) || !bytecode.is_valid()) {
 404         report_error("no invoke found at bci");
 405         return nullptr;
 406       }
 407       bytecode.verify();
 408       int index = bytecode.index();
 409 
 410       ConstantPoolCacheEntry* cp_cache_entry = nullptr;
 411       CallInfo callInfo;
 412       Bytecodes::Code bc = bytecode.invoke_code();
 413       LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, bc, CHECK_NULL);
 414 
 415       // ResolvedIndyEntry and ConstantPoolCacheEntry must currently coexist.
 416       // To address this, the variables below contain the values that *might*
 417       // be used to avoid multiple blocks of similar code. When CPCE is obsoleted
 418       // these can be removed
 419       oop appendix = nullptr;
 420       Method* adapter_method = nullptr;
 421       int pool_index = 0;
 422 
 423       if (bytecode.is_invokedynamic()) {
 424         index = cp->decode_invokedynamic_index(index);
 425         cp->cache()->set_dynamic_call(callInfo, index);
 426 
 427         appendix = cp->resolved_reference_from_indy(index);
 428         adapter_method = cp->resolved_indy_entry_at(index)->method();
 429         pool_index = cp->resolved_indy_entry_at(index)->constant_pool_index();
 430       } else if (bytecode.is_invokehandle()) {
 431 #ifdef ASSERT
 432         Klass* holder = cp->klass_ref_at(index, bytecode.code(), CHECK_NULL);
 433         Symbol* name = cp->name_ref_at(index, bytecode.code());
 434         assert(MethodHandles::is_signature_polymorphic_name(holder, name), "");
 435 #endif
 436         cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
 437         cp_cache_entry->set_method_handle(cp, callInfo);
 438 
 439         appendix = cp_cache_entry->appendix_if_resolved(cp);
 440         adapter_method = cp_cache_entry->f1_as_method();
 441         pool_index = cp_cache_entry->constant_pool_index();
 442       } else {
 443         report_error("no dynamic invoke found");
 444         return nullptr;
 445       }
 446       char* dyno_ref = parse_string();
 447       if (strcmp(dyno_ref, "<appendix>") == 0) {
 448         obj = appendix;
 449       } else if (strcmp(dyno_ref, "<adapter>") == 0) {
 450         if (!parse_terminator()) {
 451           report_error("no dynamic invoke found");
 452           return nullptr;
 453         }
 454         Method* adapter = adapter_method;
 455         if (adapter == nullptr) {
 456           report_error("no adapter found");
 457           return nullptr;
 458         }
 459         return adapter->method_holder();
 460       } else if (strcmp(dyno_ref, "<bsm>") == 0) {
 461         BootstrapInfo bootstrap_specifier(cp, pool_index, index);
 462         obj = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), CHECK_NULL);
 463       } else {
 464         report_error("unrecognized token");
 465         return nullptr;
 466       }
 467     } else {
 468       // constant pool ref (MethodHandle)
 469       if (strcmp(ref, "cpi") != 0) {
 470         report_error("unexpected token");
 471         return nullptr;
 472       }
 473 
 474       Klass* k = parse_klass(CHECK_NULL);
 475       if (k == nullptr) {
 476         return nullptr;
 477       }
 478       InstanceKlass* ik = InstanceKlass::cast(k);
 479       const constantPoolHandle cp(Thread::current(), ik->constants());
 480 
 481       int cpi = parse_int("cpi");
 482 
 483       if (cpi >= cp->length()) {
 484         report_error("bad cpi");
 485         return nullptr;
 486       }
 487       if (!cp->tag_at(cpi).is_method_handle()) {
 488         report_error("no method handle found at cpi");
 489         return nullptr;
 490       }
 491       ik->link_class(CHECK_NULL);
 492       obj = cp->resolve_possibly_cached_constant_at(cpi, CHECK_NULL);
 493     }
 494     if (obj == nullptr) {
 495       report_error("null cp object found");
 496       return nullptr;
 497     }
 498     Klass* k = nullptr;
 499     skip_ws();
 500     // loop: read fields
 501     char* field = nullptr;
 502     do {
 503       field = parse_string();
 504       if (field == nullptr) {
 505         report_error("no field found");
 506         return nullptr;
 507       }
 508       if (strcmp(field, ";") == 0) {
 509         break;
 510       }
 511       // raw Method*
 512       if (strcmp(field, "<vmtarget>") == 0) {
 513         Method* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
 514         k = (vmtarget == nullptr) ? nullptr : vmtarget->method_holder();
 515         if (k == nullptr) {
 516           report_error("null vmtarget found");
 517           return nullptr;
 518         }
 519         if (!parse_terminator()) {
 520           report_error("missing terminator");
 521           return nullptr;
 522         }
 523         return k;
 524       }
 525       obj = ciReplay::obj_field(obj, field);
 526       // array
 527       if (obj != nullptr && obj->is_objArray()) {
 528         objArrayOop arr = (objArrayOop)obj;
 529         int index = parse_int("index");
 530         if (index >= arr->length()) {
 531           report_error("bad array index");
 532           return nullptr;
 533         }
 534         obj = arr->obj_at(index);
 535       }
 536     } while (obj != nullptr);
 537     if (obj == nullptr) {
 538       report_error("null field found");
 539       return nullptr;
 540     }
 541     k = obj->klass();
 542     return k;
 543   }
 544 
 545   // Parse a valid klass name and look it up
 546   // syntax: <name>
 547   // syntax: <constant pool ref>
 548   Klass* parse_klass(TRAPS) {
 549     skip_ws();
 550     // check for constant pool object reference (for a dynamic/hidden class)
 551     bool cp_ref = (*_bufptr == '@');
 552     if (cp_ref) {
 553       ++_bufptr;
 554       Klass* k = parse_cp_ref(CHECK_NULL);
 555       if (k != nullptr && !k->is_hidden()) {
 556         report_error("expected hidden class");
 557         return nullptr;
 558       }
 559       return k;
 560     }
 561     char* str = parse_escaped_string();
 562     Symbol* klass_name = SymbolTable::new_symbol(str);
 563     if (klass_name != nullptr) {
 564       Klass* k = nullptr;
 565       if (_iklass != nullptr) {
 566         k = (Klass*)_iklass->find_klass(ciSymbol::make(klass_name->as_C_string()))->constant_encoding();
 567       } else {
 568         k = SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 569       }
 570       if (HAS_PENDING_EXCEPTION) {
 571         oop throwable = PENDING_EXCEPTION;
 572         java_lang_Throwable::print(throwable, tty);
 573         tty->cr();
 574         report_error(str);
 575         if (ReplayIgnoreInitErrors) {
 576           CLEAR_PENDING_EXCEPTION;
 577           _error_message = nullptr;
 578         }
 579         return nullptr;
 580       }
 581       return k;
 582     }
 583     return nullptr;
 584   }
 585 
 586   // Lookup a klass
 587   Klass* resolve_klass(const char* klass, TRAPS) {
 588     Symbol* klass_name = SymbolTable::new_symbol(klass);
 589     return SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 590   }
 591 
 592   // Parse the standard tuple of <klass> <name> <signature>
 593   Method* parse_method(TRAPS) {
 594     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK_NULL);
 595     if (k == nullptr) {
 596       report_error("Can't find holder klass");
 597       return nullptr;
 598     }
 599     Symbol* method_name = parse_symbol();
 600     Symbol* method_signature = parse_symbol();
 601     Method* m = k->find_method(method_name, method_signature);
 602     if (m == nullptr) {
 603       report_error("Can't find method");
 604     }
 605     return m;
 606   }
 607 
 608   int get_line(int c) {
 609     int buffer_pos = 0;
 610     while(c != EOF) {
 611       if (buffer_pos + 1 >= _buffer_length) {
 612         int new_length = _buffer_length * 2;
 613         // Next call will throw error in case of OOM.
 614         _buffer = REALLOC_RESOURCE_ARRAY(char, _buffer, _buffer_length, new_length);
 615         _buffer_length = new_length;
 616       }
 617       if (c == '\n') {
 618         c = getc(_stream); // get next char
 619         break;
 620       } else if (c == '\r') {
 621         // skip LF
 622       } else {
 623         _buffer[buffer_pos++] = c;
 624       }
 625       c = getc(_stream);
 626     }
 627     // null terminate it, reset the pointer
 628     _buffer[buffer_pos] = '\0'; // NL or EOF
 629     _bufptr = _buffer;
 630     return c;
 631   }
 632 
 633   // Process each line of the replay file executing each command until
 634   // the file ends.
 635   void process(TRAPS) {
 636     int line_no = 1;
 637     int c = getc(_stream);
 638     while(c != EOF) {
 639       c = get_line(c);
 640       process_command(false, THREAD);
 641       if (had_error()) {
 642         int pos = _bufptr - _buffer + 1;
 643         tty->print_cr("Error while parsing line %d at position %d: %s\n", line_no, pos, _error_message);
 644         if (ReplayIgnoreInitErrors) {
 645           CLEAR_PENDING_EXCEPTION;
 646           _error_message = nullptr;
 647         } else {
 648           return;
 649         }
 650       }
 651       line_no++;
 652     }
 653     reset();
 654   }
 655 
 656   void process_command(bool is_replay_inline, TRAPS) {
 657     char* cmd = parse_string();
 658     if (cmd == nullptr) {
 659       return;
 660     }
 661     if (strcmp("#", cmd) == 0) {
 662       // comment line, print or ignore
 663       if (Verbose) {
 664         tty->print_cr("# %s", _bufptr);
 665       }
 666       skip_remaining();
 667     } else if (strcmp("version", cmd) == 0) {
 668       _version = parse_int("version");
 669       if (_version < 0 || _version > REPLAY_VERSION) {
 670         tty->print_cr("# unrecognized version %d, expected 0 <= version <= %d", _version, REPLAY_VERSION);
 671       }
 672     } else if (strcmp("compile", cmd) == 0) {
 673       process_compile(CHECK);
 674     } else if (!is_replay_inline) {
 675       if (strcmp("ciMethod", cmd) == 0) {
 676         process_ciMethod(CHECK);
 677       } else if (strcmp("ciMethodData", cmd) == 0) {
 678         process_ciMethodData(CHECK);
 679       } else if (strcmp("staticfield", cmd) == 0) {
 680         process_staticfield(CHECK);
 681       } else if (strcmp("ciInstanceKlass", cmd) == 0) {
 682         process_ciInstanceKlass(CHECK);
 683       } else if (strcmp("instanceKlass", cmd) == 0) {
 684         process_instanceKlass(CHECK);
 685 #if INCLUDE_JVMTI
 686       } else if (strcmp("JvmtiExport", cmd) == 0) {
 687         process_JvmtiExport(CHECK);
 688 #endif // INCLUDE_JVMTI
 689       } else {
 690         report_error("unknown command");
 691       }
 692     } else {
 693       report_error("unknown command");
 694     }
 695     if (!had_error() && *_bufptr != '\0') {
 696       report_error("line not properly terminated");
 697     }
 698   }
 699 
 700   // validation of comp_level
 701   bool is_valid_comp_level(int comp_level) {
 702     const int msg_len = 256;
 703     char* msg = nullptr;
 704     if (!is_compile(comp_level)) {
 705       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 706       jio_snprintf(msg, msg_len, "%d isn't compilation level", comp_level);
 707     } else if (is_c1_compile(comp_level) && !CompilerConfig::is_c1_enabled()) {
 708       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 709       jio_snprintf(msg, msg_len, "compilation level %d requires C1", comp_level);
 710     } else if (is_c2_compile(comp_level) && !CompilerConfig::is_c2_enabled()) {
 711       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 712       jio_snprintf(msg, msg_len, "compilation level %d requires C2", comp_level);
 713     }
 714     if (msg != nullptr) {
 715       report_error(msg);
 716       return false;
 717     }
 718     return true;
 719   }
 720 
 721   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> (<depth> <bci> <klass> <name> <signature>)*
 722   void* process_inline(ciMethod* imethod, Method* m, int entry_bci, int comp_level, TRAPS) {
 723     _imethod    = m;
 724     _iklass     = imethod->holder();
 725     _entry_bci  = entry_bci;
 726     _comp_level = comp_level;
 727     int line_no = 1;
 728     int c = getc(_stream);
 729     while(c != EOF) {
 730       c = get_line(c);
 731       process_command(true, CHECK_NULL);
 732       if (had_error()) {
 733         tty->print_cr("Error while parsing line %d: %s\n", line_no, _error_message);
 734         tty->print_cr("%s", _buffer);
 735         return nullptr;
 736       }
 737       if (_ci_inline_records != nullptr && _ci_inline_records->length() > 0) {
 738         // Found inlining record for the requested method.
 739         return _ci_inline_records;
 740       }
 741       line_no++;
 742     }
 743     return nullptr;
 744   }
 745 
 746   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> (<depth> <bci> <inline_late> <klass> <name> <signature>)*
 747   void process_compile(TRAPS) {
 748     Method* method = parse_method(CHECK);
 749     if (had_error()) return;
 750     int entry_bci = parse_int("entry_bci");
 751     int comp_level = parse_int("comp_level");
 752     if (!is_valid_comp_level(comp_level)) {
 753       return;
 754     }
 755     if (_imethod != nullptr) {
 756       // Replay Inlining
 757       if (entry_bci != _entry_bci || comp_level != _comp_level) {
 758         return;
 759       }
 760       const char* iklass_name  = _imethod->method_holder()->name()->as_utf8();
 761       const char* imethod_name = _imethod->name()->as_utf8();
 762       const char* isignature   = _imethod->signature()->as_utf8();
 763       const char* klass_name   = method->method_holder()->name()->as_utf8();
 764       const char* method_name  = method->name()->as_utf8();
 765       const char* signature    = method->signature()->as_utf8();
 766       if (strcmp(iklass_name,  klass_name)  != 0 ||
 767           strcmp(imethod_name, method_name) != 0 ||
 768           strcmp(isignature,   signature)   != 0) {
 769         return;
 770       }
 771     }
 772     int inline_count = 0;
 773     if (parse_tag_and_count("inline", inline_count)) {
 774       // Record inlining data
 775       _ci_inline_records = new GrowableArray<ciInlineRecord*>();
 776       for (int i = 0; i < inline_count; i++) {
 777         int depth = parse_int("inline_depth");
 778         int bci = parse_int("inline_bci");
 779         if (had_error()) {
 780           break;
 781         }
 782         int inline_late = 0;
 783         if (_version >= 2) {
 784           inline_late = parse_int("inline_late");
 785           if (had_error()) {
 786               break;
 787           }
 788         }
 789 
 790         Method* inl_method = parse_method(CHECK);
 791         if (had_error()) {
 792           break;
 793         }
 794         new_ciInlineRecord(inl_method, bci, depth, inline_late);
 795       }
 796     }
 797     if (_imethod != nullptr) {
 798       return; // Replay Inlining
 799     }
 800     InstanceKlass* ik = method->method_holder();
 801     ik->initialize(THREAD);
 802     if (HAS_PENDING_EXCEPTION) {
 803       oop throwable = PENDING_EXCEPTION;
 804       java_lang_Throwable::print(throwable, tty);
 805       tty->cr();
 806       if (ReplayIgnoreInitErrors) {
 807         CLEAR_PENDING_EXCEPTION;
 808         ik->set_init_state(InstanceKlass::fully_initialized);
 809       } else {
 810         return;
 811       }
 812     }
 813     // Make sure the existence of a prior compile doesn't stop this one
 814     CompiledMethod* nm = (entry_bci != InvocationEntryBci) ? method->lookup_osr_nmethod_for(entry_bci, comp_level, true) : method->code();
 815     if (nm != nullptr) {
 816       nm->make_not_entrant();
 817     }
 818     replay_state = this;
 819     CompileBroker::compile_method(methodHandle(THREAD, method), entry_bci, comp_level,
 820                                   methodHandle(), 0, CompileTask::Reason_Replay, THREAD);
 821     replay_state = nullptr;
 822   }
 823 
 824   // ciMethod <klass> <name> <signature> <invocation_counter> <backedge_counter> <interpreter_invocation_count> <interpreter_throwout_count> <instructions_size>
 825   void process_ciMethod(TRAPS) {
 826     Method* method = parse_method(CHECK);
 827     if (had_error()) return;
 828     ciMethodRecord* rec = new_ciMethod(method);
 829     rec->_invocation_counter = parse_int("invocation_counter");
 830     rec->_backedge_counter = parse_int("backedge_counter");
 831     rec->_interpreter_invocation_count = parse_int("interpreter_invocation_count");
 832     rec->_interpreter_throwout_count = parse_int("interpreter_throwout_count");
 833     rec->_instructions_size = parse_int("instructions_size");
 834   }
 835 
 836   // ciMethodData <klass> <name> <signature> <state> <invocation_counter> orig <length> <byte>* data <length> <ptr>* oops <length> (<offset> <klass>)* methods <length> (<offset> <klass> <name> <signature>)*
 837   void process_ciMethodData(TRAPS) {
 838     Method* method = parse_method(CHECK);
 839     if (had_error()) return;
 840     /* just copied from Method, to build interpret data*/
 841 
 842     // To be properly initialized, some profiling in the MDO needs the
 843     // method to be rewritten (number of arguments at a call for instance)
 844     method->method_holder()->link_class(CHECK);
 845     assert(method->method_data() == nullptr, "Should only be initialized once");
 846     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 847     MethodData* method_data = MethodData::allocate(loader_data, methodHandle(THREAD, method), CHECK);
 848     method->set_method_data(method_data);
 849 
 850     // collect and record all the needed information for later
 851     ciMethodDataRecord* rec = new_ciMethodData(method);
 852     rec->_state = parse_int("state");
 853     if (_version < 1) {
 854       parse_int("current_mileage");
 855     } else {
 856       rec->_invocation_counter = parse_int("invocation_counter");
 857     }
 858 
 859     rec->_orig_data = parse_data("orig", rec->_orig_data_length);
 860     if (rec->_orig_data == nullptr) {
 861       return;
 862     }
 863     rec->_data = parse_intptr_data("data", rec->_data_length);
 864     if (rec->_data == nullptr) {
 865       return;
 866     }
 867     if (!parse_tag_and_count("oops", rec->_classes_length)) {
 868       return;
 869     }
 870     rec->_classes = NEW_RESOURCE_ARRAY(Klass*, rec->_classes_length);
 871     rec->_classes_offsets = NEW_RESOURCE_ARRAY(int, rec->_classes_length);
 872     for (int i = 0; i < rec->_classes_length; i++) {
 873       int offset = parse_int("offset");
 874       if (had_error()) {
 875         return;
 876       }
 877       Klass* k = parse_klass(CHECK);
 878       rec->_classes_offsets[i] = offset;
 879       rec->_classes[i] = k;
 880     }
 881 
 882     if (!parse_tag_and_count("methods", rec->_methods_length)) {
 883       return;
 884     }
 885     rec->_methods = NEW_RESOURCE_ARRAY(Method*, rec->_methods_length);
 886     rec->_methods_offsets = NEW_RESOURCE_ARRAY(int, rec->_methods_length);
 887     for (int i = 0; i < rec->_methods_length; i++) {
 888       int offset = parse_int("offset");
 889       if (had_error()) {
 890         return;
 891       }
 892       Method* m = parse_method(CHECK);
 893       rec->_methods_offsets[i] = offset;
 894       rec->_methods[i] = m;
 895     }
 896   }
 897 
 898   // instanceKlass <name>
 899   // instanceKlass <constant pool ref> # <original hidden class name>
 900   //
 901   // Loads and initializes the klass 'name'.  This can be used to
 902   // create particular class loading environments
 903   void process_instanceKlass(TRAPS) {
 904     // just load the referenced class
 905     Klass* k = parse_klass(CHECK);
 906 
 907     if (_version >= 1) {
 908       if (!_protection_domain_initialized && k != nullptr) {
 909         assert(_protection_domain() == nullptr, "must be uninitialized");
 910         // The first entry is the holder class of the method for which a replay compilation is requested.
 911         // Use the same protection domain to load all subsequent classes in order to resolve all classes
 912         // in signatures of inlinees. This ensures that inlining can be done as stated in the replay file.
 913         _protection_domain = Handle(_thread, k->protection_domain());
 914       }
 915 
 916       _protection_domain_initialized = true;
 917     }
 918 
 919     if (k == nullptr) {
 920       return;
 921     }
 922     const char* comment = parse_string();
 923     bool is_comment = comment != nullptr && strcmp(comment, "#") == 0;
 924     if (k->is_hidden() != is_comment) {
 925       report_error("hidden class with comment expected");
 926       return;
 927     }
 928     // comment, print or ignore
 929     if (is_comment) {
 930       if (Verbose) {
 931         const char* hidden = parse_string();
 932         tty->print_cr("Found %s for %s", k->name()->as_quoted_ascii(), hidden);
 933       }
 934       skip_remaining();
 935     }
 936   }
 937 
 938   // ciInstanceKlass <name> <is_linked> <is_initialized> <length> tag*
 939   //
 940   // Load the klass 'name' and link or initialize it.  Verify that the
 941   // constant pool is the same length as 'length' and make sure the
 942   // constant pool tags are in the same state.
 943   void process_ciInstanceKlass(TRAPS) {
 944     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK);
 945     if (k == nullptr) {
 946       skip_remaining();
 947       return;
 948     }
 949     int is_linked = parse_int("is_linked");
 950     int is_initialized = parse_int("is_initialized");
 951     int length = parse_int("length");
 952     if (is_initialized) {
 953       k->initialize(THREAD);
 954       if (HAS_PENDING_EXCEPTION) {
 955         oop throwable = PENDING_EXCEPTION;
 956         java_lang_Throwable::print(throwable, tty);
 957         tty->cr();
 958         if (ReplayIgnoreInitErrors) {
 959           CLEAR_PENDING_EXCEPTION;
 960           k->set_init_state(InstanceKlass::fully_initialized);
 961         } else {
 962           return;
 963         }
 964       }
 965     } else if (is_linked) {
 966       k->link_class(CHECK);
 967     }
 968     new_ciInstanceKlass(k);
 969     ConstantPool* cp = k->constants();
 970     if (length != cp->length()) {
 971       report_error("constant pool length mismatch: wrong class files?");
 972       return;
 973     }
 974 
 975     int parsed_two_word = 0;
 976     for (int i = 1; i < length; i++) {
 977       int tag = parse_int("tag");
 978       if (had_error()) {
 979         return;
 980       }
 981       switch (cp->tag_at(i).value()) {
 982         case JVM_CONSTANT_UnresolvedClass: {
 983           if (tag == JVM_CONSTANT_Class) {
 984             tty->print_cr("Resolving klass %s at %d", cp->klass_name_at(i)->as_utf8(), i);
 985             Klass* k = cp->klass_at(i, CHECK);
 986           }
 987           break;
 988         }
 989         case JVM_CONSTANT_Long:
 990         case JVM_CONSTANT_Double:
 991           parsed_two_word = i + 1;
 992 
 993         case JVM_CONSTANT_ClassIndex:
 994         case JVM_CONSTANT_StringIndex:
 995         case JVM_CONSTANT_String:
 996         case JVM_CONSTANT_UnresolvedClassInError:
 997         case JVM_CONSTANT_Fieldref:
 998         case JVM_CONSTANT_Methodref:
 999         case JVM_CONSTANT_InterfaceMethodref:
1000         case JVM_CONSTANT_NameAndType:
1001         case JVM_CONSTANT_Utf8:
1002         case JVM_CONSTANT_Integer:
1003         case JVM_CONSTANT_Float:
1004         case JVM_CONSTANT_MethodHandle:
1005         case JVM_CONSTANT_MethodType:
1006         case JVM_CONSTANT_Dynamic:
1007         case JVM_CONSTANT_InvokeDynamic:
1008           if (tag != cp->tag_at(i).value()) {
1009             report_error("tag mismatch: wrong class files?");
1010             return;
1011           }
1012           break;
1013 
1014         case JVM_CONSTANT_Class:
1015           if (tag == JVM_CONSTANT_UnresolvedClass) {
1016             Klass* k = cp->klass_at(i, CHECK);
1017             tty->print_cr("Warning: entry was unresolved in the replay data: %s", k->name()->as_utf8());
1018           } else if (tag != JVM_CONSTANT_Class) {
1019             report_error("Unexpected tag");
1020             return;
1021           }
1022           break;
1023 
1024         case 0:
1025           if (parsed_two_word == i) continue;
1026 
1027         default:
1028           fatal("Unexpected tag: %d", cp->tag_at(i).value());
1029           break;
1030       }
1031 
1032     }
1033   }
1034 
1035   // staticfield <klass> <name> <signature> <value>
1036   //
1037   // Initialize a class and fill in the value for a static field.
1038   // This is useful when the compile was dependent on the value of
1039   // static fields but it's impossible to properly rerun the static
1040   // initializer.
1041   void process_staticfield(TRAPS) {
1042     InstanceKlass* k = (InstanceKlass *)parse_klass(CHECK);
1043 
1044     if (k == nullptr || ReplaySuppressInitializers == 0 ||
1045         (ReplaySuppressInitializers == 2 && k->class_loader() == nullptr)) {
1046       skip_remaining();
1047       return;
1048     }
1049 
1050     assert(k->is_initialized(), "must be");
1051 
1052     const char* field_name = parse_escaped_string();
1053     const char* field_signature = parse_string();
1054     fieldDescriptor fd;
1055     Symbol* name = SymbolTable::new_symbol(field_name);
1056     Symbol* sig = SymbolTable::new_symbol(field_signature);
1057     if (!k->find_local_field(name, sig, &fd) ||
1058         !fd.is_static() ||
1059         fd.has_initial_value()) {
1060       report_error(field_name);
1061       return;
1062     }
1063 
1064     oop java_mirror = k->java_mirror();
1065     if (field_signature[0] == JVM_SIGNATURE_ARRAY) {
1066       int length = parse_int("array length");
1067       oop value = nullptr;
1068 
1069       if (field_signature[1] == JVM_SIGNATURE_ARRAY) {
1070         // multi dimensional array
1071         ArrayKlass* kelem = (ArrayKlass *)parse_klass(CHECK);
1072         if (kelem == nullptr) {
1073           return;
1074         }
1075         int rank = 0;
1076         while (field_signature[rank] == JVM_SIGNATURE_ARRAY) {
1077           rank++;
1078         }
1079         jint* dims = NEW_RESOURCE_ARRAY(jint, rank);
1080         dims[0] = length;
1081         for (int i = 1; i < rank; i++) {
1082           dims[i] = 1; // These aren't relevant to the compiler
1083         }
1084         value = kelem->multi_allocate(rank, dims, CHECK);
1085       } else {
1086         if (strcmp(field_signature, "[B") == 0) {
1087           value = oopFactory::new_byteArray(length, CHECK);
1088         } else if (strcmp(field_signature, "[Z") == 0) {
1089           value = oopFactory::new_boolArray(length, CHECK);
1090         } else if (strcmp(field_signature, "[C") == 0) {
1091           value = oopFactory::new_charArray(length, CHECK);
1092         } else if (strcmp(field_signature, "[S") == 0) {
1093           value = oopFactory::new_shortArray(length, CHECK);
1094         } else if (strcmp(field_signature, "[F") == 0) {
1095           value = oopFactory::new_floatArray(length, CHECK);
1096         } else if (strcmp(field_signature, "[D") == 0) {
1097           value = oopFactory::new_doubleArray(length, CHECK);
1098         } else if (strcmp(field_signature, "[I") == 0) {
1099           value = oopFactory::new_intArray(length, CHECK);
1100         } else if (strcmp(field_signature, "[J") == 0) {
1101           value = oopFactory::new_longArray(length, CHECK);
1102         } else if (field_signature[0] == JVM_SIGNATURE_ARRAY &&
1103                    field_signature[1] == JVM_SIGNATURE_CLASS) {
1104           parse_klass(CHECK); // eat up the array class name
1105           Klass* kelem = resolve_klass(field_signature + 1, CHECK);
1106           value = oopFactory::new_objArray(kelem, length, CHECK);
1107         } else {
1108           report_error("unhandled array staticfield");
1109         }
1110       }
1111       java_mirror->obj_field_put(fd.offset(), value);
1112     } else {
1113       const char* string_value = parse_escaped_string();
1114       if (strcmp(field_signature, "I") == 0) {
1115         int value = atoi(string_value);
1116         java_mirror->int_field_put(fd.offset(), value);
1117       } else if (strcmp(field_signature, "B") == 0) {
1118         int value = atoi(string_value);
1119         java_mirror->byte_field_put(fd.offset(), value);
1120       } else if (strcmp(field_signature, "C") == 0) {
1121         int value = atoi(string_value);
1122         java_mirror->char_field_put(fd.offset(), value);
1123       } else if (strcmp(field_signature, "S") == 0) {
1124         int value = atoi(string_value);
1125         java_mirror->short_field_put(fd.offset(), value);
1126       } else if (strcmp(field_signature, "Z") == 0) {
1127         int value = atoi(string_value);
1128         java_mirror->bool_field_put(fd.offset(), value);
1129       } else if (strcmp(field_signature, "J") == 0) {
1130         jlong value;
1131         if (sscanf(string_value, JLONG_FORMAT, &value) != 1) {
1132           fprintf(stderr, "Error parsing long: %s\n", string_value);
1133           return;
1134         }
1135         java_mirror->long_field_put(fd.offset(), value);
1136       } else if (strcmp(field_signature, "F") == 0) {
1137         float value = atof(string_value);
1138         java_mirror->float_field_put(fd.offset(), value);
1139       } else if (strcmp(field_signature, "D") == 0) {
1140         double value = atof(string_value);
1141         java_mirror->double_field_put(fd.offset(), value);
1142       } else if (strcmp(field_signature, "Ljava/lang/String;") == 0) {
1143         Handle value = java_lang_String::create_from_str(string_value, CHECK);
1144         java_mirror->obj_field_put(fd.offset(), value());
1145       } else if (field_signature[0] == JVM_SIGNATURE_CLASS) {
1146         Klass* k = resolve_klass(string_value, CHECK);
1147         oop value = InstanceKlass::cast(k)->allocate_instance(CHECK);
1148         java_mirror->obj_field_put(fd.offset(), value);
1149       } else {
1150         report_error("unhandled staticfield");
1151       }
1152     }
1153   }
1154 
1155 #if INCLUDE_JVMTI
1156   // JvmtiExport <field> <value>
1157   void process_JvmtiExport(TRAPS) {
1158     const char* field = parse_string();
1159     bool value = parse_int("JvmtiExport flag") != 0;
1160     if (strcmp(field, "can_access_local_variables") == 0) {
1161       JvmtiExport::set_can_access_local_variables(value);
1162     } else if (strcmp(field, "can_hotswap_or_post_breakpoint") == 0) {
1163       JvmtiExport::set_can_hotswap_or_post_breakpoint(value);
1164     } else if (strcmp(field, "can_post_on_exceptions") == 0) {
1165       JvmtiExport::set_can_post_on_exceptions(value);
1166     } else {
1167       report_error("Unrecognized JvmtiExport directive");
1168     }
1169   }
1170 #endif // INCLUDE_JVMTI
1171 
1172   // Create and initialize a record for a ciMethod
1173   ciMethodRecord* new_ciMethod(Method* method) {
1174     ciMethodRecord* rec = NEW_RESOURCE_OBJ(ciMethodRecord);
1175     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1176     rec->_method_name = method->name()->as_utf8();
1177     rec->_signature = method->signature()->as_utf8();
1178     _ci_method_records.append(rec);
1179     return rec;
1180   }
1181 
1182   // Lookup data for a ciMethod
1183   ciMethodRecord* find_ciMethodRecord(Method* method) {
1184     const char* klass_name =  method->method_holder()->name()->as_utf8();
1185     const char* method_name = method->name()->as_utf8();
1186     const char* signature = method->signature()->as_utf8();
1187     for (int i = 0; i < _ci_method_records.length(); i++) {
1188       ciMethodRecord* rec = _ci_method_records.at(i);
1189       if (strcmp(rec->_klass_name, klass_name) == 0 &&
1190           strcmp(rec->_method_name, method_name) == 0 &&
1191           strcmp(rec->_signature, signature) == 0) {
1192         return rec;
1193       }
1194     }
1195     return nullptr;
1196   }
1197 
1198   // Create and initialize a record for a ciInstanceKlass which was present at replay dump time.
1199   void new_ciInstanceKlass(const InstanceKlass* klass) {
1200     ciInstanceKlassRecord* rec = NEW_RESOURCE_OBJ(ciInstanceKlassRecord);
1201     rec->_klass = klass;
1202     oop java_mirror = klass->java_mirror();
1203     Handle h_java_mirror(_thread, java_mirror);
1204     rec->_java_mirror = JNIHandles::make_global(h_java_mirror);
1205     _ci_instance_klass_records.append(rec);
1206   }
1207 
1208   // Check if a ciInstanceKlass was present at replay dump time for a klass.
1209   ciInstanceKlassRecord* find_ciInstanceKlass(const InstanceKlass* klass) {
1210     for (int i = 0; i < _ci_instance_klass_records.length(); i++) {
1211       ciInstanceKlassRecord* rec = _ci_instance_klass_records.at(i);
1212       if (klass == rec->_klass) {
1213         // ciInstanceKlass for this klass was resolved.
1214         return rec;
1215       }
1216     }
1217     return nullptr;
1218   }
1219 
1220   // Create and initialize a record for a ciMethodData
1221   ciMethodDataRecord* new_ciMethodData(Method* method) {
1222     ciMethodDataRecord* rec = NEW_RESOURCE_OBJ(ciMethodDataRecord);
1223     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1224     rec->_method_name = method->name()->as_utf8();
1225     rec->_signature = method->signature()->as_utf8();
1226     _ci_method_data_records.append(rec);
1227     return rec;
1228   }
1229 
1230   // Lookup data for a ciMethodData
1231   ciMethodDataRecord* find_ciMethodDataRecord(Method* method) {
1232     const char* klass_name =  method->method_holder()->name()->as_utf8();
1233     const char* method_name = method->name()->as_utf8();
1234     const char* signature = method->signature()->as_utf8();
1235     for (int i = 0; i < _ci_method_data_records.length(); i++) {
1236       ciMethodDataRecord* rec = _ci_method_data_records.at(i);
1237       if (strcmp(rec->_klass_name, klass_name) == 0 &&
1238           strcmp(rec->_method_name, method_name) == 0 &&
1239           strcmp(rec->_signature, signature) == 0) {
1240         return rec;
1241       }
1242     }
1243     return nullptr;
1244   }
1245 
1246   // Create and initialize a record for a ciInlineRecord
1247   ciInlineRecord* new_ciInlineRecord(Method* method, int bci, int depth, int inline_late) {
1248     ciInlineRecord* rec = NEW_RESOURCE_OBJ(ciInlineRecord);
1249     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1250     rec->_method_name = method->name()->as_utf8();
1251     rec->_signature = method->signature()->as_utf8();
1252     rec->_inline_bci = bci;
1253     rec->_inline_depth = depth;
1254     rec->_inline_late = inline_late;
1255     _ci_inline_records->append(rec);
1256     return rec;
1257   }
1258 
1259   // Lookup inlining data for a ciMethod
1260   ciInlineRecord* find_ciInlineRecord(Method* method, int bci, int depth) {
1261     if (_ci_inline_records != nullptr) {
1262       return find_ciInlineRecord(_ci_inline_records, method, bci, depth);
1263     }
1264     return nullptr;
1265   }
1266 
1267   static ciInlineRecord* find_ciInlineRecord(GrowableArray<ciInlineRecord*>*  records,
1268                                       Method* method, int bci, int depth) {
1269     if (records != nullptr) {
1270       const char* klass_name  = method->method_holder()->name()->as_utf8();
1271       const char* method_name = method->name()->as_utf8();
1272       const char* signature   = method->signature()->as_utf8();
1273       for (int i = 0; i < records->length(); i++) {
1274         ciInlineRecord* rec = records->at(i);
1275         if ((rec->_inline_bci == bci) &&
1276             (rec->_inline_depth == depth) &&
1277             (strcmp(rec->_klass_name, klass_name) == 0) &&
1278             (strcmp(rec->_method_name, method_name) == 0) &&
1279             (strcmp(rec->_signature, signature) == 0)) {
1280           return rec;
1281         }
1282       }
1283     }
1284     return nullptr;
1285   }
1286 
1287   const char* error_message() {
1288     return _error_message;
1289   }
1290 
1291   void reset() {
1292     _error_message = nullptr;
1293     _ci_method_records.clear();
1294     _ci_method_data_records.clear();
1295   }
1296 
1297   // Take an ascii string contain \u#### escapes and convert it to utf8
1298   // in place.
1299   static void unescape_string(char* value) {
1300     char* from = value;
1301     char* to = value;
1302     while (*from != '\0') {
1303       if (*from != '\\') {
1304         *from++ = *to++;
1305       } else {
1306         switch (from[1]) {
1307           case 'u': {
1308             from += 2;
1309             jchar value=0;
1310             for (int i=0; i<4; i++) {
1311               char c = *from++;
1312               switch (c) {
1313                 case '0': case '1': case '2': case '3': case '4':
1314                 case '5': case '6': case '7': case '8': case '9':
1315                   value = (value << 4) + c - '0';
1316                   break;
1317                 case 'a': case 'b': case 'c':
1318                 case 'd': case 'e': case 'f':
1319                   value = (value << 4) + 10 + c - 'a';
1320                   break;
1321                 case 'A': case 'B': case 'C':
1322                 case 'D': case 'E': case 'F':
1323                   value = (value << 4) + 10 + c - 'A';
1324                   break;
1325                 default:
1326                   ShouldNotReachHere();
1327               }
1328             }
1329             UNICODE::convert_to_utf8(&value, 1, to);
1330             to++;
1331             break;
1332           }
1333           case 't': *to++ = '\t'; from += 2; break;
1334           case 'n': *to++ = '\n'; from += 2; break;
1335           case 'r': *to++ = '\r'; from += 2; break;
1336           case 'f': *to++ = '\f'; from += 2; break;
1337           default:
1338             ShouldNotReachHere();
1339         }
1340       }
1341     }
1342     *from = *to;
1343   }
1344 };
1345 
1346 void ciReplay::replay(TRAPS) {
1347   int exit_code = replay_impl(THREAD);
1348 
1349   Threads::destroy_vm();
1350 
1351   vm_exit(exit_code);
1352 }
1353 
1354 bool ciReplay::no_replay_state() {
1355   return replay_state == nullptr;
1356 }
1357 
1358 void* ciReplay::load_inline_data(ciMethod* method, int entry_bci, int comp_level) {
1359   if (FLAG_IS_DEFAULT(InlineDataFile)) {
1360     tty->print_cr("ERROR: no inline replay data file specified (use -XX:InlineDataFile=inline_pid12345.txt).");
1361     return nullptr;
1362   }
1363 
1364   VM_ENTRY_MARK;
1365   // Load and parse the replay data
1366   CompileReplay rp(InlineDataFile, THREAD);
1367   if (!rp.can_replay()) {
1368     tty->print_cr("ciReplay: !rp.can_replay()");
1369     return nullptr;
1370   }
1371   void* data = rp.process_inline(method, method->get_Method(), entry_bci, comp_level, THREAD);
1372   if (HAS_PENDING_EXCEPTION) {
1373     Handle throwable(THREAD, PENDING_EXCEPTION);
1374     CLEAR_PENDING_EXCEPTION;
1375     java_lang_Throwable::print_stack_trace(throwable, tty);
1376     tty->cr();
1377     return nullptr;
1378   }
1379 
1380   if (rp.had_error()) {
1381     tty->print_cr("ciReplay: Failed on %s", rp.error_message());
1382     return nullptr;
1383   }
1384   return data;
1385 }
1386 
1387 int ciReplay::replay_impl(TRAPS) {
1388   HandleMark hm(THREAD);
1389   ResourceMark rm(THREAD);
1390 
1391   if (ReplaySuppressInitializers > 2) {
1392     // ReplaySuppressInitializers > 2 means that we want to allow
1393     // normal VM bootstrap but once we get into the replay itself
1394     // don't allow any initializers to be run.
1395     ReplaySuppressInitializers = 1;
1396   }
1397 
1398   if (FLAG_IS_DEFAULT(ReplayDataFile)) {
1399     tty->print_cr("ERROR: no compiler replay data file specified (use -XX:ReplayDataFile=replay_pid12345.txt).");
1400     return 1;
1401   }
1402 
1403   // Load and parse the replay data
1404   CompileReplay rp(ReplayDataFile, THREAD);
1405   int exit_code = 0;
1406   if (rp.can_replay()) {
1407     rp.process(THREAD);
1408   } else {
1409     exit_code = 1;
1410     return exit_code;
1411   }
1412 
1413   if (HAS_PENDING_EXCEPTION) {
1414     Handle throwable(THREAD, PENDING_EXCEPTION);
1415     CLEAR_PENDING_EXCEPTION;
1416     java_lang_Throwable::print_stack_trace(throwable, tty);
1417     tty->cr();
1418     exit_code = 2;
1419   }
1420 
1421   if (rp.had_error()) {
1422     tty->print_cr("Failed on %s", rp.error_message());
1423     exit_code = 1;
1424   }
1425   return exit_code;
1426 }
1427 
1428 void ciReplay::initialize(ciMethodData* m) {
1429   if (no_replay_state()) {
1430     return;
1431   }
1432 
1433   ASSERT_IN_VM;
1434   ResourceMark rm;
1435 
1436   Method* method = m->get_MethodData()->method();
1437   ciMethodDataRecord* rec = replay_state->find_ciMethodDataRecord(method);
1438   if (rec == nullptr) {
1439     // This indicates some mismatch with the original environment and
1440     // the replay environment though it's not always enough to
1441     // interfere with reproducing a bug
1442     tty->print_cr("Warning: requesting ciMethodData record for method with no data: ");
1443     method->print_name(tty);
1444     tty->cr();
1445   } else {
1446     m->_state = rec->_state;
1447     m->_invocation_counter = rec->_invocation_counter;
1448     if (rec->_data_length != 0) {
1449       assert(m->_data_size + m->_extra_data_size == rec->_data_length * (int)sizeof(rec->_data[0]) ||
1450              m->_data_size == rec->_data_length * (int)sizeof(rec->_data[0]), "must agree");
1451 
1452       // Write the correct ciObjects back into the profile data
1453       ciEnv* env = ciEnv::current();
1454       for (int i = 0; i < rec->_classes_length; i++) {
1455         Klass *k = rec->_classes[i];
1456         // In case this class pointer is is tagged, preserve the tag bits
1457         intptr_t status = 0;
1458         if (k != nullptr) {
1459           status = ciTypeEntries::with_status(env->get_metadata(k)->as_klass(), rec->_data[rec->_classes_offsets[i]]);
1460         }
1461         rec->_data[rec->_classes_offsets[i]] = status;
1462       }
1463       for (int i = 0; i < rec->_methods_length; i++) {
1464         Method *m = rec->_methods[i];
1465         *(ciMetadata**)(rec->_data + rec->_methods_offsets[i]) =
1466           env->get_metadata(m);
1467       }
1468       // Copy the updated profile data into place as intptr_ts
1469 #ifdef _LP64
1470       Copy::conjoint_jlongs_atomic((jlong *)rec->_data, (jlong *)m->_data, rec->_data_length);
1471 #else
1472       Copy::conjoint_jints_atomic((jint *)rec->_data, (jint *)m->_data, rec->_data_length);
1473 #endif
1474     }
1475 
1476     // copy in the original header
1477     Copy::conjoint_jbytes(rec->_orig_data, (char*)&m->_orig, rec->_orig_data_length);
1478   }
1479 }
1480 
1481 
1482 bool ciReplay::should_not_inline(ciMethod* method) {
1483   if (no_replay_state()) {
1484     return false;
1485   }
1486   VM_ENTRY_MARK;
1487   // ciMethod without a record shouldn't be inlined.
1488   return replay_state->find_ciMethodRecord(method->get_Method()) == nullptr;
1489 }
1490 
1491 bool ciReplay::should_inline(void* data, ciMethod* method, int bci, int inline_depth, bool& should_delay) {
1492   if (data != nullptr) {
1493     GrowableArray<ciInlineRecord*>* records = (GrowableArray<ciInlineRecord*>*)data;
1494     VM_ENTRY_MARK;
1495     // Inline record are ordered by bci and depth.
1496     ciInlineRecord* record = CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth);
1497     if (record == nullptr) {
1498       return false;
1499     }
1500     should_delay = record->_inline_late;
1501     return true;
1502   } else if (replay_state != nullptr) {
1503     VM_ENTRY_MARK;
1504     // Inline record are ordered by bci and depth.
1505     ciInlineRecord* record = replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth);
1506     if (record == nullptr) {
1507       return false;
1508     }
1509     should_delay = record->_inline_late;
1510     return true;
1511   }
1512   return false;
1513 }
1514 
1515 bool ciReplay::should_not_inline(void* data, ciMethod* method, int bci, int inline_depth) {
1516   if (data != nullptr) {
1517     GrowableArray<ciInlineRecord*>* records = (GrowableArray<ciInlineRecord*>*)data;
1518     VM_ENTRY_MARK;
1519     // Inline record are ordered by bci and depth.
1520     return CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth) == nullptr;
1521   } else if (replay_state != nullptr) {
1522     VM_ENTRY_MARK;
1523     // Inline record are ordered by bci and depth.
1524     return replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth) == nullptr;
1525   }
1526   return false;
1527 }
1528 
1529 void ciReplay::initialize(ciMethod* m) {
1530   if (no_replay_state()) {
1531     return;
1532   }
1533 
1534   ASSERT_IN_VM;
1535   ResourceMark rm;
1536 
1537   Method* method = m->get_Method();
1538   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1539   if (rec == nullptr) {
1540     // This indicates some mismatch with the original environment and
1541     // the replay environment though it's not always enough to
1542     // interfere with reproducing a bug
1543     tty->print_cr("Warning: requesting ciMethod record for method with no data: ");
1544     method->print_name(tty);
1545     tty->cr();
1546   } else {
1547     EXCEPTION_CONTEXT;
1548     // m->_instructions_size = rec->_instructions_size;
1549     m->_inline_instructions_size = -1;
1550     m->_interpreter_invocation_count = rec->_interpreter_invocation_count;
1551     m->_interpreter_throwout_count = rec->_interpreter_throwout_count;
1552     MethodCounters* mcs = method->get_method_counters(CHECK_AND_CLEAR);
1553     guarantee(mcs != nullptr, "method counters allocation failed");
1554     mcs->invocation_counter()->_counter = rec->_invocation_counter;
1555     mcs->backedge_counter()->_counter = rec->_backedge_counter;
1556   }
1557 }
1558 
1559 void ciReplay::initialize(ciInstanceKlass* ci_ik, InstanceKlass* ik) {
1560   assert(!no_replay_state(), "must have replay state");
1561 
1562   ASSERT_IN_VM;
1563   ciInstanceKlassRecord* rec = replay_state->find_ciInstanceKlass(ik);
1564   assert(rec != nullptr, "ciInstanceKlass must be whitelisted");
1565   ci_ik->_java_mirror = CURRENT_ENV->get_instance(JNIHandles::resolve(rec->_java_mirror));
1566 }
1567 
1568 bool ciReplay::is_loaded(Method* method) {
1569   if (no_replay_state()) {
1570     return true;
1571   }
1572 
1573   ASSERT_IN_VM;
1574   ResourceMark rm;
1575 
1576   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1577   return rec != nullptr;
1578 }
1579 
1580 bool ciReplay::is_klass_unresolved(const InstanceKlass* klass) {
1581   if (no_replay_state()) {
1582     return false;
1583   }
1584 
1585   // Check if klass is found on whitelist.
1586   ciInstanceKlassRecord* rec = replay_state->find_ciInstanceKlass(klass);
1587   return rec == nullptr;
1588 }
1589 
1590 oop ciReplay::obj_field(oop obj, Symbol* name) {
1591   InstanceKlass* ik = InstanceKlass::cast(obj->klass());
1592 
1593   do {
1594     if (!ik->has_nonstatic_fields()) {
1595       ik = ik->java_super();
1596       continue;
1597     }
1598 
1599     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
1600       if (fs.access_flags().is_static()) {
1601         continue;
1602       }
1603       if (fs.name() == name) {
1604         int offset = fs.offset();
1605 #ifdef ASSERT
1606         fieldDescriptor fd = fs.field_descriptor();
1607         assert(fd.offset() == ik->field_offset(fd.index()), "!");
1608 #endif
1609         oop f = obj->obj_field(offset);
1610         return f;
1611       }
1612     }
1613 
1614     ik = ik->java_super();
1615   } while (ik != nullptr);
1616   return nullptr;
1617 }
1618 
1619 oop ciReplay::obj_field(oop obj, const char *name) {
1620   Symbol* fname = SymbolTable::probe(name, (int)strlen(name));
1621   if (fname == nullptr) {
1622     return nullptr;
1623   }
1624   return obj_field(obj, fname);
1625 }