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