1 /*
   2  * Copyright (c) 2013, 2018, 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 "compiler/compileBroker.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "memory/oopFactory.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "oops/method.inline.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "utilities/copy.hpp"
  39 #include "utilities/macros.hpp"
  40 
  41 #ifndef PRODUCT
  42 
  43 // ciReplay
  44 
  45 typedef struct _ciMethodDataRecord {
  46   const char* _klass_name;
  47   const char* _method_name;
  48   const char* _signature;
  49 
  50   int _state;
  51   int _current_mileage;
  52 
  53   intptr_t* _data;
  54   char*     _orig_data;
  55   Klass**   _classes;
  56   Method**  _methods;
  57   int*      _classes_offsets;
  58   int*      _methods_offsets;
  59   int       _data_length;
  60   int       _orig_data_length;
  61   int       _classes_length;
  62   int       _methods_length;
  63 } ciMethodDataRecord;
  64 
  65 typedef struct _ciMethodRecord {
  66   const char* _klass_name;
  67   const char* _method_name;
  68   const char* _signature;
  69 
  70   int _instructions_size;
  71   int _interpreter_invocation_count;
  72   int _interpreter_throwout_count;
  73   int _invocation_counter;
  74   int _backedge_counter;
  75 } ciMethodRecord;
  76 
  77 typedef struct _ciInlineRecord {
  78   const char* _klass_name;
  79   const char* _method_name;
  80   const char* _signature;
  81 
  82   int _inline_depth;
  83   int _inline_bci;
  84 } ciInlineRecord;
  85 
  86 class  CompileReplay;
  87 static CompileReplay* replay_state;
  88 
  89 class CompileReplay : public StackObj {
  90  private:
  91   FILE*   _stream;
  92   Thread* _thread;
  93   Handle  _protection_domain;
  94   Handle  _loader;
  95 
  96   GrowableArray<ciMethodRecord*>     _ci_method_records;
  97   GrowableArray<ciMethodDataRecord*> _ci_method_data_records;
  98 
  99   // Use pointer because we may need to return inline records
 100   // without destroying them.
 101   GrowableArray<ciInlineRecord*>*    _ci_inline_records;
 102 
 103   const char* _error_message;
 104 
 105   char* _bufptr;
 106   char* _buffer;
 107   int   _buffer_length;
 108   int   _buffer_pos;
 109 
 110   // "compile" data
 111   ciKlass* _iklass;
 112   Method*  _imethod;
 113   int      _entry_bci;
 114   int      _comp_level;
 115 
 116  public:
 117   CompileReplay(const char* filename, TRAPS) {
 118     _thread = THREAD;
 119     _loader = Handle(_thread, SystemDictionary::java_system_loader());
 120     _protection_domain = Handle();
 121 
 122     _stream = fopen(filename, "rt");
 123     if (_stream == NULL) {
 124       fprintf(stderr, "ERROR: Can't open replay file %s\n", filename);
 125     }
 126 
 127     _ci_inline_records = NULL;
 128     _error_message = NULL;
 129 
 130     _buffer_length = 32;
 131     _buffer = NEW_RESOURCE_ARRAY(char, _buffer_length);
 132     _bufptr = _buffer;
 133     _buffer_pos = 0;
 134 
 135     _imethod = NULL;
 136     _iklass  = NULL;
 137     _entry_bci  = 0;
 138     _comp_level = 0;
 139 
 140     test();
 141   }
 142 
 143   ~CompileReplay() {
 144     if (_stream != NULL) fclose(_stream);
 145   }
 146 
 147   void test() {
 148     strcpy(_buffer, "1 2 foo 4 bar 0x9 \"this is it\"");
 149     _bufptr = _buffer;
 150     assert(parse_int("test") == 1, "what");
 151     assert(parse_int("test") == 2, "what");
 152     assert(strcmp(parse_string(), "foo") == 0, "what");
 153     assert(parse_int("test") == 4, "what");
 154     assert(strcmp(parse_string(), "bar") == 0, "what");
 155     assert(parse_intptr_t("test") == 9, "what");
 156     assert(strcmp(parse_quoted_string(), "this is it") == 0, "what");
 157   }
 158 
 159   bool had_error() {
 160     return _error_message != NULL || _thread->has_pending_exception();
 161   }
 162 
 163   bool can_replay() {
 164     return !(_stream == NULL || had_error());
 165   }
 166 
 167   void report_error(const char* msg) {
 168     _error_message = msg;
 169     // Restore the _buffer contents for error reporting
 170     for (int i = 0; i < _buffer_pos; i++) {
 171       if (_buffer[i] == '\0') _buffer[i] = ' ';
 172     }
 173   }
 174 
 175   int parse_int(const char* label) {
 176     if (had_error()) {
 177       return 0;
 178     }
 179 
 180     int v = 0;
 181     int read;
 182     if (sscanf(_bufptr, "%i%n", &v, &read) != 1) {
 183       report_error(label);
 184     } else {
 185       _bufptr += read;
 186     }
 187     return v;
 188   }
 189 
 190   intptr_t parse_intptr_t(const char* label) {
 191     if (had_error()) {
 192       return 0;
 193     }
 194 
 195     intptr_t v = 0;
 196     int read;
 197     if (sscanf(_bufptr, INTPTR_FORMAT "%n", &v, &read) != 1) {
 198       report_error(label);
 199     } else {
 200       _bufptr += read;
 201     }
 202     return v;
 203   }
 204 
 205   void skip_ws() {
 206     // Skip any leading whitespace
 207     while (*_bufptr == ' ' || *_bufptr == '\t') {
 208       _bufptr++;
 209     }
 210   }
 211 
 212 
 213   char* scan_and_terminate(char delim) {
 214     char* str = _bufptr;
 215     while (*_bufptr != delim && *_bufptr != '\0') {
 216       _bufptr++;
 217     }
 218     if (*_bufptr != '\0') {
 219       *_bufptr++ = '\0';
 220     }
 221     if (_bufptr == str) {
 222       // nothing here
 223       return NULL;
 224     }
 225     return str;
 226   }
 227 
 228   char* parse_string() {
 229     if (had_error()) return NULL;
 230 
 231     skip_ws();
 232     return scan_and_terminate(' ');
 233   }
 234 
 235   char* parse_quoted_string() {
 236     if (had_error()) return NULL;
 237 
 238     skip_ws();
 239 
 240     if (*_bufptr == '"') {
 241       _bufptr++;
 242       return scan_and_terminate('"');
 243     } else {
 244       return scan_and_terminate(' ');
 245     }
 246   }
 247 
 248   const char* parse_escaped_string() {
 249     char* result = parse_quoted_string();
 250     if (result != NULL) {
 251       unescape_string(result);
 252     }
 253     return result;
 254   }
 255 
 256   // Look for the tag 'tag' followed by an
 257   bool parse_tag_and_count(const char* tag, int& length) {
 258     const char* t = parse_string();
 259     if (t == NULL) {
 260       return false;
 261     }
 262 
 263     if (strcmp(tag, t) != 0) {
 264       report_error(tag);
 265       return false;
 266     }
 267     length = parse_int("parse_tag_and_count");
 268     return !had_error();
 269   }
 270 
 271   // Parse a sequence of raw data encoded as bytes and return the
 272   // resulting data.
 273   char* parse_data(const char* tag, int& length) {
 274     if (!parse_tag_and_count(tag, length)) {
 275       return NULL;
 276     }
 277 
 278     char * result = NEW_RESOURCE_ARRAY(char, length);
 279     for (int i = 0; i < length; i++) {
 280       int val = parse_int("data");
 281       result[i] = val;
 282     }
 283     return result;
 284   }
 285 
 286   // Parse a standard chunk of data emitted as:
 287   //   'tag' <length> # # ...
 288   // Where each # is an intptr_t item
 289   intptr_t* parse_intptr_data(const char* tag, int& length) {
 290     if (!parse_tag_and_count(tag, length)) {
 291       return NULL;
 292     }
 293 
 294     intptr_t* result = NEW_RESOURCE_ARRAY(intptr_t, length);
 295     for (int i = 0; i < length; i++) {
 296       skip_ws();
 297       intptr_t val = parse_intptr_t("data");
 298       result[i] = val;
 299     }
 300     return result;
 301   }
 302 
 303   // Parse a possibly quoted version of a symbol into a symbolOop
 304   Symbol* parse_symbol(TRAPS) {
 305     const char* str = parse_escaped_string();
 306     if (str != NULL) {
 307       Symbol* sym = SymbolTable::lookup(str, (int)strlen(str), CHECK_NULL);
 308       return sym;
 309     }
 310     return NULL;
 311   }
 312 
 313   // Parse a valid klass name and look it up
 314   Klass* parse_klass(TRAPS) {
 315     const char* str = parse_escaped_string();
 316     Symbol* klass_name = SymbolTable::lookup(str, (int)strlen(str), CHECK_NULL);
 317     if (klass_name != NULL) {
 318       Klass* k = NULL;
 319       if (_iklass != NULL) {
 320         k = (Klass*)_iklass->find_klass(ciSymbol::make(klass_name->as_C_string()))->constant_encoding();
 321       } else {
 322         k = SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 323       }
 324       if (HAS_PENDING_EXCEPTION) {
 325         oop throwable = PENDING_EXCEPTION;
 326         java_lang_Throwable::print(throwable, tty);
 327         tty->cr();
 328         report_error(str);
 329         if (ReplayIgnoreInitErrors) {
 330           CLEAR_PENDING_EXCEPTION;
 331           _error_message = NULL;
 332         }
 333         return NULL;
 334       }
 335       return k;
 336     }
 337     return NULL;
 338   }
 339 
 340   // Lookup a klass
 341   Klass* resolve_klass(const char* klass, TRAPS) {
 342     Symbol* klass_name = SymbolTable::lookup(klass, (int)strlen(klass), CHECK_NULL);
 343     return SystemDictionary::resolve_or_fail(klass_name, _loader, _protection_domain, true, THREAD);
 344   }
 345 
 346   // Parse the standard tuple of <klass> <name> <signature>
 347   Method* parse_method(TRAPS) {
 348     InstanceKlass* k = (InstanceKlass*)parse_klass(CHECK_NULL);
 349     if (k == NULL) {
 350       report_error("Can't find holder klass");
 351       return NULL;
 352     }
 353     Symbol* method_name = parse_symbol(CHECK_NULL);
 354     Symbol* method_signature = parse_symbol(CHECK_NULL);
 355     Method* m = k->find_method(method_name, method_signature);
 356     if (m == NULL) {
 357       report_error("Can't find method");
 358     }
 359     return m;
 360   }
 361 
 362   int get_line(int c) {
 363     while(c != EOF) {
 364       if (_buffer_pos + 1 >= _buffer_length) {
 365         int new_length = _buffer_length * 2;
 366         // Next call will throw error in case of OOM.
 367         _buffer = REALLOC_RESOURCE_ARRAY(char, _buffer, _buffer_length, new_length);
 368         _buffer_length = new_length;
 369       }
 370       if (c == '\n') {
 371         c = getc(_stream); // get next char
 372         break;
 373       } else if (c == '\r') {
 374         // skip LF
 375       } else {
 376         _buffer[_buffer_pos++] = c;
 377       }
 378       c = getc(_stream);
 379     }
 380     // null terminate it, reset the pointer
 381     _buffer[_buffer_pos] = '\0'; // NL or EOF
 382     _buffer_pos = 0;
 383     _bufptr = _buffer;
 384     return c;
 385   }
 386 
 387   // Process each line of the replay file executing each command until
 388   // the file ends.
 389   void process(TRAPS) {
 390     int line_no = 1;
 391     int c = getc(_stream);
 392     while(c != EOF) {
 393       c = get_line(c);
 394       process_command(THREAD);
 395       if (had_error()) {
 396         tty->print_cr("Error while parsing line %d: %s\n", line_no, _error_message);
 397         if (ReplayIgnoreInitErrors) {
 398           CLEAR_PENDING_EXCEPTION;
 399           _error_message = NULL;
 400         } else {
 401           return;
 402         }
 403       }
 404       line_no++;
 405     }
 406   }
 407 
 408   void process_command(TRAPS) {
 409     char* cmd = parse_string();
 410     if (cmd == NULL) {
 411       return;
 412     }
 413     if (strcmp("#", cmd) == 0) {
 414       // ignore
 415     } else if (strcmp("compile", cmd) == 0) {
 416       process_compile(CHECK);
 417     } else if (strcmp("ciMethod", cmd) == 0) {
 418       process_ciMethod(CHECK);
 419     } else if (strcmp("ciMethodData", cmd) == 0) {
 420       process_ciMethodData(CHECK);
 421     } else if (strcmp("staticfield", cmd) == 0) {
 422       process_staticfield(CHECK);
 423     } else if (strcmp("ciInstanceKlass", cmd) == 0) {
 424       process_ciInstanceKlass(CHECK);
 425     } else if (strcmp("instanceKlass", cmd) == 0) {
 426       process_instanceKlass(CHECK);
 427 #if INCLUDE_JVMTI
 428     } else if (strcmp("JvmtiExport", cmd) == 0) {
 429       process_JvmtiExport(CHECK);
 430 #endif // INCLUDE_JVMTI
 431     } else {
 432       report_error("unknown command");
 433     }
 434   }
 435 
 436   // validation of comp_level
 437   bool is_valid_comp_level(int comp_level) {
 438     const int msg_len = 256;
 439     char* msg = NULL;
 440     if (!is_compile(comp_level)) {
 441       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 442       jio_snprintf(msg, msg_len, "%d isn't compilation level", comp_level);
 443     } else if (!TieredCompilation && (comp_level != CompLevel_highest_tier)) {
 444       msg = NEW_RESOURCE_ARRAY(char, msg_len);
 445       switch (comp_level) {
 446         case CompLevel_simple:
 447           jio_snprintf(msg, msg_len, "compilation level %d requires Client VM or TieredCompilation", comp_level);
 448           break;
 449         case CompLevel_full_optimization:
 450           jio_snprintf(msg, msg_len, "compilation level %d requires Server VM", comp_level);
 451           break;
 452         default:
 453           jio_snprintf(msg, msg_len, "compilation level %d requires TieredCompilation", comp_level);
 454       }
 455     }
 456     if (msg != NULL) {
 457       report_error(msg);
 458       return false;
 459     }
 460     return true;
 461   }
 462 
 463   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> <depth> <bci> <klass> <name> <signature> ...
 464   void* process_inline(ciMethod* imethod, Method* m, int entry_bci, int comp_level, TRAPS) {
 465     _imethod    = m;
 466     _iklass     = imethod->holder();
 467     _entry_bci  = entry_bci;
 468     _comp_level = comp_level;
 469     int line_no = 1;
 470     int c = getc(_stream);
 471     while(c != EOF) {
 472       c = get_line(c);
 473       // Expecting only lines with "compile" command in inline replay file.
 474       char* cmd = parse_string();
 475       if (cmd == NULL || strcmp("compile", cmd) != 0) {
 476         return NULL;
 477       }
 478       process_compile(CHECK_NULL);
 479       if (had_error()) {
 480         tty->print_cr("Error while parsing line %d: %s\n", line_no, _error_message);
 481         tty->print_cr("%s", _buffer);
 482         return NULL;
 483       }
 484       if (_ci_inline_records != NULL && _ci_inline_records->length() > 0) {
 485         // Found inlining record for the requested method.
 486         return _ci_inline_records;
 487       }
 488       line_no++;
 489     }
 490     return NULL;
 491   }
 492 
 493   // compile <klass> <name> <signature> <entry_bci> <comp_level> inline <count> <depth> <bci> <klass> <name> <signature> ...
 494   void process_compile(TRAPS) {
 495     Method* method = parse_method(CHECK);
 496     if (had_error()) return;
 497     int entry_bci = parse_int("entry_bci");
 498     const char* comp_level_label = "comp_level";
 499     int comp_level = parse_int(comp_level_label);
 500     // old version w/o comp_level
 501     if (had_error() && (error_message() == comp_level_label)) {
 502       // use highest available tier
 503       comp_level = TieredCompilation ? TieredStopAtLevel : CompLevel_highest_tier;
 504     }
 505     if (!is_valid_comp_level(comp_level)) {
 506       return;
 507     }
 508     if (_imethod != NULL) {
 509       // Replay Inlining
 510       if (entry_bci != _entry_bci || comp_level != _comp_level) {
 511         return;
 512       }
 513       const char* iklass_name  = _imethod->method_holder()->name()->as_utf8();
 514       const char* imethod_name = _imethod->name()->as_utf8();
 515       const char* isignature   = _imethod->signature()->as_utf8();
 516       const char* klass_name   = method->method_holder()->name()->as_utf8();
 517       const char* method_name  = method->name()->as_utf8();
 518       const char* signature    = method->signature()->as_utf8();
 519       if (strcmp(iklass_name,  klass_name)  != 0 ||
 520           strcmp(imethod_name, method_name) != 0 ||
 521           strcmp(isignature,   signature)   != 0) {
 522         return;
 523       }
 524     }
 525     int inline_count = 0;
 526     if (parse_tag_and_count("inline", inline_count)) {
 527       // Record inlining data
 528       _ci_inline_records = new GrowableArray<ciInlineRecord*>();
 529       for (int i = 0; i < inline_count; i++) {
 530         int depth = parse_int("inline_depth");
 531         int bci = parse_int("inline_bci");
 532         if (had_error()) {
 533           break;
 534         }
 535         Method* inl_method = parse_method(CHECK);
 536         if (had_error()) {
 537           break;
 538         }
 539         new_ciInlineRecord(inl_method, bci, depth);
 540       }
 541     }
 542     if (_imethod != NULL) {
 543       return; // Replay Inlining
 544     }
 545     InstanceKlass* ik = method->method_holder();
 546     ik->initialize(THREAD);
 547     if (HAS_PENDING_EXCEPTION) {
 548       oop throwable = PENDING_EXCEPTION;
 549       java_lang_Throwable::print(throwable, tty);
 550       tty->cr();
 551       if (ReplayIgnoreInitErrors) {
 552         CLEAR_PENDING_EXCEPTION;
 553         ik->set_init_state(InstanceKlass::fully_initialized);
 554       } else {
 555         return;
 556       }
 557     }
 558     // Make sure the existence of a prior compile doesn't stop this one
 559     CompiledMethod* nm = (entry_bci != InvocationEntryBci) ? method->lookup_osr_nmethod_for(entry_bci, comp_level, true) : method->code();
 560     if (nm != NULL) {
 561       nm->make_not_entrant();
 562     }
 563     replay_state = this;
 564     CompileBroker::compile_method(method, entry_bci, comp_level,
 565                                   methodHandle(), 0, CompileTask::Reason_Replay, THREAD);
 566     replay_state = NULL;
 567     reset();
 568   }
 569 
 570   // ciMethod <klass> <name> <signature> <invocation_counter> <backedge_counter> <interpreter_invocation_count> <interpreter_throwout_count> <instructions_size>
 571   //
 572   //
 573   void process_ciMethod(TRAPS) {
 574     Method* method = parse_method(CHECK);
 575     if (had_error()) return;
 576     ciMethodRecord* rec = new_ciMethod(method);
 577     rec->_invocation_counter = parse_int("invocation_counter");
 578     rec->_backedge_counter = parse_int("backedge_counter");
 579     rec->_interpreter_invocation_count = parse_int("interpreter_invocation_count");
 580     rec->_interpreter_throwout_count = parse_int("interpreter_throwout_count");
 581     rec->_instructions_size = parse_int("instructions_size");
 582   }
 583 
 584   // ciMethodData <klass> <name> <signature> <state> <current mileage> orig <length> # # ... data <length> # # ... oops <length> # ... methods <length>
 585   void process_ciMethodData(TRAPS) {
 586     Method* method = parse_method(CHECK);
 587     if (had_error()) return;
 588     /* just copied from Method, to build interpret data*/
 589 
 590     // To be properly initialized, some profiling in the MDO needs the
 591     // method to be rewritten (number of arguments at a call for
 592     // instance)
 593     method->method_holder()->link_class(CHECK);
 594     // methodOopDesc::build_interpreter_method_data(method, CHECK);
 595     {
 596       // Grab a lock here to prevent multiple
 597       // MethodData*s from being created.
 598       MutexLocker ml(MethodData_lock, THREAD);
 599       if (method->method_data() == NULL) {
 600         ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 601         MethodData* method_data = MethodData::allocate(loader_data, method, CHECK);
 602         method->set_method_data(method_data);
 603       }
 604     }
 605 
 606     // collect and record all the needed information for later
 607     ciMethodDataRecord* rec = new_ciMethodData(method);
 608     rec->_state = parse_int("state");
 609     rec->_current_mileage = parse_int("current_mileage");
 610 
 611     rec->_orig_data = parse_data("orig", rec->_orig_data_length);
 612     if (rec->_orig_data == NULL) {
 613       return;
 614     }
 615     rec->_data = parse_intptr_data("data", rec->_data_length);
 616     if (rec->_data == NULL) {
 617       return;
 618     }
 619     if (!parse_tag_and_count("oops", rec->_classes_length)) {
 620       return;
 621     }
 622     rec->_classes = NEW_RESOURCE_ARRAY(Klass*, rec->_classes_length);
 623     rec->_classes_offsets = NEW_RESOURCE_ARRAY(int, rec->_classes_length);
 624     for (int i = 0; i < rec->_classes_length; i++) {
 625       int offset = parse_int("offset");
 626       if (had_error()) {
 627         return;
 628       }
 629       Klass* k = parse_klass(CHECK);
 630       rec->_classes_offsets[i] = offset;
 631       rec->_classes[i] = k;
 632     }
 633 
 634     if (!parse_tag_and_count("methods", rec->_methods_length)) {
 635       return;
 636     }
 637     rec->_methods = NEW_RESOURCE_ARRAY(Method*, rec->_methods_length);
 638     rec->_methods_offsets = NEW_RESOURCE_ARRAY(int, rec->_methods_length);
 639     for (int i = 0; i < rec->_methods_length; i++) {
 640       int offset = parse_int("offset");
 641       if (had_error()) {
 642         return;
 643       }
 644       Method* m = parse_method(CHECK);
 645       rec->_methods_offsets[i] = offset;
 646       rec->_methods[i] = m;
 647     }
 648   }
 649 
 650   // instanceKlass <name>
 651   //
 652   // Loads and initializes the klass 'name'.  This can be used to
 653   // create particular class loading environments
 654   void process_instanceKlass(TRAPS) {
 655     // just load the referenced class
 656     Klass* k = parse_klass(CHECK);
 657   }
 658 
 659   // ciInstanceKlass <name> <is_linked> <is_initialized> <length> tag # # # ...
 660   //
 661   // Load the klass 'name' and link or initialize it.  Verify that the
 662   // constant pool is the same length as 'length' and make sure the
 663   // constant pool tags are in the same state.
 664   void process_ciInstanceKlass(TRAPS) {
 665     InstanceKlass* k = (InstanceKlass *)parse_klass(CHECK);
 666     if (k == NULL) {
 667       return;
 668     }
 669     int is_linked = parse_int("is_linked");
 670     int is_initialized = parse_int("is_initialized");
 671     int length = parse_int("length");
 672     if (is_initialized) {
 673       k->initialize(THREAD);
 674       if (HAS_PENDING_EXCEPTION) {
 675         oop throwable = PENDING_EXCEPTION;
 676         java_lang_Throwable::print(throwable, tty);
 677         tty->cr();
 678         if (ReplayIgnoreInitErrors) {
 679           CLEAR_PENDING_EXCEPTION;
 680           k->set_init_state(InstanceKlass::fully_initialized);
 681         } else {
 682           return;
 683         }
 684       }
 685     } else if (is_linked) {
 686       k->link_class(CHECK);
 687     }
 688     ConstantPool* cp = k->constants();
 689     if (length != cp->length()) {
 690       report_error("constant pool length mismatch: wrong class files?");
 691       return;
 692     }
 693 
 694     int parsed_two_word = 0;
 695     for (int i = 1; i < length; i++) {
 696       int tag = parse_int("tag");
 697       if (had_error()) {
 698         return;
 699       }
 700       switch (cp->tag_at(i).value()) {
 701         case JVM_CONSTANT_UnresolvedClass: {
 702           if (tag == JVM_CONSTANT_Class) {
 703             tty->print_cr("Resolving klass %s at %d", cp->klass_name_at(i)->as_utf8(), i);
 704             Klass* k = cp->klass_at(i, CHECK);
 705           }
 706           break;
 707         }
 708         case JVM_CONSTANT_Long:
 709         case JVM_CONSTANT_Double:
 710           parsed_two_word = i + 1;
 711 
 712         case JVM_CONSTANT_ClassIndex:
 713         case JVM_CONSTANT_StringIndex:
 714         case JVM_CONSTANT_String:
 715         case JVM_CONSTANT_UnresolvedClassInError:
 716         case JVM_CONSTANT_Fieldref:
 717         case JVM_CONSTANT_Methodref:
 718         case JVM_CONSTANT_InterfaceMethodref:
 719         case JVM_CONSTANT_NameAndType:
 720         case JVM_CONSTANT_Utf8:
 721         case JVM_CONSTANT_Integer:
 722         case JVM_CONSTANT_Float:
 723         case JVM_CONSTANT_MethodHandle:
 724         case JVM_CONSTANT_MethodType:
 725         case JVM_CONSTANT_Dynamic:
 726         case JVM_CONSTANT_InvokeDynamic:
 727           if (tag != cp->tag_at(i).value()) {
 728             report_error("tag mismatch: wrong class files?");
 729             return;
 730           }
 731           break;
 732 
 733         case JVM_CONSTANT_Class:
 734           if (tag == JVM_CONSTANT_Class) {
 735           } else if (tag == JVM_CONSTANT_UnresolvedClass) {
 736             tty->print_cr("Warning: entry was unresolved in the replay data");
 737           } else {
 738             report_error("Unexpected tag");
 739             return;
 740           }
 741           break;
 742 
 743         case 0:
 744           if (parsed_two_word == i) continue;
 745 
 746         default:
 747           fatal("Unexpected tag: %d", cp->tag_at(i).value());
 748           break;
 749       }
 750 
 751     }
 752   }
 753 
 754   // Initialize a class and fill in the value for a static field.
 755   // This is useful when the compile was dependent on the value of
 756   // static fields but it's impossible to properly rerun the static
 757   // initiailizer.
 758   void process_staticfield(TRAPS) {
 759     InstanceKlass* k = (InstanceKlass *)parse_klass(CHECK);
 760 
 761     if (k == NULL || ReplaySuppressInitializers == 0 ||
 762         (ReplaySuppressInitializers == 2 && k->class_loader() == NULL)) {
 763       return;
 764     }
 765 
 766     assert(k->is_initialized(), "must be");
 767 
 768     const char* field_name = parse_escaped_string();
 769     const char* field_signature = parse_string();
 770     fieldDescriptor fd;
 771     Symbol* name = SymbolTable::lookup(field_name, (int)strlen(field_name), CHECK);
 772     Symbol* sig = SymbolTable::lookup(field_signature, (int)strlen(field_signature), CHECK);
 773     if (!k->find_local_field(name, sig, &fd) ||
 774         !fd.is_static() ||
 775         fd.has_initial_value()) {
 776       report_error(field_name);
 777       return;
 778     }
 779 
 780     oop java_mirror = k->java_mirror();
 781     if (field_signature[0] == '[') {
 782       int length = parse_int("array length");
 783       oop value = NULL;
 784 
 785       if (field_signature[1] == '[') {
 786         // multi dimensional array
 787         ArrayKlass* kelem = (ArrayKlass *)parse_klass(CHECK);
 788         if (kelem == NULL) {
 789           return;
 790         }
 791         int rank = 0;
 792         while (field_signature[rank] == '[') {
 793           rank++;
 794         }
 795         jint* dims = NEW_RESOURCE_ARRAY(jint, rank);
 796         dims[0] = length;
 797         for (int i = 1; i < rank; i++) {
 798           dims[i] = 1; // These aren't relevant to the compiler
 799         }
 800         value = kelem->multi_allocate(rank, dims, CHECK);
 801       } else {
 802         if (strcmp(field_signature, "[B") == 0) {
 803           value = oopFactory::new_byteArray(length, CHECK);
 804         } else if (strcmp(field_signature, "[Z") == 0) {
 805           value = oopFactory::new_boolArray(length, CHECK);
 806         } else if (strcmp(field_signature, "[C") == 0) {
 807           value = oopFactory::new_charArray(length, CHECK);
 808         } else if (strcmp(field_signature, "[S") == 0) {
 809           value = oopFactory::new_shortArray(length, CHECK);
 810         } else if (strcmp(field_signature, "[F") == 0) {
 811           value = oopFactory::new_singleArray(length, CHECK);
 812         } else if (strcmp(field_signature, "[D") == 0) {
 813           value = oopFactory::new_doubleArray(length, CHECK);
 814         } else if (strcmp(field_signature, "[I") == 0) {
 815           value = oopFactory::new_intArray(length, CHECK);
 816         } else if (strcmp(field_signature, "[J") == 0) {
 817           value = oopFactory::new_longArray(length, CHECK);
 818         } else if (field_signature[0] == '[' && field_signature[1] == 'L') {
 819           Klass* kelem = resolve_klass(field_signature + 1, CHECK);
 820           value = oopFactory::new_objArray(kelem, length, CHECK);
 821         } else {
 822           report_error("unhandled array staticfield");
 823         }
 824       }
 825       java_mirror->obj_field_put(fd.offset(), value);
 826     } else {
 827       const char* string_value = parse_escaped_string();
 828       if (strcmp(field_signature, "I") == 0) {
 829         int value = atoi(string_value);
 830         java_mirror->int_field_put(fd.offset(), value);
 831       } else if (strcmp(field_signature, "B") == 0) {
 832         int value = atoi(string_value);
 833         java_mirror->byte_field_put(fd.offset(), value);
 834       } else if (strcmp(field_signature, "C") == 0) {
 835         int value = atoi(string_value);
 836         java_mirror->char_field_put(fd.offset(), value);
 837       } else if (strcmp(field_signature, "S") == 0) {
 838         int value = atoi(string_value);
 839         java_mirror->short_field_put(fd.offset(), value);
 840       } else if (strcmp(field_signature, "Z") == 0) {
 841         int value = atoi(string_value);
 842         java_mirror->bool_field_put(fd.offset(), value);
 843       } else if (strcmp(field_signature, "J") == 0) {
 844         jlong value;
 845         if (sscanf(string_value, JLONG_FORMAT, &value) != 1) {
 846           fprintf(stderr, "Error parsing long: %s\n", string_value);
 847           return;
 848         }
 849         java_mirror->long_field_put(fd.offset(), value);
 850       } else if (strcmp(field_signature, "F") == 0) {
 851         float value = atof(string_value);
 852         java_mirror->float_field_put(fd.offset(), value);
 853       } else if (strcmp(field_signature, "D") == 0) {
 854         double value = atof(string_value);
 855         java_mirror->double_field_put(fd.offset(), value);
 856       } else if (strcmp(field_signature, "Ljava/lang/String;") == 0) {
 857         Handle value = java_lang_String::create_from_str(string_value, CHECK);
 858         java_mirror->obj_field_put(fd.offset(), value());
 859       } else if (field_signature[0] == 'L') {
 860         Klass* k = resolve_klass(string_value, CHECK);
 861         oop value = InstanceKlass::cast(k)->allocate_instance(CHECK);
 862         java_mirror->obj_field_put(fd.offset(), value);
 863       } else {
 864         report_error("unhandled staticfield");
 865       }
 866     }
 867   }
 868 
 869 #if INCLUDE_JVMTI
 870   void process_JvmtiExport(TRAPS) {
 871     const char* field = parse_string();
 872     bool value = parse_int("JvmtiExport flag") != 0;
 873     if (strcmp(field, "can_access_local_variables") == 0) {
 874       JvmtiExport::set_can_access_local_variables(value);
 875     } else if (strcmp(field, "can_hotswap_or_post_breakpoint") == 0) {
 876       JvmtiExport::set_can_hotswap_or_post_breakpoint(value);
 877     } else if (strcmp(field, "can_post_on_exceptions") == 0) {
 878       JvmtiExport::set_can_post_on_exceptions(value);
 879     } else {
 880       report_error("Unrecognized JvmtiExport directive");
 881     }
 882   }
 883 #endif // INCLUDE_JVMTI
 884 
 885   // Create and initialize a record for a ciMethod
 886   ciMethodRecord* new_ciMethod(Method* method) {
 887     ciMethodRecord* rec = NEW_RESOURCE_OBJ(ciMethodRecord);
 888     rec->_klass_name =  method->method_holder()->name()->as_utf8();
 889     rec->_method_name = method->name()->as_utf8();
 890     rec->_signature = method->signature()->as_utf8();
 891     _ci_method_records.append(rec);
 892     return rec;
 893   }
 894 
 895   // Lookup data for a ciMethod
 896   ciMethodRecord* find_ciMethodRecord(Method* method) {
 897     const char* klass_name =  method->method_holder()->name()->as_utf8();
 898     const char* method_name = method->name()->as_utf8();
 899     const char* signature = method->signature()->as_utf8();
 900     for (int i = 0; i < _ci_method_records.length(); i++) {
 901       ciMethodRecord* rec = _ci_method_records.at(i);
 902       if (strcmp(rec->_klass_name, klass_name) == 0 &&
 903           strcmp(rec->_method_name, method_name) == 0 &&
 904           strcmp(rec->_signature, signature) == 0) {
 905         return rec;
 906       }
 907     }
 908     return NULL;
 909   }
 910 
 911   // Create and initialize a record for a ciMethodData
 912   ciMethodDataRecord* new_ciMethodData(Method* method) {
 913     ciMethodDataRecord* rec = NEW_RESOURCE_OBJ(ciMethodDataRecord);
 914     rec->_klass_name =  method->method_holder()->name()->as_utf8();
 915     rec->_method_name = method->name()->as_utf8();
 916     rec->_signature = method->signature()->as_utf8();
 917     _ci_method_data_records.append(rec);
 918     return rec;
 919   }
 920 
 921   // Lookup data for a ciMethodData
 922   ciMethodDataRecord* find_ciMethodDataRecord(Method* method) {
 923     const char* klass_name =  method->method_holder()->name()->as_utf8();
 924     const char* method_name = method->name()->as_utf8();
 925     const char* signature = method->signature()->as_utf8();
 926     for (int i = 0; i < _ci_method_data_records.length(); i++) {
 927       ciMethodDataRecord* rec = _ci_method_data_records.at(i);
 928       if (strcmp(rec->_klass_name, klass_name) == 0 &&
 929           strcmp(rec->_method_name, method_name) == 0 &&
 930           strcmp(rec->_signature, signature) == 0) {
 931         return rec;
 932       }
 933     }
 934     return NULL;
 935   }
 936 
 937   // Create and initialize a record for a ciInlineRecord
 938   ciInlineRecord* new_ciInlineRecord(Method* method, int bci, int depth) {
 939     ciInlineRecord* rec = NEW_RESOURCE_OBJ(ciInlineRecord);
 940     rec->_klass_name =  method->method_holder()->name()->as_utf8();
 941     rec->_method_name = method->name()->as_utf8();
 942     rec->_signature = method->signature()->as_utf8();
 943     rec->_inline_bci = bci;
 944     rec->_inline_depth = depth;
 945     _ci_inline_records->append(rec);
 946     return rec;
 947   }
 948 
 949   // Lookup inlining data for a ciMethod
 950   ciInlineRecord* find_ciInlineRecord(Method* method, int bci, int depth) {
 951     if (_ci_inline_records != NULL) {
 952       return find_ciInlineRecord(_ci_inline_records, method, bci, depth);
 953     }
 954     return NULL;
 955   }
 956 
 957   static ciInlineRecord* find_ciInlineRecord(GrowableArray<ciInlineRecord*>*  records,
 958                                       Method* method, int bci, int depth) {
 959     if (records != NULL) {
 960       const char* klass_name  = method->method_holder()->name()->as_utf8();
 961       const char* method_name = method->name()->as_utf8();
 962       const char* signature   = method->signature()->as_utf8();
 963       for (int i = 0; i < records->length(); i++) {
 964         ciInlineRecord* rec = records->at(i);
 965         if ((rec->_inline_bci == bci) &&
 966             (rec->_inline_depth == depth) &&
 967             (strcmp(rec->_klass_name, klass_name) == 0) &&
 968             (strcmp(rec->_method_name, method_name) == 0) &&
 969             (strcmp(rec->_signature, signature) == 0)) {
 970           return rec;
 971         }
 972       }
 973     }
 974     return NULL;
 975   }
 976 
 977   const char* error_message() {
 978     return _error_message;
 979   }
 980 
 981   void reset() {
 982     _error_message = NULL;
 983     _ci_method_records.clear();
 984     _ci_method_data_records.clear();
 985   }
 986 
 987   // Take an ascii string contain \u#### escapes and convert it to utf8
 988   // in place.
 989   static void unescape_string(char* value) {
 990     char* from = value;
 991     char* to = value;
 992     while (*from != '\0') {
 993       if (*from != '\\') {
 994         *from++ = *to++;
 995       } else {
 996         switch (from[1]) {
 997           case 'u': {
 998             from += 2;
 999             jchar value=0;
1000             for (int i=0; i<4; i++) {
1001               char c = *from++;
1002               switch (c) {
1003                 case '0': case '1': case '2': case '3': case '4':
1004                 case '5': case '6': case '7': case '8': case '9':
1005                   value = (value << 4) + c - '0';
1006                   break;
1007                 case 'a': case 'b': case 'c':
1008                 case 'd': case 'e': case 'f':
1009                   value = (value << 4) + 10 + c - 'a';
1010                   break;
1011                 case 'A': case 'B': case 'C':
1012                 case 'D': case 'E': case 'F':
1013                   value = (value << 4) + 10 + c - 'A';
1014                   break;
1015                 default:
1016                   ShouldNotReachHere();
1017               }
1018             }
1019             UNICODE::convert_to_utf8(&value, 1, to);
1020             to++;
1021             break;
1022           }
1023           case 't': *to++ = '\t'; from += 2; break;
1024           case 'n': *to++ = '\n'; from += 2; break;
1025           case 'r': *to++ = '\r'; from += 2; break;
1026           case 'f': *to++ = '\f'; from += 2; break;
1027           default:
1028             ShouldNotReachHere();
1029         }
1030       }
1031     }
1032     *from = *to;
1033   }
1034 };
1035 
1036 void ciReplay::replay(TRAPS) {
1037   int exit_code = replay_impl(THREAD);
1038 
1039   Threads::destroy_vm();
1040 
1041   vm_exit(exit_code);
1042 }
1043 
1044 void* ciReplay::load_inline_data(ciMethod* method, int entry_bci, int comp_level) {
1045   if (FLAG_IS_DEFAULT(InlineDataFile)) {
1046     tty->print_cr("ERROR: no inline replay data file specified (use -XX:InlineDataFile=inline_pid12345.txt).");
1047     return NULL;
1048   }
1049 
1050   VM_ENTRY_MARK;
1051   // Load and parse the replay data
1052   CompileReplay rp(InlineDataFile, THREAD);
1053   if (!rp.can_replay()) {
1054     tty->print_cr("ciReplay: !rp.can_replay()");
1055     return NULL;
1056   }
1057   void* data = rp.process_inline(method, method->get_Method(), entry_bci, comp_level, THREAD);
1058   if (HAS_PENDING_EXCEPTION) {
1059     Handle throwable(THREAD, PENDING_EXCEPTION);
1060     CLEAR_PENDING_EXCEPTION;
1061     java_lang_Throwable::print_stack_trace(throwable, tty);
1062     tty->cr();
1063     return NULL;
1064   }
1065 
1066   if (rp.had_error()) {
1067     tty->print_cr("ciReplay: Failed on %s", rp.error_message());
1068     return NULL;
1069   }
1070   return data;
1071 }
1072 
1073 int ciReplay::replay_impl(TRAPS) {
1074   HandleMark hm;
1075   ResourceMark rm;
1076 
1077   if (ReplaySuppressInitializers > 2) {
1078     // ReplaySuppressInitializers > 2 means that we want to allow
1079     // normal VM bootstrap but once we get into the replay itself
1080     // don't allow any intializers to be run.
1081     ReplaySuppressInitializers = 1;
1082   }
1083 
1084   if (FLAG_IS_DEFAULT(ReplayDataFile)) {
1085     tty->print_cr("ERROR: no compiler replay data file specified (use -XX:ReplayDataFile=replay_pid12345.txt).");
1086     return 1;
1087   }
1088 
1089   // Load and parse the replay data
1090   CompileReplay rp(ReplayDataFile, THREAD);
1091   int exit_code = 0;
1092   if (rp.can_replay()) {
1093     rp.process(THREAD);
1094   } else {
1095     exit_code = 1;
1096     return exit_code;
1097   }
1098 
1099   if (HAS_PENDING_EXCEPTION) {
1100     Handle throwable(THREAD, PENDING_EXCEPTION);
1101     CLEAR_PENDING_EXCEPTION;
1102     java_lang_Throwable::print_stack_trace(throwable, tty);
1103     tty->cr();
1104     exit_code = 2;
1105   }
1106 
1107   if (rp.had_error()) {
1108     tty->print_cr("Failed on %s", rp.error_message());
1109     exit_code = 1;
1110   }
1111   return exit_code;
1112 }
1113 
1114 void ciReplay::initialize(ciMethodData* m) {
1115   if (replay_state == NULL) {
1116     return;
1117   }
1118 
1119   ASSERT_IN_VM;
1120   ResourceMark rm;
1121 
1122   Method* method = m->get_MethodData()->method();
1123   ciMethodDataRecord* rec = replay_state->find_ciMethodDataRecord(method);
1124   if (rec == NULL) {
1125     // This indicates some mismatch with the original environment and
1126     // the replay environment though it's not always enough to
1127     // interfere with reproducing a bug
1128     tty->print_cr("Warning: requesting ciMethodData record for method with no data: ");
1129     method->print_name(tty);
1130     tty->cr();
1131   } else {
1132     m->_state = rec->_state;
1133     m->_current_mileage = rec->_current_mileage;
1134     if (rec->_data_length != 0) {
1135       assert(m->_data_size + m->_extra_data_size == rec->_data_length * (int)sizeof(rec->_data[0]) ||
1136              m->_data_size == rec->_data_length * (int)sizeof(rec->_data[0]), "must agree");
1137 
1138       // Write the correct ciObjects back into the profile data
1139       ciEnv* env = ciEnv::current();
1140       for (int i = 0; i < rec->_classes_length; i++) {
1141         Klass *k = rec->_classes[i];
1142         // In case this class pointer is is tagged, preserve the tag bits
1143         intptr_t status = 0;
1144         if (k != NULL) {
1145           status = ciTypeEntries::with_status(env->get_metadata(k)->as_klass(), rec->_data[rec->_classes_offsets[i]]);
1146         }
1147         rec->_data[rec->_classes_offsets[i]] = status;
1148       }
1149       for (int i = 0; i < rec->_methods_length; i++) {
1150         Method *m = rec->_methods[i];
1151         *(ciMetadata**)(rec->_data + rec->_methods_offsets[i]) =
1152           env->get_metadata(m);
1153       }
1154       // Copy the updated profile data into place as intptr_ts
1155 #ifdef _LP64
1156       Copy::conjoint_jlongs_atomic((jlong *)rec->_data, (jlong *)m->_data, rec->_data_length);
1157 #else
1158       Copy::conjoint_jints_atomic((jint *)rec->_data, (jint *)m->_data, rec->_data_length);
1159 #endif
1160     }
1161 
1162     // copy in the original header
1163     Copy::conjoint_jbytes(rec->_orig_data, (char*)&m->_orig, rec->_orig_data_length);
1164   }
1165 }
1166 
1167 
1168 bool ciReplay::should_not_inline(ciMethod* method) {
1169   if (replay_state == NULL) {
1170     return false;
1171   }
1172   VM_ENTRY_MARK;
1173   // ciMethod without a record shouldn't be inlined.
1174   return replay_state->find_ciMethodRecord(method->get_Method()) == NULL;
1175 }
1176 
1177 bool ciReplay::should_inline(void* data, ciMethod* method, int bci, int inline_depth) {
1178   if (data != NULL) {
1179     GrowableArray<ciInlineRecord*>*  records = (GrowableArray<ciInlineRecord*>*)data;
1180     VM_ENTRY_MARK;
1181     // Inline record are ordered by bci and depth.
1182     return CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth) != NULL;
1183   } else if (replay_state != NULL) {
1184     VM_ENTRY_MARK;
1185     // Inline record are ordered by bci and depth.
1186     return replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth) != NULL;
1187   }
1188   return false;
1189 }
1190 
1191 bool ciReplay::should_not_inline(void* data, ciMethod* method, int bci, int inline_depth) {
1192   if (data != NULL) {
1193     GrowableArray<ciInlineRecord*>*  records = (GrowableArray<ciInlineRecord*>*)data;
1194     VM_ENTRY_MARK;
1195     // Inline record are ordered by bci and depth.
1196     return CompileReplay::find_ciInlineRecord(records, method->get_Method(), bci, inline_depth) == NULL;
1197   } else if (replay_state != NULL) {
1198     VM_ENTRY_MARK;
1199     // Inline record are ordered by bci and depth.
1200     return replay_state->find_ciInlineRecord(method->get_Method(), bci, inline_depth) == NULL;
1201   }
1202   return false;
1203 }
1204 
1205 void ciReplay::initialize(ciMethod* m) {
1206   if (replay_state == NULL) {
1207     return;
1208   }
1209 
1210   ASSERT_IN_VM;
1211   ResourceMark rm;
1212 
1213   Method* method = m->get_Method();
1214   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1215   if (rec == NULL) {
1216     // This indicates some mismatch with the original environment and
1217     // the replay environment though it's not always enough to
1218     // interfere with reproducing a bug
1219     tty->print_cr("Warning: requesting ciMethod record for method with no data: ");
1220     method->print_name(tty);
1221     tty->cr();
1222   } else {
1223     EXCEPTION_CONTEXT;
1224     // m->_instructions_size = rec->_instructions_size;
1225     m->_instructions_size = -1;
1226     m->_interpreter_invocation_count = rec->_interpreter_invocation_count;
1227     m->_interpreter_throwout_count = rec->_interpreter_throwout_count;
1228     MethodCounters* mcs = method->get_method_counters(CHECK_AND_CLEAR);
1229     guarantee(mcs != NULL, "method counters allocation failed");
1230     mcs->invocation_counter()->_counter = rec->_invocation_counter;
1231     mcs->backedge_counter()->_counter = rec->_backedge_counter;
1232   }
1233 }
1234 
1235 bool ciReplay::is_loaded(Method* method) {
1236   if (replay_state == NULL) {
1237     return true;
1238   }
1239 
1240   ASSERT_IN_VM;
1241   ResourceMark rm;
1242 
1243   ciMethodRecord* rec = replay_state->find_ciMethodRecord(method);
1244   return rec != NULL;
1245 }
1246 #endif // PRODUCT