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       CallInfo callInfo;
 411       Bytecodes::Code bc = bytecode.invoke_code();
 412       LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, bc, CHECK_NULL);
 413 
 414       oop appendix = nullptr;
 415       Method* adapter_method = nullptr;
 416       int pool_index = 0;
 417 
 418       if (bytecode.is_invokedynamic()) {
 419         index = cp->decode_invokedynamic_index(index);
 420         cp->cache()->set_dynamic_call(callInfo, index);
 421 
 422         appendix = cp->resolved_reference_from_indy(index);
 423         adapter_method = cp->resolved_indy_entry_at(index)->method();
 424         pool_index = cp->resolved_indy_entry_at(index)->constant_pool_index();
 425       } else if (bytecode.is_invokehandle()) {
 426 #ifdef ASSERT
 427         Klass* holder = cp->klass_ref_at(index, bytecode.code(), CHECK_NULL);
 428         Symbol* name = cp->name_ref_at(index, bytecode.code());
 429         assert(MethodHandles::is_signature_polymorphic_name(holder, name), "");
 430 #endif
 431         ResolvedMethodEntry* method_entry = cp->cache()->set_method_handle(index, callInfo);
 432         appendix = cp->cache()->appendix_if_resolved(method_entry);
 433         adapter_method = method_entry->method();
 434         pool_index = method_entry->constant_pool_index();
 435       } else {
 436         report_error("no dynamic invoke found");
 437         return nullptr;
 438       }
 439       char* dyno_ref = parse_string();
 440       if (strcmp(dyno_ref, "<appendix>") == 0) {
 441         obj = appendix;
 442       } else if (strcmp(dyno_ref, "<adapter>") == 0) {
 443         if (!parse_terminator()) {
 444           report_error("no dynamic invoke found");
 445           return nullptr;
 446         }
 447         Method* adapter = adapter_method;
 448         if (adapter == nullptr) {
 449           report_error("no adapter found");
 450           return nullptr;
 451         }
 452         return adapter->method_holder();
 453       } else if (strcmp(dyno_ref, "<bsm>") == 0) {
 454         BootstrapInfo bootstrap_specifier(cp, pool_index, index);
 455         obj = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), CHECK_NULL);
 456       } else {
 457         report_error("unrecognized token");
 458         return nullptr;
 459       }
 460     } else {
 461       // constant pool ref (MethodHandle)
 462       if (strcmp(ref, "cpi") != 0) {
 463         report_error("unexpected token");
 464         return nullptr;
 465       }
 466 
 467       Klass* k = parse_klass(CHECK_NULL);
 468       if (k == nullptr) {
 469         return nullptr;
 470       }
 471       InstanceKlass* ik = InstanceKlass::cast(k);
 472       const constantPoolHandle cp(Thread::current(), ik->constants());
 473 
 474       int cpi = parse_int("cpi");
 475 
 476       if (cpi >= cp->length()) {
 477         report_error("bad cpi");
 478         return nullptr;
 479       }
 480       if (!cp->tag_at(cpi).is_method_handle()) {
 481         report_error("no method handle found at cpi");
 482         return nullptr;
 483       }
 484       ik->link_class(CHECK_NULL);
 485       obj = cp->resolve_possibly_cached_constant_at(cpi, CHECK_NULL);
 486     }
 487     if (obj == nullptr) {
 488       report_error("null cp object found");
 489       return nullptr;
 490     }
 491     Klass* k = nullptr;
 492     skip_ws();
 493     // loop: read fields
 494     char* field = nullptr;
 495     do {
 496       field = parse_string();
 497       if (field == nullptr) {
 498         report_error("no field found");
 499         return nullptr;
 500       }
 501       if (strcmp(field, ";") == 0) {
 502         break;
 503       }
 504       // raw Method*
 505       if (strcmp(field, "<vmtarget>") == 0) {
 506         Method* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
 507         k = (vmtarget == nullptr) ? nullptr : vmtarget->method_holder();
 508         if (k == nullptr) {
 509           report_error("null vmtarget found");
 510           return nullptr;
 511         }
 512         if (!parse_terminator()) {
 513           report_error("missing terminator");
 514           return nullptr;
 515         }
 516         return k;
 517       }
 518       obj = ciReplay::obj_field(obj, field);
 519       // array
 520       if (obj != nullptr && obj->is_objArray()) {
 521         objArrayOop arr = (objArrayOop)obj;
 522         int index = parse_int("index");
 523         if (index >= arr->length()) {
 524           report_error("bad array index");
 525           return nullptr;
 526         }
 527         obj = arr->obj_at(index);
 528       }
 529     } while (obj != nullptr);
 530     if (obj == nullptr) {
 531       report_error("null field found");
 532       return nullptr;
 533     }
 534     k = obj->klass();
 535     return k;
 536   }
 537 
 538   // Parse a valid klass name and look it up
 539   // syntax: <name>
 540   // syntax: <constant pool ref>
 541   Klass* parse_klass(TRAPS) {
 542     skip_ws();
 543     // check for constant pool object reference (for a dynamic/hidden class)
 544     bool cp_ref = (*_bufptr == '@');
 545     if (cp_ref) {
 546       ++_bufptr;
 547       Klass* k = parse_cp_ref(CHECK_NULL);
 548       if (k != nullptr && !k->is_hidden()) {
 549         report_error("expected hidden class");
 550         return nullptr;
 551       }
 552       return k;
 553     }
 554     char* str = parse_escaped_string();
 555     Symbol* klass_name = SymbolTable::new_symbol(str);
 556     if (klass_name != nullptr) {
 557       Klass* k = nullptr;
 558       if (_iklass != nullptr) {
 559         k = (Klass*)_iklass->find_klass(ciSymbol::make(klass_name->as_C_string()))->constant_encoding();
 560       } else {
 561         k = SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 562       }
 563       if (HAS_PENDING_EXCEPTION) {
 564         oop throwable = PENDING_EXCEPTION;
 565         java_lang_Throwable::print(throwable, tty);
 566         tty->cr();
 567         report_error(str);
 568         if (ReplayIgnoreInitErrors) {
 569           CLEAR_PENDING_EXCEPTION;
 570           _error_message = nullptr;
 571         }
 572         return nullptr;
 573       }
 574       return k;
 575     }
 576     return nullptr;
 577   }
 578 
 579   // Lookup a klass
 580   Klass* resolve_klass(const char* klass, TRAPS) {
 581     Symbol* klass_name = SymbolTable::new_symbol(klass);
 582     return SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 583   }
 584 
 585   // Parse the standard tuple of <klass> <name> <signature>
 586   Method* parse_method(TRAPS) {
 587     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK_NULL);
 588     if (k == nullptr) {
 589       report_error("Can't find holder klass");
 590       return nullptr;
 591     }
 592     Symbol* method_name = parse_symbol();
 593     Symbol* method_signature = parse_symbol();
 594     Method* m = k->find_method(method_name, method_signature);
 595     if (m == nullptr) {
 596       report_error("Can't find method");
 597     }
 598     return m;
 599   }
 600 
 601   int get_line(int c) {
 602     int buffer_pos = 0;
 603     while(c != EOF) {
 604       if (buffer_pos + 1 >= _buffer_length) {
 605         int new_length = _buffer_length * 2;
 606         // Next call will throw error in case of OOM.
 607         _buffer = REALLOC_RESOURCE_ARRAY(char, _buffer, _buffer_length, new_length);
 608         _buffer_length = new_length;
 609       }
 610       if (c == '\n') {
 611         c = getc(_stream); // get next char
 612         break;
 613       } else if (c == '\r') {
 614         // skip LF
 615       } else {
 616         _buffer[buffer_pos++] = c;
 617       }
 618       c = getc(_stream);
 619     }
 620     // null terminate it, reset the pointer
 621     _buffer[buffer_pos] = '\0'; // NL or EOF
 622     _bufptr = _buffer;
 623     return c;
 624   }
 625 
 626   // Process each line of the replay file executing each command until
 627   // the file ends.
 628   void process(TRAPS) {
 629     int line_no = 1;
 630     int c = getc(_stream);
 631     while(c != EOF) {
 632       c = get_line(c);
 633       process_command(false, THREAD);
 634       if (had_error()) {
 635         int pos = _bufptr - _buffer + 1;
 636         tty->print_cr("Error while parsing line %d at position %d: %s\n", line_no, pos, _error_message);
 637         if (ReplayIgnoreInitErrors) {
 638           CLEAR_PENDING_EXCEPTION;
 639           _error_message = nullptr;
 640         } else {
 641           return;
 642         }
 643       }
 644       line_no++;
 645     }
 646     reset();
 647   }
 648 
 649   void process_command(bool is_replay_inline, TRAPS) {
 650     char* cmd = parse_string();
 651     if (cmd == nullptr) {
 652       return;
 653     }
 654     if (strcmp("#", cmd) == 0) {
 655       // comment line, print or ignore
 656       if (Verbose) {
 657         tty->print_cr("# %s", _bufptr);
 658       }
 659       skip_remaining();
 660     } else if (strcmp("version", cmd) == 0) {
 661       _version = parse_int("version");
 662       if (_version < 0 || _version > REPLAY_VERSION) {
 663         tty->print_cr("# unrecognized version %d, expected 0 <= version <= %d", _version, REPLAY_VERSION);
 664       }
 665     } else if (strcmp("compile", cmd) == 0) {
 666       process_compile(CHECK);
 667     } else if (!is_replay_inline) {
 668       if (strcmp("ciMethod", cmd) == 0) {
 669         process_ciMethod(CHECK);
 670       } else if (strcmp("ciMethodData", cmd) == 0) {
 671         process_ciMethodData(CHECK);
 672       } else if (strcmp("staticfield", cmd) == 0) {
 673         process_staticfield(CHECK);
 674       } else if (strcmp("ciInstanceKlass", cmd) == 0) {
 675         process_ciInstanceKlass(CHECK);
 676       } else if (strcmp("instanceKlass", cmd) == 0) {
 677         process_instanceKlass(CHECK);
 678 #if INCLUDE_JVMTI
 679       } else if (strcmp("JvmtiExport", cmd) == 0) {
 680         process_JvmtiExport(CHECK);
 681 #endif // INCLUDE_JVMTI
 682       } else {
 683         report_error("unknown command");
 684       }
 685     } else {
 686       report_error("unknown command");
 687     }
 688     if (!had_error() && *_bufptr != '\0') {
 689       report_error("line not properly terminated");
 690     }
 691   }
 692 
 693   // validation of comp_level
 694   bool is_valid_comp_level(int comp_level) {
 695     const int msg_len = 256;
 696     char* msg = nullptr;
 697     if (!is_compile(comp_level)) {
 698       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 699       jio_snprintf(msg, msg_len, "%d isn't compilation level", comp_level);
 700     } else if (is_c1_compile(comp_level) && !CompilerConfig::is_c1_enabled()) {
 701       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 702       jio_snprintf(msg, msg_len, "compilation level %d requires C1", comp_level);
 703     } else if (is_c2_compile(comp_level) && !CompilerConfig::is_c2_enabled()) {
 704       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 705       jio_snprintf(msg, msg_len, "compilation level %d requires C2", comp_level);
 706     }
 707     if (msg != nullptr) {
 708       report_error(msg);
 709       return false;
 710     }
 711     return true;
 712   }
 713 
 714   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> (<depth> <bci> <klass> <name> <signature>)*
 715   void* process_inline(ciMethod* imethod, Method* m, int entry_bci, int comp_level, TRAPS) {
 716     _imethod    = m;
 717     _iklass     = imethod->holder();
 718     _entry_bci  = entry_bci;
 719     _comp_level = comp_level;
 720     int line_no = 1;
 721     int c = getc(_stream);
 722     while(c != EOF) {
 723       c = get_line(c);
 724       process_command(true, CHECK_NULL);
 725       if (had_error()) {
 726         tty->print_cr("Error while parsing line %d: %s\n", line_no, _error_message);
 727         tty->print_cr("%s", _buffer);
 728         return nullptr;
 729       }
 730       if (_ci_inline_records != nullptr && _ci_inline_records->length() > 0) {
 731         // Found inlining record for the requested method.
 732         return _ci_inline_records;
 733       }
 734       line_no++;
 735     }
 736     return nullptr;
 737   }
 738 
 739   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> (<depth> <bci> <inline_late> <klass> <name> <signature>)*
 740   void process_compile(TRAPS) {
 741     Method* method = parse_method(CHECK);
 742     if (had_error()) return;
 743     int entry_bci = parse_int("entry_bci");
 744     int comp_level = parse_int("comp_level");
 745     if (!is_valid_comp_level(comp_level)) {
 746       return;
 747     }
 748     if (_imethod != nullptr) {
 749       // Replay Inlining
 750       if (entry_bci != _entry_bci || comp_level != _comp_level) {
 751         return;
 752       }
 753       const char* iklass_name  = _imethod->method_holder()->name()->as_utf8();
 754       const char* imethod_name = _imethod->name()->as_utf8();
 755       const char* isignature   = _imethod->signature()->as_utf8();
 756       const char* klass_name   = method->method_holder()->name()->as_utf8();
 757       const char* method_name  = method->name()->as_utf8();
 758       const char* signature    = method->signature()->as_utf8();
 759       if (strcmp(iklass_name,  klass_name)  != 0 ||
 760           strcmp(imethod_name, method_name) != 0 ||
 761           strcmp(isignature,   signature)   != 0) {
 762         return;
 763       }
 764     }
 765     int inline_count = 0;
 766     if (parse_tag_and_count("inline", inline_count)) {
 767       // Record inlining data
 768       _ci_inline_records = new GrowableArray<ciInlineRecord*>();
 769       for (int i = 0; i < inline_count; i++) {
 770         int depth = parse_int("inline_depth");
 771         int bci = parse_int("inline_bci");
 772         if (had_error()) {
 773           break;
 774         }
 775         int inline_late = 0;
 776         if (_version >= 2) {
 777           inline_late = parse_int("inline_late");
 778           if (had_error()) {
 779               break;
 780           }
 781         }
 782 
 783         Method* inl_method = parse_method(CHECK);
 784         if (had_error()) {
 785           break;
 786         }
 787         new_ciInlineRecord(inl_method, bci, depth, inline_late);
 788       }
 789     }
 790     if (_imethod != nullptr) {
 791       return; // Replay Inlining
 792     }
 793     InstanceKlass* ik = method->method_holder();
 794     ik->initialize(THREAD);
 795     if (HAS_PENDING_EXCEPTION) {
 796       oop throwable = PENDING_EXCEPTION;
 797       java_lang_Throwable::print(throwable, tty);
 798       tty->cr();
 799       if (ReplayIgnoreInitErrors) {
 800         CLEAR_PENDING_EXCEPTION;
 801         ik->set_init_state(InstanceKlass::fully_initialized);
 802       } else {
 803         return;
 804       }
 805     }
 806     // Make sure the existence of a prior compile doesn't stop this one
 807     CompiledMethod* nm = (entry_bci != InvocationEntryBci) ? method->lookup_osr_nmethod_for(entry_bci, comp_level, true) : method->code();
 808     if (nm != nullptr) {
 809       nm->make_not_entrant();
 810     }
 811     replay_state = this;
 812     CompileBroker::compile_method(methodHandle(THREAD, method), entry_bci, comp_level,
 813                                   methodHandle(), 0, CompileTask::Reason_Replay, THREAD);
 814     replay_state = nullptr;
 815   }
 816 
 817   // ciMethod <klass> <name> <signature> <invocation_counter> <backedge_counter> <interpreter_invocation_count> <interpreter_throwout_count> <instructions_size>
 818   void process_ciMethod(TRAPS) {
 819     Method* method = parse_method(CHECK);
 820     if (had_error()) return;
 821     ciMethodRecord* rec = new_ciMethod(method);
 822     rec->_invocation_counter = parse_int("invocation_counter");
 823     rec->_backedge_counter = parse_int("backedge_counter");
 824     rec->_interpreter_invocation_count = parse_int("interpreter_invocation_count");
 825     rec->_interpreter_throwout_count = parse_int("interpreter_throwout_count");
 826     rec->_instructions_size = parse_int("instructions_size");
 827   }
 828 
 829   // ciMethodData <klass> <name> <signature> <state> <invocation_counter> orig <length> <byte>* data <length> <ptr>* oops <length> (<offset> <klass>)* methods <length> (<offset> <klass> <name> <signature>)*
 830   void process_ciMethodData(TRAPS) {
 831     Method* method = parse_method(CHECK);
 832     if (had_error()) return;
 833     /* just copied from Method, to build interpret data*/
 834 
 835     // To be properly initialized, some profiling in the MDO needs the
 836     // method to be rewritten (number of arguments at a call for instance)
 837     method->method_holder()->link_class(CHECK);
 838     assert(method->method_data() == nullptr, "Should only be initialized once");
 839     method->build_profiling_method_data(methodHandle(THREAD, method), CHECK);
 840 
 841     // collect and record all the needed information for later
 842     ciMethodDataRecord* rec = new_ciMethodData(method);
 843     rec->_state = parse_int("state");
 844     if (_version < 1) {
 845       parse_int("current_mileage");
 846     } else {
 847       rec->_invocation_counter = parse_int("invocation_counter");
 848     }
 849 
 850     rec->_orig_data = parse_data("orig", rec->_orig_data_length);
 851     if (rec->_orig_data == nullptr) {
 852       return;
 853     }
 854     rec->_data = parse_intptr_data("data", rec->_data_length);
 855     if (rec->_data == nullptr) {
 856       return;
 857     }
 858     if (!parse_tag_and_count("oops", rec->_classes_length)) {
 859       return;
 860     }
 861     rec->_classes = NEW_RESOURCE_ARRAY(Klass*, rec->_classes_length);
 862     rec->_classes_offsets = NEW_RESOURCE_ARRAY(int, rec->_classes_length);
 863     for (int i = 0; i < rec->_classes_length; i++) {
 864       int offset = parse_int("offset");
 865       if (had_error()) {
 866         return;
 867       }
 868       Klass* k = parse_klass(CHECK);
 869       rec->_classes_offsets[i] = offset;
 870       rec->_classes[i] = k;
 871     }
 872 
 873     if (!parse_tag_and_count("methods", rec->_methods_length)) {
 874       return;
 875     }
 876     rec->_methods = NEW_RESOURCE_ARRAY(Method*, rec->_methods_length);
 877     rec->_methods_offsets = NEW_RESOURCE_ARRAY(int, rec->_methods_length);
 878     for (int i = 0; i < rec->_methods_length; i++) {
 879       int offset = parse_int("offset");
 880       if (had_error()) {
 881         return;
 882       }
 883       Method* m = parse_method(CHECK);
 884       rec->_methods_offsets[i] = offset;
 885       rec->_methods[i] = m;
 886     }
 887   }
 888 
 889   // instanceKlass <name>
 890   // instanceKlass <constant pool ref> # <original hidden class name>
 891   //
 892   // Loads and initializes the klass 'name'.  This can be used to
 893   // create particular class loading environments
 894   void process_instanceKlass(TRAPS) {
 895     // just load the referenced class
 896     Klass* k = parse_klass(CHECK);
 897 
 898     if (_version >= 1) {
 899       if (!_protection_domain_initialized && k != nullptr) {
 900         assert(_protection_domain() == nullptr, "must be uninitialized");
 901         // The first entry is the holder class of the method for which a replay compilation is requested.
 902         // Use the same protection domain to load all subsequent classes in order to resolve all classes
 903         // in signatures of inlinees. This ensures that inlining can be done as stated in the replay file.
 904         _protection_domain = Handle(_thread, k->protection_domain());
 905       }
 906 
 907       _protection_domain_initialized = true;
 908     }
 909 
 910     if (k == nullptr) {
 911       return;
 912     }
 913     const char* comment = parse_string();
 914     bool is_comment = comment != nullptr && strcmp(comment, "#") == 0;
 915     if (k->is_hidden() != is_comment) {
 916       report_error("hidden class with comment expected");
 917       return;
 918     }
 919     // comment, print or ignore
 920     if (is_comment) {
 921       if (Verbose) {
 922         const char* hidden = parse_string();
 923         tty->print_cr("Found %s for %s", k->name()->as_quoted_ascii(), hidden);
 924       }
 925       skip_remaining();
 926     }
 927   }
 928 
 929   // ciInstanceKlass <name> <is_linked> <is_initialized> <length> tag*
 930   //
 931   // Load the klass 'name' and link or initialize it.  Verify that the
 932   // constant pool is the same length as 'length' and make sure the
 933   // constant pool tags are in the same state.
 934   void process_ciInstanceKlass(TRAPS) {
 935     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK);
 936     if (k == nullptr) {
 937       skip_remaining();
 938       return;
 939     }
 940     int is_linked = parse_int("is_linked");
 941     int is_initialized = parse_int("is_initialized");
 942     int length = parse_int("length");
 943     if (is_initialized) {
 944       k->initialize(THREAD);
 945       if (HAS_PENDING_EXCEPTION) {
 946         oop throwable = PENDING_EXCEPTION;
 947         java_lang_Throwable::print(throwable, tty);
 948         tty->cr();
 949         if (ReplayIgnoreInitErrors) {
 950           CLEAR_PENDING_EXCEPTION;
 951           k->set_init_state(InstanceKlass::fully_initialized);
 952         } else {
 953           return;
 954         }
 955       }
 956     } else if (is_linked) {
 957       k->link_class(CHECK);
 958     }
 959     new_ciInstanceKlass(k);
 960     ConstantPool* cp = k->constants();
 961     if (length != cp->length()) {
 962       report_error("constant pool length mismatch: wrong class files?");
 963       return;
 964     }
 965 
 966     int parsed_two_word = 0;
 967     for (int i = 1; i < length; i++) {
 968       int tag = parse_int("tag");
 969       if (had_error()) {
 970         return;
 971       }
 972       switch (cp->tag_at(i).value()) {
 973         case JVM_CONSTANT_UnresolvedClass: {
 974           if (tag == JVM_CONSTANT_Class) {
 975             tty->print_cr("Resolving klass %s at %d", cp->klass_name_at(i)->as_utf8(), i);
 976             Klass* k = cp->klass_at(i, CHECK);
 977           }
 978           break;
 979         }
 980         case JVM_CONSTANT_Long:
 981         case JVM_CONSTANT_Double:
 982           parsed_two_word = i + 1;
 983 
 984         case JVM_CONSTANT_ClassIndex:
 985         case JVM_CONSTANT_StringIndex:
 986         case JVM_CONSTANT_String:
 987         case JVM_CONSTANT_UnresolvedClassInError:
 988         case JVM_CONSTANT_Fieldref:
 989         case JVM_CONSTANT_Methodref:
 990         case JVM_CONSTANT_InterfaceMethodref:
 991         case JVM_CONSTANT_NameAndType:
 992         case JVM_CONSTANT_Utf8:
 993         case JVM_CONSTANT_Integer:
 994         case JVM_CONSTANT_Float:
 995         case JVM_CONSTANT_MethodHandle:
 996         case JVM_CONSTANT_MethodType:
 997         case JVM_CONSTANT_Dynamic:
 998         case JVM_CONSTANT_InvokeDynamic:
 999           if (tag != cp->tag_at(i).value()) {
1000             report_error("tag mismatch: wrong class files?");
1001             return;
1002           }
1003           break;
1004 
1005         case JVM_CONSTANT_Class:
1006           if (tag == JVM_CONSTANT_UnresolvedClass) {
1007             Klass* k = cp->klass_at(i, CHECK);
1008             tty->print_cr("Warning: entry was unresolved in the replay data: %s", k->name()->as_utf8());
1009           } else if (tag != JVM_CONSTANT_Class) {
1010             report_error("Unexpected tag");
1011             return;
1012           }
1013           break;
1014 
1015         case 0:
1016           if (parsed_two_word == i) continue;
1017 
1018         default:
1019           fatal("Unexpected tag: %d", cp->tag_at(i).value());
1020           break;
1021       }
1022 
1023     }
1024   }
1025 
1026   // staticfield <klass> <name> <signature> <value>
1027   //
1028   // Initialize a class and fill in the value for a static field.
1029   // This is useful when the compile was dependent on the value of
1030   // static fields but it's impossible to properly rerun the static
1031   // initializer.
1032   void process_staticfield(TRAPS) {
1033     InstanceKlass* k = (InstanceKlass *)parse_klass(CHECK);
1034 
1035     if (k == nullptr || ReplaySuppressInitializers == 0 ||
1036         (ReplaySuppressInitializers == 2 && k->class_loader() == nullptr)) {
1037       skip_remaining();
1038       return;
1039     }
1040 
1041     assert(k->is_initialized(), "must be");
1042 
1043     const char* field_name = parse_escaped_string();
1044     const char* field_signature = parse_string();
1045     fieldDescriptor fd;
1046     Symbol* name = SymbolTable::new_symbol(field_name);
1047     Symbol* sig = SymbolTable::new_symbol(field_signature);
1048     if (!k->find_local_field(name, sig, &fd) ||
1049         !fd.is_static() ||
1050         fd.has_initial_value()) {
1051       report_error(field_name);
1052       return;
1053     }
1054 
1055     oop java_mirror = k->java_mirror();
1056     if (field_signature[0] == JVM_SIGNATURE_ARRAY) {
1057       int length = parse_int("array length");
1058       oop value = nullptr;
1059 
1060       if (field_signature[1] == JVM_SIGNATURE_ARRAY) {
1061         // multi dimensional array
1062         ArrayKlass* kelem = (ArrayKlass *)parse_klass(CHECK);
1063         if (kelem == nullptr) {
1064           return;
1065         }
1066         int rank = 0;
1067         while (field_signature[rank] == JVM_SIGNATURE_ARRAY) {
1068           rank++;
1069         }
1070         jint* dims = NEW_RESOURCE_ARRAY(jint, rank);
1071         dims[0] = length;
1072         for (int i = 1; i < rank; i++) {
1073           dims[i] = 1; // These aren't relevant to the compiler
1074         }
1075         value = kelem->multi_allocate(rank, dims, CHECK);
1076       } else {
1077         if (strcmp(field_signature, "[B") == 0) {
1078           value = oopFactory::new_byteArray(length, CHECK);
1079         } else if (strcmp(field_signature, "[Z") == 0) {
1080           value = oopFactory::new_boolArray(length, CHECK);
1081         } else if (strcmp(field_signature, "[C") == 0) {
1082           value = oopFactory::new_charArray(length, CHECK);
1083         } else if (strcmp(field_signature, "[S") == 0) {
1084           value = oopFactory::new_shortArray(length, CHECK);
1085         } else if (strcmp(field_signature, "[F") == 0) {
1086           value = oopFactory::new_floatArray(length, CHECK);
1087         } else if (strcmp(field_signature, "[D") == 0) {
1088           value = oopFactory::new_doubleArray(length, CHECK);
1089         } else if (strcmp(field_signature, "[I") == 0) {
1090           value = oopFactory::new_intArray(length, CHECK);
1091         } else if (strcmp(field_signature, "[J") == 0) {
1092           value = oopFactory::new_longArray(length, CHECK);
1093         } else if (field_signature[0] == JVM_SIGNATURE_ARRAY &&
1094                    field_signature[1] == JVM_SIGNATURE_CLASS) {
1095           parse_klass(CHECK); // eat up the array class name
1096           Klass* kelem = resolve_klass(field_signature + 1, CHECK);
1097           value = oopFactory::new_objArray(kelem, length, CHECK);
1098         } else {
1099           report_error("unhandled array staticfield");
1100         }
1101       }
1102       java_mirror->obj_field_put(fd.offset(), value);
1103     } else {
1104       const char* string_value = parse_escaped_string();
1105       if (strcmp(field_signature, "I") == 0) {
1106         int value = atoi(string_value);
1107         java_mirror->int_field_put(fd.offset(), value);
1108       } else if (strcmp(field_signature, "B") == 0) {
1109         int value = atoi(string_value);
1110         java_mirror->byte_field_put(fd.offset(), value);
1111       } else if (strcmp(field_signature, "C") == 0) {
1112         int value = atoi(string_value);
1113         java_mirror->char_field_put(fd.offset(), value);
1114       } else if (strcmp(field_signature, "S") == 0) {
1115         int value = atoi(string_value);
1116         java_mirror->short_field_put(fd.offset(), value);
1117       } else if (strcmp(field_signature, "Z") == 0) {
1118         int value = atoi(string_value);
1119         java_mirror->bool_field_put(fd.offset(), value);
1120       } else if (strcmp(field_signature, "J") == 0) {
1121         jlong value;
1122         if (sscanf(string_value, JLONG_FORMAT, &value) != 1) {
1123           fprintf(stderr, "Error parsing long: %s\n", string_value);
1124           return;
1125         }
1126         java_mirror->long_field_put(fd.offset(), value);
1127       } else if (strcmp(field_signature, "F") == 0) {
1128         float value = atof(string_value);
1129         java_mirror->float_field_put(fd.offset(), value);
1130       } else if (strcmp(field_signature, "D") == 0) {
1131         double value = atof(string_value);
1132         java_mirror->double_field_put(fd.offset(), value);
1133       } else if (strcmp(field_signature, "Ljava/lang/String;") == 0) {
1134         Handle value = java_lang_String::create_from_str(string_value, CHECK);
1135         java_mirror->obj_field_put(fd.offset(), value());
1136       } else if (field_signature[0] == JVM_SIGNATURE_CLASS) {
1137         Klass* k = resolve_klass(string_value, CHECK);
1138         oop value = InstanceKlass::cast(k)->allocate_instance(CHECK);
1139         java_mirror->obj_field_put(fd.offset(), value);
1140       } else {
1141         report_error("unhandled staticfield");
1142       }
1143     }
1144   }
1145 
1146 #if INCLUDE_JVMTI
1147   // JvmtiExport <field> <value>
1148   void process_JvmtiExport(TRAPS) {
1149     const char* field = parse_string();
1150     bool value = parse_int("JvmtiExport flag") != 0;
1151     if (strcmp(field, "can_access_local_variables") == 0) {
1152       JvmtiExport::set_can_access_local_variables(value);
1153     } else if (strcmp(field, "can_hotswap_or_post_breakpoint") == 0) {
1154       JvmtiExport::set_can_hotswap_or_post_breakpoint(value);
1155     } else if (strcmp(field, "can_post_on_exceptions") == 0) {
1156       JvmtiExport::set_can_post_on_exceptions(value);
1157     } else {
1158       report_error("Unrecognized JvmtiExport directive");
1159     }
1160   }
1161 #endif // INCLUDE_JVMTI
1162 
1163   // Create and initialize a record for a ciMethod
1164   ciMethodRecord* new_ciMethod(Method* method) {
1165     ciMethodRecord* rec = NEW_RESOURCE_OBJ(ciMethodRecord);
1166     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1167     rec->_method_name = method->name()->as_utf8();
1168     rec->_signature = method->signature()->as_utf8();
1169     _ci_method_records.append(rec);
1170     return rec;
1171   }
1172 
1173   // Lookup data for a ciMethod
1174   ciMethodRecord* find_ciMethodRecord(Method* method) {
1175     const char* klass_name =  method->method_holder()->name()->as_utf8();
1176     const char* method_name = method->name()->as_utf8();
1177     const char* signature = method->signature()->as_utf8();
1178     for (int i = 0; i < _ci_method_records.length(); i++) {
1179       ciMethodRecord* rec = _ci_method_records.at(i);
1180       if (strcmp(rec->_klass_name, klass_name) == 0 &&
1181           strcmp(rec->_method_name, method_name) == 0 &&
1182           strcmp(rec->_signature, signature) == 0) {
1183         return rec;
1184       }
1185     }
1186     return nullptr;
1187   }
1188 
1189   // Create and initialize a record for a ciInstanceKlass which was present at replay dump time.
1190   void new_ciInstanceKlass(const InstanceKlass* klass) {
1191     ciInstanceKlassRecord* rec = NEW_RESOURCE_OBJ(ciInstanceKlassRecord);
1192     rec->_klass = klass;
1193     oop java_mirror = klass->java_mirror();
1194     Handle h_java_mirror(_thread, java_mirror);
1195     rec->_java_mirror = JNIHandles::make_global(h_java_mirror);
1196     _ci_instance_klass_records.append(rec);
1197   }
1198 
1199   // Check if a ciInstanceKlass was present at replay dump time for a klass.
1200   ciInstanceKlassRecord* find_ciInstanceKlass(const InstanceKlass* klass) {
1201     for (int i = 0; i < _ci_instance_klass_records.length(); i++) {
1202       ciInstanceKlassRecord* rec = _ci_instance_klass_records.at(i);
1203       if (klass == rec->_klass) {
1204         // ciInstanceKlass for this klass was resolved.
1205         return rec;
1206       }
1207     }
1208     return nullptr;
1209   }
1210 
1211   // Create and initialize a record for a ciMethodData
1212   ciMethodDataRecord* new_ciMethodData(Method* method) {
1213     ciMethodDataRecord* rec = NEW_RESOURCE_OBJ(ciMethodDataRecord);
1214     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1215     rec->_method_name = method->name()->as_utf8();
1216     rec->_signature = method->signature()->as_utf8();
1217     _ci_method_data_records.append(rec);
1218     return rec;
1219   }
1220 
1221   // Lookup data for a ciMethodData
1222   ciMethodDataRecord* find_ciMethodDataRecord(Method* method) {
1223     const char* klass_name =  method->method_holder()->name()->as_utf8();
1224     const char* method_name = method->name()->as_utf8();
1225     const char* signature = method->signature()->as_utf8();
1226     for (int i = 0; i < _ci_method_data_records.length(); i++) {
1227       ciMethodDataRecord* rec = _ci_method_data_records.at(i);
1228       if (strcmp(rec->_klass_name, klass_name) == 0 &&
1229           strcmp(rec->_method_name, method_name) == 0 &&
1230           strcmp(rec->_signature, signature) == 0) {
1231         return rec;
1232       }
1233     }
1234     return nullptr;
1235   }
1236 
1237   // Create and initialize a record for a ciInlineRecord
1238   ciInlineRecord* new_ciInlineRecord(Method* method, int bci, int depth, int inline_late) {
1239     ciInlineRecord* rec = NEW_RESOURCE_OBJ(ciInlineRecord);
1240     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1241     rec->_method_name = method->name()->as_utf8();
1242     rec->_signature = method->signature()->as_utf8();
1243     rec->_inline_bci = bci;
1244     rec->_inline_depth = depth;
1245     rec->_inline_late = inline_late;
1246     _ci_inline_records->append(rec);
1247     return rec;
1248   }
1249 
1250   // Lookup inlining data for a ciMethod
1251   ciInlineRecord* find_ciInlineRecord(Method* method, int bci, int depth) {
1252     if (_ci_inline_records != nullptr) {
1253       return find_ciInlineRecord(_ci_inline_records, method, bci, depth);
1254     }
1255     return nullptr;
1256   }
1257 
1258   static ciInlineRecord* find_ciInlineRecord(GrowableArray<ciInlineRecord*>*  records,
1259                                       Method* method, int bci, int depth) {
1260     if (records != nullptr) {
1261       const char* klass_name  = method->method_holder()->name()->as_utf8();
1262       const char* method_name = method->name()->as_utf8();
1263       const char* signature   = method->signature()->as_utf8();
1264       for (int i = 0; i < records->length(); i++) {
1265         ciInlineRecord* rec = records->at(i);
1266         if ((rec->_inline_bci == bci) &&
1267             (rec->_inline_depth == depth) &&
1268             (strcmp(rec->_klass_name, klass_name) == 0) &&
1269             (strcmp(rec->_method_name, method_name) == 0) &&
1270             (strcmp(rec->_signature, signature) == 0)) {
1271           return rec;
1272         }
1273       }
1274     }
1275     return nullptr;
1276   }
1277 
1278   const char* error_message() {
1279     return _error_message;
1280   }
1281 
1282   void reset() {
1283     _error_message = nullptr;
1284     _ci_method_records.clear();
1285     _ci_method_data_records.clear();
1286   }
1287 
1288   // Take an ascii string contain \u#### escapes and convert it to utf8
1289   // in place.
1290   static void unescape_string(char* value) {
1291     char* from = value;
1292     char* to = value;
1293     while (*from != '\0') {
1294       if (*from != '\\') {
1295         *from++ = *to++;
1296       } else {
1297         switch (from[1]) {
1298           case 'u': {
1299             from += 2;
1300             jchar value=0;
1301             for (int i=0; i<4; i++) {
1302               char c = *from++;
1303               switch (c) {
1304                 case '0': case '1': case '2': case '3': case '4':
1305                 case '5': case '6': case '7': case '8': case '9':
1306                   value = (value << 4) + c - '0';
1307                   break;
1308                 case 'a': case 'b': case 'c':
1309                 case 'd': case 'e': case 'f':
1310                   value = (value << 4) + 10 + c - 'a';
1311                   break;
1312                 case 'A': case 'B': case 'C':
1313                 case 'D': case 'E': case 'F':
1314                   value = (value << 4) + 10 + c - 'A';
1315                   break;
1316                 default:
1317                   ShouldNotReachHere();
1318               }
1319             }
1320             UNICODE::convert_to_utf8(&value, 1, to);
1321             to++;
1322             break;
1323           }
1324           case 't': *to++ = '\t'; from += 2; break;
1325           case 'n': *to++ = '\n'; from += 2; break;
1326           case 'r': *to++ = '\r'; from += 2; break;
1327           case 'f': *to++ = '\f'; from += 2; break;
1328           default:
1329             ShouldNotReachHere();
1330         }
1331       }
1332     }
1333     *from = *to;
1334   }
1335 };
1336 
1337 void ciReplay::replay(TRAPS) {
1338   int exit_code = replay_impl(THREAD);
1339 
1340   Threads::destroy_vm();
1341 
1342   vm_exit(exit_code);
1343 }
1344 
1345 bool ciReplay::no_replay_state() {
1346   return replay_state == nullptr;
1347 }
1348 
1349 void* ciReplay::load_inline_data(ciMethod* method, int entry_bci, int comp_level) {
1350   if (FLAG_IS_DEFAULT(InlineDataFile)) {
1351     tty->print_cr("ERROR: no inline replay data file specified (use -XX:InlineDataFile=inline_pid12345.txt).");
1352     return nullptr;
1353   }
1354 
1355   VM_ENTRY_MARK;
1356   // Load and parse the replay data
1357   CompileReplay rp(InlineDataFile, THREAD);
1358   if (!rp.can_replay()) {
1359     tty->print_cr("ciReplay: !rp.can_replay()");
1360     return nullptr;
1361   }
1362   void* data = rp.process_inline(method, method->get_Method(), entry_bci, comp_level, THREAD);
1363   if (HAS_PENDING_EXCEPTION) {
1364     Handle throwable(THREAD, PENDING_EXCEPTION);
1365     CLEAR_PENDING_EXCEPTION;
1366     java_lang_Throwable::print_stack_trace(throwable, tty);
1367     tty->cr();
1368     return nullptr;
1369   }
1370 
1371   if (rp.had_error()) {
1372     tty->print_cr("ciReplay: Failed on %s", rp.error_message());
1373     return nullptr;
1374   }
1375   return data;
1376 }
1377 
1378 int ciReplay::replay_impl(TRAPS) {
1379   HandleMark hm(THREAD);
1380   ResourceMark rm(THREAD);
1381 
1382   if (ReplaySuppressInitializers > 2) {
1383     // ReplaySuppressInitializers > 2 means that we want to allow
1384     // normal VM bootstrap but once we get into the replay itself
1385     // don't allow any initializers to be run.
1386     ReplaySuppressInitializers = 1;
1387   }
1388 
1389   if (FLAG_IS_DEFAULT(ReplayDataFile)) {
1390     tty->print_cr("ERROR: no compiler replay data file specified (use -XX:ReplayDataFile=replay_pid12345.txt).");
1391     return 1;
1392   }
1393 
1394   // Load and parse the replay data
1395   CompileReplay rp(ReplayDataFile, THREAD);
1396   int exit_code = 0;
1397   if (rp.can_replay()) {
1398     rp.process(THREAD);
1399   } else {
1400     exit_code = 1;
1401     return exit_code;
1402   }
1403 
1404   if (HAS_PENDING_EXCEPTION) {
1405     Handle throwable(THREAD, PENDING_EXCEPTION);
1406     CLEAR_PENDING_EXCEPTION;
1407     java_lang_Throwable::print_stack_trace(throwable, tty);
1408     tty->cr();
1409     exit_code = 2;
1410   }
1411 
1412   if (rp.had_error()) {
1413     tty->print_cr("Failed on %s", rp.error_message());
1414     exit_code = 1;
1415   }
1416   return exit_code;
1417 }
1418 
1419 void ciReplay::initialize(ciMethodData* m) {
1420   if (no_replay_state()) {
1421     return;
1422   }
1423 
1424   ASSERT_IN_VM;
1425   ResourceMark rm;
1426 
1427   Method* method = m->get_MethodData()->method();
1428   ciMethodDataRecord* rec = replay_state->find_ciMethodDataRecord(method);
1429   if (rec == nullptr) {
1430     // This indicates some mismatch with the original environment and
1431     // the replay environment though it's not always enough to
1432     // interfere with reproducing a bug
1433     tty->print_cr("Warning: requesting ciMethodData record for method with no data: ");
1434     method->print_name(tty);
1435     tty->cr();
1436   } else {
1437     m->_state = rec->_state;
1438     m->_invocation_counter = rec->_invocation_counter;
1439     if (rec->_data_length != 0) {
1440       assert(m->_data_size + m->_extra_data_size == rec->_data_length * (int)sizeof(rec->_data[0]) ||
1441              m->_data_size == rec->_data_length * (int)sizeof(rec->_data[0]), "must agree");
1442 
1443       // Write the correct ciObjects back into the profile data
1444       ciEnv* env = ciEnv::current();
1445       for (int i = 0; i < rec->_classes_length; i++) {
1446         Klass *k = rec->_classes[i];
1447         // In case this class pointer is is tagged, preserve the tag bits
1448         intptr_t status = 0;
1449         if (k != nullptr) {
1450           status = ciTypeEntries::with_status(env->get_metadata(k)->as_klass(), rec->_data[rec->_classes_offsets[i]]);
1451         }
1452         rec->_data[rec->_classes_offsets[i]] = status;
1453       }
1454       for (int i = 0; i < rec->_methods_length; i++) {
1455         Method *m = rec->_methods[i];
1456         *(ciMetadata**)(rec->_data + rec->_methods_offsets[i]) =
1457           env->get_metadata(m);
1458       }
1459       // Copy the updated profile data into place as intptr_ts
1460 #ifdef _LP64
1461       Copy::conjoint_jlongs_atomic((jlong *)rec->_data, (jlong *)m->_data, rec->_data_length);
1462 #else
1463       Copy::conjoint_jints_atomic((jint *)rec->_data, (jint *)m->_data, rec->_data_length);
1464 #endif
1465     }
1466 
1467     // copy in the original header
1468     Copy::conjoint_jbytes(rec->_orig_data, (char*)&m->_orig, rec->_orig_data_length);
1469   }
1470 }
1471 
1472 
1473 bool ciReplay::should_not_inline(ciMethod* method) {
1474   if (no_replay_state()) {
1475     return false;
1476   }
1477   VM_ENTRY_MARK;
1478   // ciMethod without a record shouldn't be inlined.
1479   return replay_state->find_ciMethodRecord(method->get_Method()) == nullptr;
1480 }
1481 
1482 bool ciReplay::should_inline(void* data, ciMethod* method, int bci, int inline_depth, bool& should_delay) {
1483   if (data != nullptr) {
1484     GrowableArray<ciInlineRecord*>* records = (GrowableArray<ciInlineRecord*>*)data;
1485     VM_ENTRY_MARK;
1486     // Inline record are ordered by bci and depth.
1487     ciInlineRecord* record = CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth);
1488     if (record == nullptr) {
1489       return false;
1490     }
1491     should_delay = record->_inline_late;
1492     return true;
1493   } else if (replay_state != nullptr) {
1494     VM_ENTRY_MARK;
1495     // Inline record are ordered by bci and depth.
1496     ciInlineRecord* record = replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth);
1497     if (record == nullptr) {
1498       return false;
1499     }
1500     should_delay = record->_inline_late;
1501     return true;
1502   }
1503   return false;
1504 }
1505 
1506 bool ciReplay::should_not_inline(void* data, ciMethod* method, int bci, int inline_depth) {
1507   if (data != nullptr) {
1508     GrowableArray<ciInlineRecord*>* records = (GrowableArray<ciInlineRecord*>*)data;
1509     VM_ENTRY_MARK;
1510     // Inline record are ordered by bci and depth.
1511     return CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth) == nullptr;
1512   } else if (replay_state != nullptr) {
1513     VM_ENTRY_MARK;
1514     // Inline record are ordered by bci and depth.
1515     return replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth) == nullptr;
1516   }
1517   return false;
1518 }
1519 
1520 void ciReplay::initialize(ciMethod* m) {
1521   if (no_replay_state()) {
1522     return;
1523   }
1524 
1525   ASSERT_IN_VM;
1526   ResourceMark rm;
1527 
1528   Method* method = m->get_Method();
1529   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1530   if (rec == nullptr) {
1531     // This indicates some mismatch with the original environment and
1532     // the replay environment though it's not always enough to
1533     // interfere with reproducing a bug
1534     tty->print_cr("Warning: requesting ciMethod record for method with no data: ");
1535     method->print_name(tty);
1536     tty->cr();
1537   } else {
1538     EXCEPTION_CONTEXT;
1539     // m->_instructions_size = rec->_instructions_size;
1540     m->_inline_instructions_size = -1;
1541     m->_interpreter_invocation_count = rec->_interpreter_invocation_count;
1542     m->_interpreter_throwout_count = rec->_interpreter_throwout_count;
1543     MethodCounters* mcs = method->get_method_counters(CHECK_AND_CLEAR);
1544     guarantee(mcs != nullptr, "method counters allocation failed");
1545     mcs->invocation_counter()->_counter = rec->_invocation_counter;
1546     mcs->backedge_counter()->_counter = rec->_backedge_counter;
1547   }
1548 }
1549 
1550 void ciReplay::initialize(ciInstanceKlass* ci_ik, InstanceKlass* ik) {
1551   assert(!no_replay_state(), "must have replay state");
1552 
1553   ASSERT_IN_VM;
1554   ciInstanceKlassRecord* rec = replay_state->find_ciInstanceKlass(ik);
1555   assert(rec != nullptr, "ciInstanceKlass must be whitelisted");
1556   ci_ik->_java_mirror = CURRENT_ENV->get_instance(JNIHandles::resolve(rec->_java_mirror));
1557 }
1558 
1559 bool ciReplay::is_loaded(Method* method) {
1560   if (no_replay_state()) {
1561     return true;
1562   }
1563 
1564   ASSERT_IN_VM;
1565   ResourceMark rm;
1566 
1567   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1568   return rec != nullptr;
1569 }
1570 
1571 bool ciReplay::is_klass_unresolved(const InstanceKlass* klass) {
1572   if (no_replay_state()) {
1573     return false;
1574   }
1575 
1576   // Check if klass is found on whitelist.
1577   ciInstanceKlassRecord* rec = replay_state->find_ciInstanceKlass(klass);
1578   return rec == nullptr;
1579 }
1580 
1581 oop ciReplay::obj_field(oop obj, Symbol* name) {
1582   InstanceKlass* ik = InstanceKlass::cast(obj->klass());
1583 
1584   do {
1585     if (!ik->has_nonstatic_fields()) {
1586       ik = ik->java_super();
1587       continue;
1588     }
1589 
1590     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
1591       if (fs.access_flags().is_static()) {
1592         continue;
1593       }
1594       if (fs.name() == name) {
1595         int offset = fs.offset();
1596 #ifdef ASSERT
1597         fieldDescriptor fd = fs.field_descriptor();
1598         assert(fd.offset() == ik->field_offset(fd.index()), "!");
1599 #endif
1600         oop f = obj->obj_field(offset);
1601         return f;
1602       }
1603     }
1604 
1605     ik = ik->java_super();
1606   } while (ik != nullptr);
1607   return nullptr;
1608 }
1609 
1610 oop ciReplay::obj_field(oop obj, const char *name) {
1611   Symbol* fname = SymbolTable::probe(name, (int)strlen(name));
1612   if (fname == nullptr) {
1613     return nullptr;
1614   }
1615   return obj_field(obj, fname);
1616 }