1 /*
   2  * Copyright (c) 2013, 2022, 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 "jvm.h"
  27 #include "ci/ciMethodData.hpp"
  28 #include "ci/ciReplay.hpp"
  29 #include "ci/ciSymbol.hpp"
  30 #include "ci/ciKlass.hpp"
  31 #include "ci/ciUtilities.inline.hpp"
  32 #include "classfile/javaClasses.hpp"
  33 #include "classfile/symbolTable.hpp"
  34 #include "classfile/systemDictionary.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compilerDefinitions.inline.hpp"
  38 #include "interpreter/linkResolver.hpp"
  39 #include "memory/allocation.inline.hpp"
  40 #include "memory/oopFactory.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "oops/constantPool.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 "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  _protection_domain;
 117   bool    _protection_domain_initialized;
 118   Handle  _loader;
 119   int     _version;
 120 
 121   GrowableArray<ciMethodRecord*>     _ci_method_records;
 122   GrowableArray<ciMethodDataRecord*> _ci_method_data_records;
 123   GrowableArray<ciInstanceKlassRecord*> _ci_instance_klass_records;
 124 
 125   // Use pointer because we may need to return inline records
 126   // without destroying them.
 127   GrowableArray<ciInlineRecord*>*    _ci_inline_records;
 128 
 129   const char* _error_message;
 130 
 131   char* _bufptr;
 132   char* _buffer;
 133   int   _buffer_length;
 134 
 135   // "compile" data
 136   ciKlass* _iklass;
 137   Method*  _imethod;
 138   int      _entry_bci;
 139   int      _comp_level;
 140 
 141  public:
 142   CompileReplay(const char* filename, TRAPS) {
 143     _thread = THREAD;
 144     _loader = Handle(_thread, SystemDictionary::java_system_loader());
 145     _protection_domain = Handle();
 146     _protection_domain_initialized = false;
 147 
 148     _stream = os::fopen(filename, "rt");
 149     if (_stream == NULL) {
 150       fprintf(stderr, "ERROR: Can't open replay file %s\n", filename);
 151     }
 152 
 153     _ci_inline_records = NULL;
 154     _error_message = NULL;
 155 
 156     _buffer_length = 32;
 157     _buffer = NEW_RESOURCE_ARRAY(char, _buffer_length);
 158     _bufptr = _buffer;
 159 
 160     _imethod = NULL;
 161     _iklass  = NULL;
 162     _entry_bci  = 0;
 163     _comp_level = 0;
 164     _version = 0;
 165 
 166     test();
 167   }
 168 
 169   ~CompileReplay() {
 170     if (_stream != NULL) fclose(_stream);
 171   }
 172 
 173   void test() {
 174     strcpy(_buffer, "1 2 foo 4 bar 0x9 \"this is it\"");
 175     _bufptr = _buffer;
 176     assert(parse_int("test") == 1, "what");
 177     assert(parse_int("test") == 2, "what");
 178     assert(strcmp(parse_string(), "foo") == 0, "what");
 179     assert(parse_int("test") == 4, "what");
 180     assert(strcmp(parse_string(), "bar") == 0, "what");
 181     assert(parse_intptr_t("test") == 9, "what");
 182     assert(strcmp(parse_quoted_string(), "this is it") == 0, "what");
 183   }
 184 
 185   bool had_error() {
 186     return _error_message != NULL || _thread->has_pending_exception();
 187   }
 188 
 189   bool can_replay() {
 190     return !(_stream == NULL || had_error());
 191   }
 192 
 193   void report_error(const char* msg) {
 194     _error_message = msg;
 195   }
 196 
 197   int parse_int(const char* label) {
 198     if (had_error()) {
 199       return 0;
 200     }
 201 
 202     int v = 0;
 203     int read;
 204     if (sscanf(_bufptr, "%i%n", &v, &read) != 1) {
 205       report_error(label);
 206     } else {
 207       _bufptr += read;
 208     }
 209     return v;
 210   }
 211 
 212   intptr_t parse_intptr_t(const char* label) {
 213     if (had_error()) {
 214       return 0;
 215     }
 216 
 217     intptr_t v = 0;
 218     int read;
 219     if (sscanf(_bufptr, INTPTR_FORMAT "%n", &v, &read) != 1) {
 220       report_error(label);
 221     } else {
 222       _bufptr += read;
 223     }
 224     return v;
 225   }
 226 
 227   void skip_ws() {
 228     // Skip any leading whitespace
 229     while (*_bufptr == ' ' || *_bufptr == '\t') {
 230       _bufptr++;
 231     }
 232   }
 233 
 234   // Ignore the rest of the line
 235   void skip_remaining() {
 236     _bufptr = &_bufptr[strlen(_bufptr)]; // skip ahead to terminator
 237   }
 238 
 239   char* scan_and_terminate(char delim) {
 240     char* str = _bufptr;
 241     while (*_bufptr != delim && *_bufptr != '\0') {
 242       _bufptr++;
 243     }
 244     if (*_bufptr != '\0') {
 245       *_bufptr++ = '\0';
 246     }
 247     if (_bufptr == str) {
 248       // nothing here
 249       return NULL;
 250     }
 251     return str;
 252   }
 253 
 254   char* parse_string() {
 255     if (had_error()) return NULL;
 256 
 257     skip_ws();
 258     return scan_and_terminate(' ');
 259   }
 260 
 261   char* parse_quoted_string() {
 262     if (had_error()) return NULL;
 263 
 264     skip_ws();
 265 
 266     if (*_bufptr == '"') {
 267       _bufptr++;
 268       return scan_and_terminate('"');
 269     } else {
 270       return scan_and_terminate(' ');
 271     }
 272   }
 273 
 274   char* parse_escaped_string() {
 275     char* result = parse_quoted_string();
 276     if (result != NULL) {
 277       unescape_string(result);
 278     }
 279     return result;
 280   }
 281 
 282   // Look for the tag 'tag' followed by an
 283   bool parse_tag_and_count(const char* tag, int& length) {
 284     const char* t = parse_string();
 285     if (t == NULL) {
 286       return false;
 287     }
 288 
 289     if (strcmp(tag, t) != 0) {
 290       report_error(tag);
 291       return false;
 292     }
 293     length = parse_int("parse_tag_and_count");
 294     return !had_error();
 295   }
 296 
 297   // Parse a sequence of raw data encoded as bytes and return the
 298   // resulting data.
 299   char* parse_data(const char* tag, int& length) {
 300     int read_size = 0;
 301     if (!parse_tag_and_count(tag, read_size)) {
 302       return NULL;
 303     }
 304 
 305     int actual_size = sizeof(MethodData::CompilerCounters);
 306     char *result = NEW_RESOURCE_ARRAY(char, actual_size);
 307     int i = 0;
 308     if (read_size != actual_size) {
 309       tty->print_cr("Warning: ciMethodData parsing sees MethodData size %i in file, current is %i", read_size,
 310                     actual_size);
 311       // Replay serializes the entire MethodData, but the data is at the end.
 312       // If the MethodData instance size has changed, we can pad or truncate in the beginning
 313       int padding = actual_size - read_size;
 314       if (padding > 0) {
 315         // pad missing data with zeros
 316         tty->print_cr("- Padding MethodData");
 317         for (; i < padding; i++) {
 318           result[i] = 0;
 319         }
 320       } else if (padding < 0) {
 321         // drop some data
 322         tty->print_cr("- Truncating MethodData");
 323         for (int j = 0; j < -padding; j++) {
 324           int val = parse_int("data");
 325           // discard val
 326         }
 327       }
 328     }
 329 
 330     assert(i < actual_size, "At least some data must remain to be copied");
 331     for (; i < actual_size; i++) {
 332       int val = parse_int("data");
 333       result[i] = val;
 334     }
 335     length = actual_size;
 336     return result;
 337   }
 338 
 339   // Parse a standard chunk of data emitted as:
 340   //   'tag' <length> # # ...
 341   // Where each # is an intptr_t item
 342   intptr_t* parse_intptr_data(const char* tag, int& length) {
 343     if (!parse_tag_and_count(tag, length)) {
 344       return NULL;
 345     }
 346 
 347     intptr_t* result = NEW_RESOURCE_ARRAY(intptr_t, length);
 348     for (int i = 0; i < length; i++) {
 349       skip_ws();
 350       intptr_t val = parse_intptr_t("data");
 351       result[i] = val;
 352     }
 353     return result;
 354   }
 355 
 356   // Parse a possibly quoted version of a symbol into a symbolOop
 357   Symbol* parse_symbol() {
 358     const char* str = parse_escaped_string();
 359     if (str != NULL) {
 360       Symbol* sym = SymbolTable::new_symbol(str);
 361       return sym;
 362     }
 363     return NULL;
 364   }
 365 
 366   bool parse_terminator() {
 367     char* terminator = parse_string();
 368     if (terminator != NULL && strcmp(terminator, ";") == 0) {
 369       return true;
 370     }
 371     return false;
 372   }
 373 
 374   // Parse a special hidden klass location syntax
 375   // syntax: @bci <klass> <name> <signature> <bci> <location>* ;
 376   // syntax: @cpi <klass> <cpi> <location>* ;
 377   Klass* parse_cp_ref(TRAPS) {
 378     JavaThread* thread = THREAD;
 379     oop obj = NULL;
 380     char* ref = parse_string();
 381     if (strcmp(ref, "bci") == 0) {
 382       Method* m = parse_method(CHECK_NULL);
 383       if (m == NULL) {
 384         return NULL;
 385       }
 386 
 387       InstanceKlass* ik = m->method_holder();
 388       const constantPoolHandle cp(Thread::current(), ik->constants());
 389 
 390       // invokedynamic or invokehandle
 391 
 392       methodHandle caller(Thread::current(), m);
 393       int bci = parse_int("bci");
 394       if (m->validate_bci(bci) != bci) {
 395         report_error("bad bci");
 396         return NULL;
 397       }
 398 
 399       ik->link_class(CHECK_NULL);
 400 
 401       Bytecode_invoke bytecode = Bytecode_invoke_check(caller, bci);
 402       if (!Bytecodes::is_defined(bytecode.code()) || !bytecode.is_valid()) {
 403         report_error("no invoke found at bci");
 404         return NULL;
 405       }
 406       bytecode.verify();
 407       int index = bytecode.index();
 408 
 409       ConstantPoolCacheEntry* cp_cache_entry = NULL;
 410       CallInfo callInfo;
 411       Bytecodes::Code bc = bytecode.invoke_code();
 412       LinkResolver::resolve_invoke(callInfo, Handle(), cp, index, bc, CHECK_NULL);
 413       if (bytecode.is_invokedynamic()) {
 414         cp_cache_entry = cp->invokedynamic_cp_cache_entry_at(index);
 415         cp_cache_entry->set_dynamic_call(cp, callInfo);
 416       } else if (bytecode.is_invokehandle()) {
 417 #ifdef ASSERT
 418         Klass* holder = cp->klass_ref_at(index, CHECK_NULL);
 419         Symbol* name = cp->name_ref_at(index);
 420         assert(MethodHandles::is_signature_polymorphic_name(holder, name), "");
 421 #endif
 422         cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
 423         cp_cache_entry->set_method_handle(cp, callInfo);
 424       } else {
 425         report_error("no dynamic invoke found");
 426         return NULL;
 427       }
 428       char* dyno_ref = parse_string();
 429       if (strcmp(dyno_ref, "<appendix>") == 0) {
 430         obj = cp_cache_entry->appendix_if_resolved(cp);
 431       } else if (strcmp(dyno_ref, "<adapter>") == 0) {
 432         if (!parse_terminator()) {
 433           report_error("no dynamic invoke found");
 434           return NULL;
 435         }
 436         Method* adapter = cp_cache_entry->f1_as_method();
 437         if (adapter == NULL) {
 438           report_error("no adapter found");
 439           return NULL;
 440         }
 441         return adapter->method_holder();
 442       } else if (strcmp(dyno_ref, "<bsm>") == 0) {
 443         int pool_index = cp_cache_entry->constant_pool_index();
 444         BootstrapInfo bootstrap_specifier(cp, pool_index, index);
 445         obj = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), CHECK_NULL);
 446       } else {
 447         report_error("unrecognized token");
 448         return NULL;
 449       }
 450     } else {
 451       // constant pool ref (MethodHandle)
 452       if (strcmp(ref, "cpi") != 0) {
 453         report_error("unexpected token");
 454         return NULL;
 455       }
 456 
 457       Klass* k = parse_klass(CHECK_NULL);
 458       if (k == NULL) {
 459         return NULL;
 460       }
 461       InstanceKlass* ik = InstanceKlass::cast(k);
 462       const constantPoolHandle cp(Thread::current(), ik->constants());
 463 
 464       int cpi = parse_int("cpi");
 465 
 466       if (cpi >= cp->length()) {
 467         report_error("bad cpi");
 468         return NULL;
 469       }
 470       if (!cp->tag_at(cpi).is_method_handle()) {
 471         report_error("no method handle found at cpi");
 472         return NULL;
 473       }
 474       ik->link_class(CHECK_NULL);
 475       obj = cp->resolve_possibly_cached_constant_at(cpi, CHECK_NULL);
 476     }
 477     if (obj == NULL) {
 478       report_error("null cp object found");
 479       return NULL;
 480     }
 481     Klass* k = NULL;
 482     skip_ws();
 483     // loop: read fields
 484     char* field = NULL;
 485     do {
 486       field = parse_string();
 487       if (field == NULL) {
 488         report_error("no field found");
 489         return NULL;
 490       }
 491       if (strcmp(field, ";") == 0) {
 492         break;
 493       }
 494       // raw Method*
 495       if (strcmp(field, "<vmtarget>") == 0) {
 496         Method* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
 497         k = (vmtarget == NULL) ? NULL : vmtarget->method_holder();
 498         if (k == NULL) {
 499           report_error("null vmtarget found");
 500           return NULL;
 501         }
 502         if (!parse_terminator()) {
 503           report_error("missing terminator");
 504           return NULL;
 505         }
 506         return k;
 507       }
 508       obj = ciReplay::obj_field(obj, field);
 509       // array
 510       if (obj != NULL && obj->is_objArray()) {
 511         objArrayOop arr = (objArrayOop)obj;
 512         int index = parse_int("index");
 513         if (index >= arr->length()) {
 514           report_error("bad array index");
 515           return NULL;
 516         }
 517         obj = arr->obj_at(index);
 518       }
 519     } while (obj != NULL);
 520     if (obj == NULL) {
 521       report_error("null field found");
 522       return NULL;
 523     }
 524     k = obj->klass();
 525     return k;
 526   }
 527 
 528   // Parse a valid klass name and look it up
 529   // syntax: <name>
 530   // syntax: <constant pool ref>
 531   Klass* parse_klass(TRAPS) {
 532     skip_ws();
 533     // check for constant pool object reference (for a dynamic/hidden class)
 534     bool cp_ref = (*_bufptr == '@');
 535     if (cp_ref) {
 536       ++_bufptr;
 537       Klass* k = parse_cp_ref(CHECK_NULL);
 538       if (k != NULL && !k->is_hidden()) {
 539         report_error("expected hidden class");
 540         return NULL;
 541       }
 542       return k;
 543     }
 544     char* str = parse_escaped_string();
 545     Symbol* klass_name = SymbolTable::new_symbol(str);
 546     if (klass_name != NULL) {
 547       Klass* k = NULL;
 548       if (_iklass != NULL) {
 549         k = (Klass*)_iklass->find_klass(ciSymbol::make(klass_name->as_C_string()))->constant_encoding();
 550       } else {
 551         k = SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 552       }
 553       if (HAS_PENDING_EXCEPTION) {
 554         oop throwable = PENDING_EXCEPTION;
 555         java_lang_Throwable::print(throwable, tty);
 556         tty->cr();
 557         report_error(str);
 558         if (ReplayIgnoreInitErrors) {
 559           CLEAR_PENDING_EXCEPTION;
 560           _error_message = NULL;
 561         }
 562         return NULL;
 563       }
 564       return k;
 565     }
 566     return NULL;
 567   }
 568 
 569   // Lookup a klass
 570   Klass* resolve_klass(const char* klass, TRAPS) {
 571     Symbol* klass_name = SymbolTable::new_symbol(klass);
 572     return SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 573   }
 574 
 575   // Parse the standard tuple of <klass> <name> <signature>
 576   Method* parse_method(TRAPS) {
 577     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK_NULL);
 578     if (k == NULL) {
 579       report_error("Can't find holder klass");
 580       return NULL;
 581     }
 582     Symbol* method_name = parse_symbol();
 583     Symbol* method_signature = parse_symbol();
 584     Method* m = k->find_method(method_name, method_signature);
 585     if (m == NULL) {
 586       report_error("Can't find method");
 587     }
 588     return m;
 589   }
 590 
 591   int get_line(int c) {
 592     int buffer_pos = 0;
 593     while(c != EOF) {
 594       if (buffer_pos + 1 >= _buffer_length) {
 595         int new_length = _buffer_length * 2;
 596         // Next call will throw error in case of OOM.
 597         _buffer = REALLOC_RESOURCE_ARRAY(char, _buffer, _buffer_length, new_length);
 598         _buffer_length = new_length;
 599       }
 600       if (c == '\n') {
 601         c = getc(_stream); // get next char
 602         break;
 603       } else if (c == '\r') {
 604         // skip LF
 605       } else {
 606         _buffer[buffer_pos++] = c;
 607       }
 608       c = getc(_stream);
 609     }
 610     // null terminate it, reset the pointer
 611     _buffer[buffer_pos] = '\0'; // NL or EOF
 612     _bufptr = _buffer;
 613     return c;
 614   }
 615 
 616   // Process each line of the replay file executing each command until
 617   // the file ends.
 618   void process(TRAPS) {
 619     int line_no = 1;
 620     int c = getc(_stream);
 621     while(c != EOF) {
 622       c = get_line(c);
 623       process_command(THREAD);
 624       if (had_error()) {
 625         int pos = _bufptr - _buffer + 1;
 626         tty->print_cr("Error while parsing line %d at position %d: %s\n", line_no, pos, _error_message);
 627         if (ReplayIgnoreInitErrors) {
 628           CLEAR_PENDING_EXCEPTION;
 629           _error_message = NULL;
 630         } else {
 631           return;
 632         }
 633       }
 634       line_no++;
 635     }
 636     reset();
 637   }
 638 
 639   void process_command(TRAPS) {
 640     char* cmd = parse_string();
 641     if (cmd == NULL) {
 642       return;
 643     }
 644     if (strcmp("#", cmd) == 0) {
 645       // comment line, print or ignore
 646       if (Verbose) {
 647         tty->print_cr("# %s", _bufptr);
 648       }
 649       skip_remaining();
 650     } else if (strcmp("version", cmd) == 0) {
 651       _version = parse_int("version");
 652       if (_version < 0 || _version > REPLAY_VERSION) {
 653         tty->print_cr("# unrecognized version %d, expected 0 <= version <= %d", _version, REPLAY_VERSION);
 654       }
 655     } else if (strcmp("compile", cmd) == 0) {
 656       process_compile(CHECK);
 657     } else if (strcmp("ciMethod", cmd) == 0) {
 658       process_ciMethod(CHECK);
 659     } else if (strcmp("ciMethodData", cmd) == 0) {
 660       process_ciMethodData(CHECK);
 661     } else if (strcmp("staticfield", cmd) == 0) {
 662       process_staticfield(CHECK);
 663     } else if (strcmp("ciInstanceKlass", cmd) == 0) {
 664       process_ciInstanceKlass(CHECK);
 665     } else if (strcmp("instanceKlass", cmd) == 0) {
 666       process_instanceKlass(CHECK);
 667 #if INCLUDE_JVMTI
 668     } else if (strcmp("JvmtiExport", cmd) == 0) {
 669       process_JvmtiExport(CHECK);
 670 #endif // INCLUDE_JVMTI
 671     } else {
 672       report_error("unknown command");
 673     }
 674     if (!had_error() && *_bufptr != '\0') {
 675       report_error("line not properly terminated");
 676     }
 677   }
 678 
 679   // validation of comp_level
 680   bool is_valid_comp_level(int comp_level) {
 681     const int msg_len = 256;
 682     char* msg = NULL;
 683     if (!is_compile(comp_level)) {
 684       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 685       jio_snprintf(msg, msg_len, "%d isn't compilation level", comp_level);
 686     } else if (is_c1_compile(comp_level) && !CompilerConfig::is_c1_enabled()) {
 687       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 688       jio_snprintf(msg, msg_len, "compilation level %d requires C1", comp_level);
 689     } else if (is_c2_compile(comp_level) && !CompilerConfig::is_c2_enabled()) {
 690       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 691       jio_snprintf(msg, msg_len, "compilation level %d requires C2", comp_level);
 692     }
 693     if (msg != NULL) {
 694       report_error(msg);
 695       return false;
 696     }
 697     return true;
 698   }
 699 
 700   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> (<depth> <bci> <klass> <name> <signature>)*
 701   void* process_inline(ciMethod* imethod, Method* m, int entry_bci, int comp_level, TRAPS) {
 702     _imethod    = m;
 703     _iklass     = imethod->holder();
 704     _entry_bci  = entry_bci;
 705     _comp_level = comp_level;
 706     int line_no = 1;
 707     int c = getc(_stream);
 708     while(c != EOF) {
 709       c = get_line(c);
 710       // Expecting only lines with "compile" command in inline replay file.
 711       char* cmd = parse_string();
 712       if (cmd == NULL || strcmp("compile", cmd) != 0) {
 713         return NULL;
 714       }
 715       process_compile(CHECK_NULL);
 716       if (had_error()) {
 717         tty->print_cr("Error while parsing line %d: %s\n", line_no, _error_message);
 718         tty->print_cr("%s", _buffer);
 719         return NULL;
 720       }
 721       if (_ci_inline_records != NULL && _ci_inline_records->length() > 0) {
 722         // Found inlining record for the requested method.
 723         return _ci_inline_records;
 724       }
 725       line_no++;
 726     }
 727     return NULL;
 728   }
 729 
 730   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> (<depth> <bci> <inline_late> <klass> <name> <signature>)*
 731   void process_compile(TRAPS) {
 732     Method* method = parse_method(CHECK);
 733     if (had_error()) return;
 734     int entry_bci = parse_int("entry_bci");
 735     int comp_level = parse_int("comp_level");
 736     if (!is_valid_comp_level(comp_level)) {
 737       return;
 738     }
 739     if (_imethod != NULL) {
 740       // Replay Inlining
 741       if (entry_bci != _entry_bci || comp_level != _comp_level) {
 742         return;
 743       }
 744       const char* iklass_name  = _imethod->method_holder()->name()->as_utf8();
 745       const char* imethod_name = _imethod->name()->as_utf8();
 746       const char* isignature   = _imethod->signature()->as_utf8();
 747       const char* klass_name   = method->method_holder()->name()->as_utf8();
 748       const char* method_name  = method->name()->as_utf8();
 749       const char* signature    = method->signature()->as_utf8();
 750       if (strcmp(iklass_name,  klass_name)  != 0 ||
 751           strcmp(imethod_name, method_name) != 0 ||
 752           strcmp(isignature,   signature)   != 0) {
 753         return;
 754       }
 755     }
 756     int inline_count = 0;
 757     if (parse_tag_and_count("inline", inline_count)) {
 758       // Record inlining data
 759       _ci_inline_records = new GrowableArray<ciInlineRecord*>();
 760       for (int i = 0; i < inline_count; i++) {
 761         int depth = parse_int("inline_depth");
 762         int bci = parse_int("inline_bci");
 763         if (had_error()) {
 764           break;
 765         }
 766         int inline_late = 0;
 767         if (_version >= 2) {
 768           inline_late = parse_int("inline_late");
 769           if (had_error()) {
 770               break;
 771           }
 772         }
 773 
 774         Method* inl_method = parse_method(CHECK);
 775         if (had_error()) {
 776           break;
 777         }
 778         new_ciInlineRecord(inl_method, bci, depth, inline_late);
 779       }
 780     }
 781     if (_imethod != NULL) {
 782       return; // Replay Inlining
 783     }
 784     InstanceKlass* ik = method->method_holder();
 785     ik->initialize(THREAD);
 786     if (HAS_PENDING_EXCEPTION) {
 787       oop throwable = PENDING_EXCEPTION;
 788       java_lang_Throwable::print(throwable, tty);
 789       tty->cr();
 790       if (ReplayIgnoreInitErrors) {
 791         CLEAR_PENDING_EXCEPTION;
 792         ik->set_init_state(InstanceKlass::fully_initialized);
 793       } else {
 794         return;
 795       }
 796     }
 797     // Make sure the existence of a prior compile doesn't stop this one
 798     CompiledMethod* nm = (entry_bci != InvocationEntryBci) ? method->lookup_osr_nmethod_for(entry_bci, comp_level, true) : method->code();
 799     if (nm != NULL) {
 800       nm->make_not_entrant();
 801     }
 802     replay_state = this;
 803     CompileBroker::compile_method(methodHandle(THREAD, method), entry_bci, comp_level,
 804                                   methodHandle(), 0, CompileTask::Reason_Replay, THREAD);
 805     replay_state = NULL;
 806   }
 807 
 808   // ciMethod <klass> <name> <signature> <invocation_counter> <backedge_counter> <interpreter_invocation_count> <interpreter_throwout_count> <instructions_size>
 809   void process_ciMethod(TRAPS) {
 810     Method* method = parse_method(CHECK);
 811     if (had_error()) return;
 812     ciMethodRecord* rec = new_ciMethod(method);
 813     rec->_invocation_counter = parse_int("invocation_counter");
 814     rec->_backedge_counter = parse_int("backedge_counter");
 815     rec->_interpreter_invocation_count = parse_int("interpreter_invocation_count");
 816     rec->_interpreter_throwout_count = parse_int("interpreter_throwout_count");
 817     rec->_instructions_size = parse_int("instructions_size");
 818   }
 819 
 820   // ciMethodData <klass> <name> <signature> <state> <invocation_counter> orig <length> <byte>* data <length> <ptr>* oops <length> (<offset> <klass>)* methods <length> (<offset> <klass> <name> <signature>)*
 821   void process_ciMethodData(TRAPS) {
 822     Method* method = parse_method(CHECK);
 823     if (had_error()) return;
 824     /* just copied from Method, to build interpret data*/
 825 
 826     // To be properly initialized, some profiling in the MDO needs the
 827     // method to be rewritten (number of arguments at a call for
 828     // instance)
 829     method->method_holder()->link_class(CHECK);
 830     // Method::build_profiling_method_data(method, CHECK);
 831     {
 832       // Grab a lock here to prevent multiple
 833       // MethodData*s from being created.
 834       MutexLocker ml(THREAD, MethodData_lock);
 835       if (method->method_data() == NULL) {
 836         ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 837         MethodData* method_data = MethodData::allocate(loader_data, methodHandle(THREAD, method), CHECK);
 838         method->set_method_data(method_data);
 839       }
 840     }
 841 
 842     // collect and record all the needed information for later
 843     ciMethodDataRecord* rec = new_ciMethodData(method);
 844     rec->_state = parse_int("state");
 845     if (_version < 1) {
 846       parse_int("current_mileage");
 847     } else {
 848       rec->_invocation_counter = parse_int("invocation_counter");
 849     }
 850 
 851     rec->_orig_data = parse_data("orig", rec->_orig_data_length);
 852     if (rec->_orig_data == NULL) {
 853       return;
 854     }
 855     rec->_data = parse_intptr_data("data", rec->_data_length);
 856     if (rec->_data == NULL) {
 857       return;
 858     }
 859     if (!parse_tag_and_count("oops", rec->_classes_length)) {
 860       return;
 861     }
 862     rec->_classes = NEW_RESOURCE_ARRAY(Klass*, rec->_classes_length);
 863     rec->_classes_offsets = NEW_RESOURCE_ARRAY(int, rec->_classes_length);
 864     for (int i = 0; i < rec->_classes_length; i++) {
 865       int offset = parse_int("offset");
 866       if (had_error()) {
 867         return;
 868       }
 869       Klass* k = parse_klass(CHECK);
 870       rec->_classes_offsets[i] = offset;
 871       rec->_classes[i] = k;
 872     }
 873 
 874     if (!parse_tag_and_count("methods", rec->_methods_length)) {
 875       return;
 876     }
 877     rec->_methods = NEW_RESOURCE_ARRAY(Method*, rec->_methods_length);
 878     rec->_methods_offsets = NEW_RESOURCE_ARRAY(int, rec->_methods_length);
 879     for (int i = 0; i < rec->_methods_length; i++) {
 880       int offset = parse_int("offset");
 881       if (had_error()) {
 882         return;
 883       }
 884       Method* m = parse_method(CHECK);
 885       rec->_methods_offsets[i] = offset;
 886       rec->_methods[i] = m;
 887     }
 888   }
 889 
 890   // instanceKlass <name>
 891   // instanceKlass <constant pool ref> # <original hidden class name>
 892   //
 893   // Loads and initializes the klass 'name'.  This can be used to
 894   // create particular class loading environments
 895   void process_instanceKlass(TRAPS) {
 896     // just load the referenced class
 897     Klass* k = parse_klass(CHECK);
 898 
 899     if (_version >= 1) {
 900       if (!_protection_domain_initialized && k != NULL) {
 901         assert(_protection_domain() == NULL, "must be uninitialized");
 902         // The first entry is the holder class of the method for which a replay compilation is requested.
 903         // Use the same protection domain to load all subsequent classes in order to resolve all classes
 904         // in signatures of inlinees. This ensures that inlining can be done as stated in the replay file.
 905         _protection_domain = Handle(_thread, k->protection_domain());
 906       }
 907 
 908       _protection_domain_initialized = true;
 909     }
 910 
 911     if (k == NULL) {
 912       return;
 913     }
 914     const char* comment = parse_string();
 915     bool is_comment = comment != NULL && strcmp(comment, "#") == 0;
 916     if (k->is_hidden() != is_comment) {
 917       report_error("hidden class with comment expected");
 918       return;
 919     }
 920     // comment, print or ignore
 921     if (is_comment) {
 922       if (Verbose) {
 923         const char* hidden = parse_string();
 924         tty->print_cr("Found %s for %s", k->name()->as_quoted_ascii(), hidden);
 925       }
 926       skip_remaining();
 927     }
 928   }
 929 
 930   // ciInstanceKlass <name> <is_linked> <is_initialized> <length> tag*
 931   //
 932   // Load the klass 'name' and link or initialize it.  Verify that the
 933   // constant pool is the same length as 'length' and make sure the
 934   // constant pool tags are in the same state.
 935   void process_ciInstanceKlass(TRAPS) {
 936     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK);
 937     if (k == NULL) {
 938       skip_remaining();
 939       return;
 940     }
 941     int is_linked = parse_int("is_linked");
 942     int is_initialized = parse_int("is_initialized");
 943     int length = parse_int("length");
 944     if (is_initialized) {
 945       k->initialize(THREAD);
 946       if (HAS_PENDING_EXCEPTION) {
 947         oop throwable = PENDING_EXCEPTION;
 948         java_lang_Throwable::print(throwable, tty);
 949         tty->cr();
 950         if (ReplayIgnoreInitErrors) {
 951           CLEAR_PENDING_EXCEPTION;
 952           k->set_init_state(InstanceKlass::fully_initialized);
 953         } else {
 954           return;
 955         }
 956       }
 957     } else if (is_linked) {
 958       k->link_class(CHECK);
 959     }
 960     new_ciInstanceKlass(k);
 961     ConstantPool* cp = k->constants();
 962     if (length != cp->length()) {
 963       report_error("constant pool length mismatch: wrong class files?");
 964       return;
 965     }
 966 
 967     int parsed_two_word = 0;
 968     for (int i = 1; i < length; i++) {
 969       int tag = parse_int("tag");
 970       if (had_error()) {
 971         return;
 972       }
 973       switch (cp->tag_at(i).value()) {
 974         case JVM_CONSTANT_UnresolvedClass: {
 975           if (tag == JVM_CONSTANT_Class) {
 976             tty->print_cr("Resolving klass %s at %d", cp->klass_name_at(i)->as_utf8(), i);
 977             Klass* k = cp->klass_at(i, CHECK);
 978           }
 979           break;
 980         }
 981         case JVM_CONSTANT_Long:
 982         case JVM_CONSTANT_Double:
 983           parsed_two_word = i + 1;
 984 
 985         case JVM_CONSTANT_ClassIndex:
 986         case JVM_CONSTANT_StringIndex:
 987         case JVM_CONSTANT_String:
 988         case JVM_CONSTANT_UnresolvedClassInError:
 989         case JVM_CONSTANT_Fieldref:
 990         case JVM_CONSTANT_Methodref:
 991         case JVM_CONSTANT_InterfaceMethodref:
 992         case JVM_CONSTANT_NameAndType:
 993         case JVM_CONSTANT_Utf8:
 994         case JVM_CONSTANT_Integer:
 995         case JVM_CONSTANT_Float:
 996         case JVM_CONSTANT_MethodHandle:
 997         case JVM_CONSTANT_MethodType:
 998         case JVM_CONSTANT_Dynamic:
 999         case JVM_CONSTANT_InvokeDynamic:
1000           if (tag != cp->tag_at(i).value()) {
1001             report_error("tag mismatch: wrong class files?");
1002             return;
1003           }
1004           break;
1005 
1006         case JVM_CONSTANT_Class:
1007           if (tag == JVM_CONSTANT_UnresolvedClass) {
1008             Klass* k = cp->klass_at(i, CHECK);
1009             tty->print_cr("Warning: entry was unresolved in the replay data: %s", k->name()->as_utf8());
1010           } else if (tag != JVM_CONSTANT_Class) {
1011             report_error("Unexpected tag");
1012             return;
1013           }
1014           break;
1015 
1016         case 0:
1017           if (parsed_two_word == i) continue;
1018 
1019         default:
1020           fatal("Unexpected tag: %d", cp->tag_at(i).value());
1021           break;
1022       }
1023 
1024     }
1025   }
1026 
1027   // staticfield <klass> <name> <signature> <value>
1028   //
1029   // Initialize a class and fill in the value for a static field.
1030   // This is useful when the compile was dependent on the value of
1031   // static fields but it's impossible to properly rerun the static
1032   // initializer.
1033   void process_staticfield(TRAPS) {
1034     InstanceKlass* k = (InstanceKlass *)parse_klass(CHECK);
1035 
1036     if (k == NULL || ReplaySuppressInitializers == 0 ||
1037         (ReplaySuppressInitializers == 2 && k->class_loader() == NULL)) {
1038       skip_remaining();
1039       return;
1040     }
1041 
1042     assert(k->is_initialized(), "must be");
1043 
1044     const char* field_name = parse_escaped_string();
1045     const char* field_signature = parse_string();
1046     fieldDescriptor fd;
1047     Symbol* name = SymbolTable::new_symbol(field_name);
1048     Symbol* sig = SymbolTable::new_symbol(field_signature);
1049     if (!k->find_local_field(name, sig, &fd) ||
1050         !fd.is_static() ||
1051         fd.has_initial_value()) {
1052       report_error(field_name);
1053       return;
1054     }
1055 
1056     oop java_mirror = k->java_mirror();
1057     if (field_signature[0] == JVM_SIGNATURE_ARRAY) {
1058       int length = parse_int("array length");
1059       oop value = NULL;
1060 
1061       if (field_signature[1] == JVM_SIGNATURE_ARRAY) {
1062         // multi dimensional array
1063         ArrayKlass* kelem = (ArrayKlass *)parse_klass(CHECK);
1064         if (kelem == NULL) {
1065           return;
1066         }
1067         int rank = 0;
1068         while (field_signature[rank] == JVM_SIGNATURE_ARRAY) {
1069           rank++;
1070         }
1071         jint* dims = NEW_RESOURCE_ARRAY(jint, rank);
1072         dims[0] = length;
1073         for (int i = 1; i < rank; i++) {
1074           dims[i] = 1; // These aren't relevant to the compiler
1075         }
1076         value = kelem->multi_allocate(rank, dims, CHECK);
1077       } else {
1078         if (strcmp(field_signature, "[B") == 0) {
1079           value = oopFactory::new_byteArray(length, CHECK);
1080         } else if (strcmp(field_signature, "[Z") == 0) {
1081           value = oopFactory::new_boolArray(length, CHECK);
1082         } else if (strcmp(field_signature, "[C") == 0) {
1083           value = oopFactory::new_charArray(length, CHECK);
1084         } else if (strcmp(field_signature, "[S") == 0) {
1085           value = oopFactory::new_shortArray(length, CHECK);
1086         } else if (strcmp(field_signature, "[F") == 0) {
1087           value = oopFactory::new_floatArray(length, CHECK);
1088         } else if (strcmp(field_signature, "[D") == 0) {
1089           value = oopFactory::new_doubleArray(length, CHECK);
1090         } else if (strcmp(field_signature, "[I") == 0) {
1091           value = oopFactory::new_intArray(length, CHECK);
1092         } else if (strcmp(field_signature, "[J") == 0) {
1093           value = oopFactory::new_longArray(length, CHECK);
1094         } else if (field_signature[0] == JVM_SIGNATURE_ARRAY &&
1095                    field_signature[1] == JVM_SIGNATURE_CLASS) {
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 NULL;
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 NULL;
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 NULL;
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 != NULL) {
1253       return find_ciInlineRecord(_ci_inline_records, method, bci, depth);
1254     }
1255     return NULL;
1256   }
1257 
1258   static ciInlineRecord* find_ciInlineRecord(GrowableArray<ciInlineRecord*>*  records,
1259                                       Method* method, int bci, int depth) {
1260     if (records != NULL) {
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 NULL;
1276   }
1277 
1278   const char* error_message() {
1279     return _error_message;
1280   }
1281 
1282   void reset() {
1283     _error_message = NULL;
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 == NULL;
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 NULL;
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 NULL;
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 NULL;
1369   }
1370 
1371   if (rp.had_error()) {
1372     tty->print_cr("ciReplay: Failed on %s", rp.error_message());
1373     return NULL;
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 == NULL) {
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 != NULL) {
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()) == NULL;
1480 }
1481 
1482 bool ciReplay::should_inline(void* data, ciMethod* method, int bci, int inline_depth, bool& should_delay) {
1483   if (data != NULL) {
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 == NULL) {
1489       return false;
1490     }
1491     should_delay = record->_inline_late;
1492     return true;
1493   } else if (replay_state != NULL) {
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 == NULL) {
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 != NULL) {
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) == NULL;
1512   } else if (replay_state != NULL) {
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) == NULL;
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 == NULL) {
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->_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 != NULL, "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 != NULL, "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 != NULL;
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 == NULL;
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 != NULL);
1607   return NULL;
1608 }
1609 
1610 oop ciReplay::obj_field(oop obj, const char *name) {
1611   Symbol* fname = SymbolTable::probe(name, (int)strlen(name));
1612   if (fname == NULL) {
1613     return NULL;
1614   }
1615   return obj_field(obj, fname);
1616 }