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