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 "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.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 instance)
 828     method->method_holder()->link_class(CHECK);
 829     assert(method->method_data() == NULL, "Should only be initialized once");
 830     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 831     MethodData* method_data = MethodData::allocate(loader_data, methodHandle(THREAD, method), CHECK);
 832     method->set_method_data(method_data);
 833 
 834     // collect and record all the needed information for later
 835     ciMethodDataRecord* rec = new_ciMethodData(method);
 836     rec->_state = parse_int("state");
 837     if (_version < 1) {
 838       parse_int("current_mileage");
 839     } else {
 840       rec->_invocation_counter = parse_int("invocation_counter");
 841     }
 842 
 843     rec->_orig_data = parse_data("orig", rec->_orig_data_length);
 844     if (rec->_orig_data == NULL) {
 845       return;
 846     }
 847     rec->_data = parse_intptr_data("data", rec->_data_length);
 848     if (rec->_data == NULL) {
 849       return;
 850     }
 851     if (!parse_tag_and_count("oops", rec->_classes_length)) {
 852       return;
 853     }
 854     rec->_classes = NEW_RESOURCE_ARRAY(Klass*, rec->_classes_length);
 855     rec->_classes_offsets = NEW_RESOURCE_ARRAY(int, rec->_classes_length);
 856     for (int i = 0; i < rec->_classes_length; i++) {
 857       int offset = parse_int("offset");
 858       if (had_error()) {
 859         return;
 860       }
 861       Klass* k = parse_klass(CHECK);
 862       rec->_classes_offsets[i] = offset;
 863       rec->_classes[i] = k;
 864     }
 865 
 866     if (!parse_tag_and_count("methods", rec->_methods_length)) {
 867       return;
 868     }
 869     rec->_methods = NEW_RESOURCE_ARRAY(Method*, rec->_methods_length);
 870     rec->_methods_offsets = NEW_RESOURCE_ARRAY(int, rec->_methods_length);
 871     for (int i = 0; i < rec->_methods_length; i++) {
 872       int offset = parse_int("offset");
 873       if (had_error()) {
 874         return;
 875       }
 876       Method* m = parse_method(CHECK);
 877       rec->_methods_offsets[i] = offset;
 878       rec->_methods[i] = m;
 879     }
 880   }
 881 
 882   // instanceKlass <name>
 883   // instanceKlass <constant pool ref> # <original hidden class name>
 884   //
 885   // Loads and initializes the klass 'name'.  This can be used to
 886   // create particular class loading environments
 887   void process_instanceKlass(TRAPS) {
 888     // just load the referenced class
 889     Klass* k = parse_klass(CHECK);
 890 
 891     if (_version >= 1) {
 892       if (!_protection_domain_initialized && k != NULL) {
 893         assert(_protection_domain() == NULL, "must be uninitialized");
 894         // The first entry is the holder class of the method for which a replay compilation is requested.
 895         // Use the same protection domain to load all subsequent classes in order to resolve all classes
 896         // in signatures of inlinees. This ensures that inlining can be done as stated in the replay file.
 897         _protection_domain = Handle(_thread, k->protection_domain());
 898       }
 899 
 900       _protection_domain_initialized = true;
 901     }
 902 
 903     if (k == NULL) {
 904       return;
 905     }
 906     const char* comment = parse_string();
 907     bool is_comment = comment != NULL && strcmp(comment, "#") == 0;
 908     if (k->is_hidden() != is_comment) {
 909       report_error("hidden class with comment expected");
 910       return;
 911     }
 912     // comment, print or ignore
 913     if (is_comment) {
 914       if (Verbose) {
 915         const char* hidden = parse_string();
 916         tty->print_cr("Found %s for %s", k->name()->as_quoted_ascii(), hidden);
 917       }
 918       skip_remaining();
 919     }
 920   }
 921 
 922   // ciInstanceKlass <name> <is_linked> <is_initialized> <length> tag*
 923   //
 924   // Load the klass 'name' and link or initialize it.  Verify that the
 925   // constant pool is the same length as 'length' and make sure the
 926   // constant pool tags are in the same state.
 927   void process_ciInstanceKlass(TRAPS) {
 928     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK);
 929     if (k == NULL) {
 930       skip_remaining();
 931       return;
 932     }
 933     int is_linked = parse_int("is_linked");
 934     int is_initialized = parse_int("is_initialized");
 935     int length = parse_int("length");
 936     if (is_initialized) {
 937       k->initialize(THREAD);
 938       if (HAS_PENDING_EXCEPTION) {
 939         oop throwable = PENDING_EXCEPTION;
 940         java_lang_Throwable::print(throwable, tty);
 941         tty->cr();
 942         if (ReplayIgnoreInitErrors) {
 943           CLEAR_PENDING_EXCEPTION;
 944           k->set_init_state(InstanceKlass::fully_initialized);
 945         } else {
 946           return;
 947         }
 948       }
 949     } else if (is_linked) {
 950       k->link_class(CHECK);
 951     }
 952     new_ciInstanceKlass(k);
 953     ConstantPool* cp = k->constants();
 954     if (length != cp->length()) {
 955       report_error("constant pool length mismatch: wrong class files?");
 956       return;
 957     }
 958 
 959     int parsed_two_word = 0;
 960     for (int i = 1; i < length; i++) {
 961       int tag = parse_int("tag");
 962       if (had_error()) {
 963         return;
 964       }
 965       switch (cp->tag_at(i).value()) {
 966         case JVM_CONSTANT_UnresolvedClass: {
 967           if (tag == JVM_CONSTANT_Class) {
 968             tty->print_cr("Resolving klass %s at %d", cp->klass_name_at(i)->as_utf8(), i);
 969             Klass* k = cp->klass_at(i, CHECK);
 970           }
 971           break;
 972         }
 973         case JVM_CONSTANT_Long:
 974         case JVM_CONSTANT_Double:
 975           parsed_two_word = i + 1;
 976 
 977         case JVM_CONSTANT_ClassIndex:
 978         case JVM_CONSTANT_StringIndex:
 979         case JVM_CONSTANT_String:
 980         case JVM_CONSTANT_UnresolvedClassInError:
 981         case JVM_CONSTANT_Fieldref:
 982         case JVM_CONSTANT_Methodref:
 983         case JVM_CONSTANT_InterfaceMethodref:
 984         case JVM_CONSTANT_NameAndType:
 985         case JVM_CONSTANT_Utf8:
 986         case JVM_CONSTANT_Integer:
 987         case JVM_CONSTANT_Float:
 988         case JVM_CONSTANT_MethodHandle:
 989         case JVM_CONSTANT_MethodType:
 990         case JVM_CONSTANT_Dynamic:
 991         case JVM_CONSTANT_InvokeDynamic:
 992           if (tag != cp->tag_at(i).value()) {
 993             report_error("tag mismatch: wrong class files?");
 994             return;
 995           }
 996           break;
 997 
 998         case JVM_CONSTANT_Class:
 999           if (tag == JVM_CONSTANT_UnresolvedClass) {
1000             Klass* k = cp->klass_at(i, CHECK);
1001             tty->print_cr("Warning: entry was unresolved in the replay data: %s", k->name()->as_utf8());
1002           } else if (tag != JVM_CONSTANT_Class) {
1003             report_error("Unexpected tag");
1004             return;
1005           }
1006           break;
1007 
1008         case 0:
1009           if (parsed_two_word == i) continue;
1010 
1011         default:
1012           fatal("Unexpected tag: %d", cp->tag_at(i).value());
1013           break;
1014       }
1015 
1016     }
1017   }
1018 
1019   // staticfield <klass> <name> <signature> <value>
1020   //
1021   // Initialize a class and fill in the value for a static field.
1022   // This is useful when the compile was dependent on the value of
1023   // static fields but it's impossible to properly rerun the static
1024   // initializer.
1025   void process_staticfield(TRAPS) {
1026     InstanceKlass* k = (InstanceKlass *)parse_klass(CHECK);
1027 
1028     if (k == NULL || ReplaySuppressInitializers == 0 ||
1029         (ReplaySuppressInitializers == 2 && k->class_loader() == NULL)) {
1030       skip_remaining();
1031       return;
1032     }
1033 
1034     assert(k->is_initialized(), "must be");
1035 
1036     const char* field_name = parse_escaped_string();
1037     const char* field_signature = parse_string();
1038     fieldDescriptor fd;
1039     Symbol* name = SymbolTable::new_symbol(field_name);
1040     Symbol* sig = SymbolTable::new_symbol(field_signature);
1041     if (!k->find_local_field(name, sig, &fd) ||
1042         !fd.is_static() ||
1043         fd.has_initial_value()) {
1044       report_error(field_name);
1045       return;
1046     }
1047 
1048     oop java_mirror = k->java_mirror();
1049     if (field_signature[0] == JVM_SIGNATURE_ARRAY) {
1050       int length = parse_int("array length");
1051       oop value = NULL;
1052 
1053       if (field_signature[1] == JVM_SIGNATURE_ARRAY) {
1054         // multi dimensional array
1055         ArrayKlass* kelem = (ArrayKlass *)parse_klass(CHECK);
1056         if (kelem == NULL) {
1057           return;
1058         }
1059         int rank = 0;
1060         while (field_signature[rank] == JVM_SIGNATURE_ARRAY) {
1061           rank++;
1062         }
1063         jint* dims = NEW_RESOURCE_ARRAY(jint, rank);
1064         dims[0] = length;
1065         for (int i = 1; i < rank; i++) {
1066           dims[i] = 1; // These aren't relevant to the compiler
1067         }
1068         value = kelem->multi_allocate(rank, dims, CHECK);
1069       } else {
1070         if (strcmp(field_signature, "[B") == 0) {
1071           value = oopFactory::new_byteArray(length, CHECK);
1072         } else if (strcmp(field_signature, "[Z") == 0) {
1073           value = oopFactory::new_boolArray(length, CHECK);
1074         } else if (strcmp(field_signature, "[C") == 0) {
1075           value = oopFactory::new_charArray(length, CHECK);
1076         } else if (strcmp(field_signature, "[S") == 0) {
1077           value = oopFactory::new_shortArray(length, CHECK);
1078         } else if (strcmp(field_signature, "[F") == 0) {
1079           value = oopFactory::new_floatArray(length, CHECK);
1080         } else if (strcmp(field_signature, "[D") == 0) {
1081           value = oopFactory::new_doubleArray(length, CHECK);
1082         } else if (strcmp(field_signature, "[I") == 0) {
1083           value = oopFactory::new_intArray(length, CHECK);
1084         } else if (strcmp(field_signature, "[J") == 0) {
1085           value = oopFactory::new_longArray(length, CHECK);
1086         } else if (field_signature[0] == JVM_SIGNATURE_ARRAY &&
1087                    field_signature[1] == JVM_SIGNATURE_CLASS) {
1088           Klass* kelem = resolve_klass(field_signature + 1, CHECK);
1089           value = oopFactory::new_objArray(kelem, length, CHECK);
1090         } else {
1091           report_error("unhandled array staticfield");
1092         }
1093       }
1094       java_mirror->obj_field_put(fd.offset(), value);
1095     } else {
1096       const char* string_value = parse_escaped_string();
1097       if (strcmp(field_signature, "I") == 0) {
1098         int value = atoi(string_value);
1099         java_mirror->int_field_put(fd.offset(), value);
1100       } else if (strcmp(field_signature, "B") == 0) {
1101         int value = atoi(string_value);
1102         java_mirror->byte_field_put(fd.offset(), value);
1103       } else if (strcmp(field_signature, "C") == 0) {
1104         int value = atoi(string_value);
1105         java_mirror->char_field_put(fd.offset(), value);
1106       } else if (strcmp(field_signature, "S") == 0) {
1107         int value = atoi(string_value);
1108         java_mirror->short_field_put(fd.offset(), value);
1109       } else if (strcmp(field_signature, "Z") == 0) {
1110         int value = atoi(string_value);
1111         java_mirror->bool_field_put(fd.offset(), value);
1112       } else if (strcmp(field_signature, "J") == 0) {
1113         jlong value;
1114         if (sscanf(string_value, JLONG_FORMAT, &value) != 1) {
1115           fprintf(stderr, "Error parsing long: %s\n", string_value);
1116           return;
1117         }
1118         java_mirror->long_field_put(fd.offset(), value);
1119       } else if (strcmp(field_signature, "F") == 0) {
1120         float value = atof(string_value);
1121         java_mirror->float_field_put(fd.offset(), value);
1122       } else if (strcmp(field_signature, "D") == 0) {
1123         double value = atof(string_value);
1124         java_mirror->double_field_put(fd.offset(), value);
1125       } else if (strcmp(field_signature, "Ljava/lang/String;") == 0) {
1126         Handle value = java_lang_String::create_from_str(string_value, CHECK);
1127         java_mirror->obj_field_put(fd.offset(), value());
1128       } else if (field_signature[0] == JVM_SIGNATURE_CLASS) {
1129         Klass* k = resolve_klass(string_value, CHECK);
1130         oop value = InstanceKlass::cast(k)->allocate_instance(CHECK);
1131         java_mirror->obj_field_put(fd.offset(), value);
1132       } else {
1133         report_error("unhandled staticfield");
1134       }
1135     }
1136   }
1137 
1138 #if INCLUDE_JVMTI
1139   // JvmtiExport <field> <value>
1140   void process_JvmtiExport(TRAPS) {
1141     const char* field = parse_string();
1142     bool value = parse_int("JvmtiExport flag") != 0;
1143     if (strcmp(field, "can_access_local_variables") == 0) {
1144       JvmtiExport::set_can_access_local_variables(value);
1145     } else if (strcmp(field, "can_hotswap_or_post_breakpoint") == 0) {
1146       JvmtiExport::set_can_hotswap_or_post_breakpoint(value);
1147     } else if (strcmp(field, "can_post_on_exceptions") == 0) {
1148       JvmtiExport::set_can_post_on_exceptions(value);
1149     } else {
1150       report_error("Unrecognized JvmtiExport directive");
1151     }
1152   }
1153 #endif // INCLUDE_JVMTI
1154 
1155   // Create and initialize a record for a ciMethod
1156   ciMethodRecord* new_ciMethod(Method* method) {
1157     ciMethodRecord* rec = NEW_RESOURCE_OBJ(ciMethodRecord);
1158     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1159     rec->_method_name = method->name()->as_utf8();
1160     rec->_signature = method->signature()->as_utf8();
1161     _ci_method_records.append(rec);
1162     return rec;
1163   }
1164 
1165   // Lookup data for a ciMethod
1166   ciMethodRecord* find_ciMethodRecord(Method* method) {
1167     const char* klass_name =  method->method_holder()->name()->as_utf8();
1168     const char* method_name = method->name()->as_utf8();
1169     const char* signature = method->signature()->as_utf8();
1170     for (int i = 0; i < _ci_method_records.length(); i++) {
1171       ciMethodRecord* rec = _ci_method_records.at(i);
1172       if (strcmp(rec->_klass_name, klass_name) == 0 &&
1173           strcmp(rec->_method_name, method_name) == 0 &&
1174           strcmp(rec->_signature, signature) == 0) {
1175         return rec;
1176       }
1177     }
1178     return NULL;
1179   }
1180 
1181   // Create and initialize a record for a ciInstanceKlass which was present at replay dump time.
1182   void new_ciInstanceKlass(const InstanceKlass* klass) {
1183     ciInstanceKlassRecord* rec = NEW_RESOURCE_OBJ(ciInstanceKlassRecord);
1184     rec->_klass = klass;
1185     oop java_mirror = klass->java_mirror();
1186     Handle h_java_mirror(_thread, java_mirror);
1187     rec->_java_mirror = JNIHandles::make_global(h_java_mirror);
1188     _ci_instance_klass_records.append(rec);
1189   }
1190 
1191   // Check if a ciInstanceKlass was present at replay dump time for a klass.
1192   ciInstanceKlassRecord* find_ciInstanceKlass(const InstanceKlass* klass) {
1193     for (int i = 0; i < _ci_instance_klass_records.length(); i++) {
1194       ciInstanceKlassRecord* rec = _ci_instance_klass_records.at(i);
1195       if (klass == rec->_klass) {
1196         // ciInstanceKlass for this klass was resolved.
1197         return rec;
1198       }
1199     }
1200     return NULL;
1201   }
1202 
1203   // Create and initialize a record for a ciMethodData
1204   ciMethodDataRecord* new_ciMethodData(Method* method) {
1205     ciMethodDataRecord* rec = NEW_RESOURCE_OBJ(ciMethodDataRecord);
1206     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1207     rec->_method_name = method->name()->as_utf8();
1208     rec->_signature = method->signature()->as_utf8();
1209     _ci_method_data_records.append(rec);
1210     return rec;
1211   }
1212 
1213   // Lookup data for a ciMethodData
1214   ciMethodDataRecord* find_ciMethodDataRecord(Method* method) {
1215     const char* klass_name =  method->method_holder()->name()->as_utf8();
1216     const char* method_name = method->name()->as_utf8();
1217     const char* signature = method->signature()->as_utf8();
1218     for (int i = 0; i < _ci_method_data_records.length(); i++) {
1219       ciMethodDataRecord* rec = _ci_method_data_records.at(i);
1220       if (strcmp(rec->_klass_name, klass_name) == 0 &&
1221           strcmp(rec->_method_name, method_name) == 0 &&
1222           strcmp(rec->_signature, signature) == 0) {
1223         return rec;
1224       }
1225     }
1226     return NULL;
1227   }
1228 
1229   // Create and initialize a record for a ciInlineRecord
1230   ciInlineRecord* new_ciInlineRecord(Method* method, int bci, int depth, int inline_late) {
1231     ciInlineRecord* rec = NEW_RESOURCE_OBJ(ciInlineRecord);
1232     rec->_klass_name =  method->method_holder()->name()->as_utf8();
1233     rec->_method_name = method->name()->as_utf8();
1234     rec->_signature = method->signature()->as_utf8();
1235     rec->_inline_bci = bci;
1236     rec->_inline_depth = depth;
1237     rec->_inline_late = inline_late;
1238     _ci_inline_records->append(rec);
1239     return rec;
1240   }
1241 
1242   // Lookup inlining data for a ciMethod
1243   ciInlineRecord* find_ciInlineRecord(Method* method, int bci, int depth) {
1244     if (_ci_inline_records != NULL) {
1245       return find_ciInlineRecord(_ci_inline_records, method, bci, depth);
1246     }
1247     return NULL;
1248   }
1249 
1250   static ciInlineRecord* find_ciInlineRecord(GrowableArray<ciInlineRecord*>*  records,
1251                                       Method* method, int bci, int depth) {
1252     if (records != NULL) {
1253       const char* klass_name  = method->method_holder()->name()->as_utf8();
1254       const char* method_name = method->name()->as_utf8();
1255       const char* signature   = method->signature()->as_utf8();
1256       for (int i = 0; i < records->length(); i++) {
1257         ciInlineRecord* rec = records->at(i);
1258         if ((rec->_inline_bci == bci) &&
1259             (rec->_inline_depth == depth) &&
1260             (strcmp(rec->_klass_name, klass_name) == 0) &&
1261             (strcmp(rec->_method_name, method_name) == 0) &&
1262             (strcmp(rec->_signature, signature) == 0)) {
1263           return rec;
1264         }
1265       }
1266     }
1267     return NULL;
1268   }
1269 
1270   const char* error_message() {
1271     return _error_message;
1272   }
1273 
1274   void reset() {
1275     _error_message = NULL;
1276     _ci_method_records.clear();
1277     _ci_method_data_records.clear();
1278   }
1279 
1280   // Take an ascii string contain \u#### escapes and convert it to utf8
1281   // in place.
1282   static void unescape_string(char* value) {
1283     char* from = value;
1284     char* to = value;
1285     while (*from != '\0') {
1286       if (*from != '\\') {
1287         *from++ = *to++;
1288       } else {
1289         switch (from[1]) {
1290           case 'u': {
1291             from += 2;
1292             jchar value=0;
1293             for (int i=0; i<4; i++) {
1294               char c = *from++;
1295               switch (c) {
1296                 case '0': case '1': case '2': case '3': case '4':
1297                 case '5': case '6': case '7': case '8': case '9':
1298                   value = (value << 4) + c - '0';
1299                   break;
1300                 case 'a': case 'b': case 'c':
1301                 case 'd': case 'e': case 'f':
1302                   value = (value << 4) + 10 + c - 'a';
1303                   break;
1304                 case 'A': case 'B': case 'C':
1305                 case 'D': case 'E': case 'F':
1306                   value = (value << 4) + 10 + c - 'A';
1307                   break;
1308                 default:
1309                   ShouldNotReachHere();
1310               }
1311             }
1312             UNICODE::convert_to_utf8(&value, 1, to);
1313             to++;
1314             break;
1315           }
1316           case 't': *to++ = '\t'; from += 2; break;
1317           case 'n': *to++ = '\n'; from += 2; break;
1318           case 'r': *to++ = '\r'; from += 2; break;
1319           case 'f': *to++ = '\f'; from += 2; break;
1320           default:
1321             ShouldNotReachHere();
1322         }
1323       }
1324     }
1325     *from = *to;
1326   }
1327 };
1328 
1329 void ciReplay::replay(TRAPS) {
1330   int exit_code = replay_impl(THREAD);
1331 
1332   Threads::destroy_vm();
1333 
1334   vm_exit(exit_code);
1335 }
1336 
1337 bool ciReplay::no_replay_state() {
1338   return replay_state == NULL;
1339 }
1340 
1341 void* ciReplay::load_inline_data(ciMethod* method, int entry_bci, int comp_level) {
1342   if (FLAG_IS_DEFAULT(InlineDataFile)) {
1343     tty->print_cr("ERROR: no inline replay data file specified (use -XX:InlineDataFile=inline_pid12345.txt).");
1344     return NULL;
1345   }
1346 
1347   VM_ENTRY_MARK;
1348   // Load and parse the replay data
1349   CompileReplay rp(InlineDataFile, THREAD);
1350   if (!rp.can_replay()) {
1351     tty->print_cr("ciReplay: !rp.can_replay()");
1352     return NULL;
1353   }
1354   void* data = rp.process_inline(method, method->get_Method(), entry_bci, comp_level, THREAD);
1355   if (HAS_PENDING_EXCEPTION) {
1356     Handle throwable(THREAD, PENDING_EXCEPTION);
1357     CLEAR_PENDING_EXCEPTION;
1358     java_lang_Throwable::print_stack_trace(throwable, tty);
1359     tty->cr();
1360     return NULL;
1361   }
1362 
1363   if (rp.had_error()) {
1364     tty->print_cr("ciReplay: Failed on %s", rp.error_message());
1365     return NULL;
1366   }
1367   return data;
1368 }
1369 
1370 int ciReplay::replay_impl(TRAPS) {
1371   HandleMark hm(THREAD);
1372   ResourceMark rm(THREAD);
1373 
1374   if (ReplaySuppressInitializers > 2) {
1375     // ReplaySuppressInitializers > 2 means that we want to allow
1376     // normal VM bootstrap but once we get into the replay itself
1377     // don't allow any initializers to be run.
1378     ReplaySuppressInitializers = 1;
1379   }
1380 
1381   if (FLAG_IS_DEFAULT(ReplayDataFile)) {
1382     tty->print_cr("ERROR: no compiler replay data file specified (use -XX:ReplayDataFile=replay_pid12345.txt).");
1383     return 1;
1384   }
1385 
1386   // Load and parse the replay data
1387   CompileReplay rp(ReplayDataFile, THREAD);
1388   int exit_code = 0;
1389   if (rp.can_replay()) {
1390     rp.process(THREAD);
1391   } else {
1392     exit_code = 1;
1393     return exit_code;
1394   }
1395 
1396   if (HAS_PENDING_EXCEPTION) {
1397     Handle throwable(THREAD, PENDING_EXCEPTION);
1398     CLEAR_PENDING_EXCEPTION;
1399     java_lang_Throwable::print_stack_trace(throwable, tty);
1400     tty->cr();
1401     exit_code = 2;
1402   }
1403 
1404   if (rp.had_error()) {
1405     tty->print_cr("Failed on %s", rp.error_message());
1406     exit_code = 1;
1407   }
1408   return exit_code;
1409 }
1410 
1411 void ciReplay::initialize(ciMethodData* m) {
1412   if (no_replay_state()) {
1413     return;
1414   }
1415 
1416   ASSERT_IN_VM;
1417   ResourceMark rm;
1418 
1419   Method* method = m->get_MethodData()->method();
1420   ciMethodDataRecord* rec = replay_state->find_ciMethodDataRecord(method);
1421   if (rec == NULL) {
1422     // This indicates some mismatch with the original environment and
1423     // the replay environment though it's not always enough to
1424     // interfere with reproducing a bug
1425     tty->print_cr("Warning: requesting ciMethodData record for method with no data: ");
1426     method->print_name(tty);
1427     tty->cr();
1428   } else {
1429     m->_state = rec->_state;
1430     m->_invocation_counter = rec->_invocation_counter;
1431     if (rec->_data_length != 0) {
1432       assert(m->_data_size + m->_extra_data_size == rec->_data_length * (int)sizeof(rec->_data[0]) ||
1433              m->_data_size == rec->_data_length * (int)sizeof(rec->_data[0]), "must agree");
1434 
1435       // Write the correct ciObjects back into the profile data
1436       ciEnv* env = ciEnv::current();
1437       for (int i = 0; i < rec->_classes_length; i++) {
1438         Klass *k = rec->_classes[i];
1439         // In case this class pointer is is tagged, preserve the tag bits
1440         intptr_t status = 0;
1441         if (k != NULL) {
1442           status = ciTypeEntries::with_status(env->get_metadata(k)->as_klass(), rec->_data[rec->_classes_offsets[i]]);
1443         }
1444         rec->_data[rec->_classes_offsets[i]] = status;
1445       }
1446       for (int i = 0; i < rec->_methods_length; i++) {
1447         Method *m = rec->_methods[i];
1448         *(ciMetadata**)(rec->_data + rec->_methods_offsets[i]) =
1449           env->get_metadata(m);
1450       }
1451       // Copy the updated profile data into place as intptr_ts
1452 #ifdef _LP64
1453       Copy::conjoint_jlongs_atomic((jlong *)rec->_data, (jlong *)m->_data, rec->_data_length);
1454 #else
1455       Copy::conjoint_jints_atomic((jint *)rec->_data, (jint *)m->_data, rec->_data_length);
1456 #endif
1457     }
1458 
1459     // copy in the original header
1460     Copy::conjoint_jbytes(rec->_orig_data, (char*)&m->_orig, rec->_orig_data_length);
1461   }
1462 }
1463 
1464 
1465 bool ciReplay::should_not_inline(ciMethod* method) {
1466   if (no_replay_state()) {
1467     return false;
1468   }
1469   VM_ENTRY_MARK;
1470   // ciMethod without a record shouldn't be inlined.
1471   return replay_state->find_ciMethodRecord(method->get_Method()) == NULL;
1472 }
1473 
1474 bool ciReplay::should_inline(void* data, ciMethod* method, int bci, int inline_depth, bool& should_delay) {
1475   if (data != NULL) {
1476     GrowableArray<ciInlineRecord*>* records = (GrowableArray<ciInlineRecord*>*)data;
1477     VM_ENTRY_MARK;
1478     // Inline record are ordered by bci and depth.
1479     ciInlineRecord* record = CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth);
1480     if (record == NULL) {
1481       return false;
1482     }
1483     should_delay = record->_inline_late;
1484     return true;
1485   } else if (replay_state != NULL) {
1486     VM_ENTRY_MARK;
1487     // Inline record are ordered by bci and depth.
1488     ciInlineRecord* record = replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth);
1489     if (record == NULL) {
1490       return false;
1491     }
1492     should_delay = record->_inline_late;
1493     return true;
1494   }
1495   return false;
1496 }
1497 
1498 bool ciReplay::should_not_inline(void* data, ciMethod* method, int bci, int inline_depth) {
1499   if (data != NULL) {
1500     GrowableArray<ciInlineRecord*>* records = (GrowableArray<ciInlineRecord*>*)data;
1501     VM_ENTRY_MARK;
1502     // Inline record are ordered by bci and depth.
1503     return CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth) == NULL;
1504   } else if (replay_state != NULL) {
1505     VM_ENTRY_MARK;
1506     // Inline record are ordered by bci and depth.
1507     return replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth) == NULL;
1508   }
1509   return false;
1510 }
1511 
1512 void ciReplay::initialize(ciMethod* m) {
1513   if (no_replay_state()) {
1514     return;
1515   }
1516 
1517   ASSERT_IN_VM;
1518   ResourceMark rm;
1519 
1520   Method* method = m->get_Method();
1521   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1522   if (rec == NULL) {
1523     // This indicates some mismatch with the original environment and
1524     // the replay environment though it's not always enough to
1525     // interfere with reproducing a bug
1526     tty->print_cr("Warning: requesting ciMethod record for method with no data: ");
1527     method->print_name(tty);
1528     tty->cr();
1529   } else {
1530     EXCEPTION_CONTEXT;
1531     // m->_instructions_size = rec->_instructions_size;
1532     m->_instructions_size = -1;
1533     m->_interpreter_invocation_count = rec->_interpreter_invocation_count;
1534     m->_interpreter_throwout_count = rec->_interpreter_throwout_count;
1535     MethodCounters* mcs = method->get_method_counters(CHECK_AND_CLEAR);
1536     guarantee(mcs != NULL, "method counters allocation failed");
1537     mcs->invocation_counter()->_counter = rec->_invocation_counter;
1538     mcs->backedge_counter()->_counter = rec->_backedge_counter;
1539   }
1540 }
1541 
1542 void ciReplay::initialize(ciInstanceKlass* ci_ik, InstanceKlass* ik) {
1543   assert(!no_replay_state(), "must have replay state");
1544 
1545   ASSERT_IN_VM;
1546   ciInstanceKlassRecord* rec = replay_state->find_ciInstanceKlass(ik);
1547   assert(rec != NULL, "ciInstanceKlass must be whitelisted");
1548   ci_ik->_java_mirror = CURRENT_ENV->get_instance(JNIHandles::resolve(rec->_java_mirror));
1549 }
1550 
1551 bool ciReplay::is_loaded(Method* method) {
1552   if (no_replay_state()) {
1553     return true;
1554   }
1555 
1556   ASSERT_IN_VM;
1557   ResourceMark rm;
1558 
1559   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1560   return rec != NULL;
1561 }
1562 
1563 bool ciReplay::is_klass_unresolved(const InstanceKlass* klass) {
1564   if (no_replay_state()) {
1565     return false;
1566   }
1567 
1568   // Check if klass is found on whitelist.
1569   ciInstanceKlassRecord* rec = replay_state->find_ciInstanceKlass(klass);
1570   return rec == NULL;
1571 }
1572 
1573 oop ciReplay::obj_field(oop obj, Symbol* name) {
1574   InstanceKlass* ik = InstanceKlass::cast(obj->klass());
1575 
1576   do {
1577     if (!ik->has_nonstatic_fields()) {
1578       ik = ik->java_super();
1579       continue;
1580     }
1581 
1582     for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
1583       if (fs.access_flags().is_static()) {
1584         continue;
1585       }
1586       if (fs.name() == name) {
1587         int offset = fs.offset();
1588 #ifdef ASSERT
1589         fieldDescriptor fd = fs.field_descriptor();
1590         assert(fd.offset() == ik->field_offset(fd.index()), "!");
1591 #endif
1592         oop f = obj->obj_field(offset);
1593         return f;
1594       }
1595     }
1596 
1597     ik = ik->java_super();
1598   } while (ik != NULL);
1599   return NULL;
1600 }
1601 
1602 oop ciReplay::obj_field(oop obj, const char *name) {
1603   Symbol* fname = SymbolTable::probe(name, (int)strlen(name));
1604   if (fname == NULL) {
1605     return NULL;
1606   }
1607   return obj_field(obj, fname);
1608 }