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