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