case Bytecodes::_lookupswitch: {
Bytecode_lookupswitch lookupswitch(str);
int npairs = lookupswitch.number_of_pairs();
_successors =
new (arena) GrowableArray<Block*>(arena, npairs+1, 0, NULL);
int bci = current_bci + lookupswitch.default_offset();
Block* block = analyzer->block_at(bci, jsrs);
assert(_successors->length() == SWITCH_DEFAULT, "");
_successors->append(block);
while(--npairs >= 0) {
LookupswitchPair pair = lookupswitch.pair_at(npairs);
int bci = current_bci + pair.offset();
Block* block = analyzer->block_at(bci, jsrs);
assert(_successors->length() >= SWITCH_CASES, "");
_successors->append_if_missing(block);
}
break;
}
case Bytecodes::_athrow: case Bytecodes::_ireturn:
case Bytecodes::_lreturn: case Bytecodes::_freturn:
case Bytecodes::_dreturn: case Bytecodes::_areturn:
case Bytecodes::_return:
_successors =
new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
break;
case Bytecodes::_ret: {
_successors =
new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
Cell local = state->local(str->get_index());
ciType* return_address = state->type_at(local);
assert(return_address->is_return_address(), "verify: wrong type");
int bci = return_address->as_return_address()->bci();
assert(_successors->length() == GOTO_TARGET, "");
_successors->append(analyzer->block_at(bci, jsrs));
break;
}
case Bytecodes::_wide:
default:
ShouldNotReachHere();
break;
}
}
}
return _successors;
}
void ciTypeFlow::Block::compute_exceptions() {
assert(_exceptions == NULL && _exc_klasses == NULL, "repeat");
if (CITraceTypeFlow) {
tty->print(">> Computing exceptions for block ");
print_value_on(tty);
tty->cr();
}
ciTypeFlow* analyzer = outer();
Arena* arena = analyzer->arena();
ciExceptionHandlerStream str(analyzer->method(), start());
int exc_count = str.count();
_exceptions = new (arena) GrowableArray<Block*>(arena, exc_count, 0, NULL);
_exc_klasses = new (arena) GrowableArray<ciInstanceKlass*>(arena, exc_count,
0, NULL);
for ( ; !str.is_done(); str.next()) {
ciExceptionHandler* handler = str.handler();
int bci = handler->handler_bci();
ciInstanceKlass* klass = NULL;
if (bci == -1) {
break;
}
if (handler->is_catch_all()) {
klass = analyzer->env()->Throwable_klass();
} else {
klass = handler->catch_klass();
}
_exceptions->append(analyzer->block_at(bci, _jsrs));
_exc_klasses->append(klass);
}
}
void ciTypeFlow::Block::set_backedge_copy(bool z) {
assert(z || (z == is_backedge_copy()), "cannot make a backedge copy public");
_backedge_copy = z;
}
bool ciTypeFlow::Block::is_clonable_exit(ciTypeFlow::Loop* lp) {
int normal_cnt = 0;
int in_loop_cnt = 0;
for (SuccIter iter(this); !iter.done(); iter.next()) {
Block* succ = iter.succ();
if (iter.is_normal_ctrl()) {
if (++normal_cnt > 2) return false;
if (lp->contains(succ->loop())) {
if (++in_loop_cnt > 1) return false;
}
} else {
if (lp->contains(succ->loop())) return false;
}
}
return in_loop_cnt == 1;
}
ciTypeFlow::Block* ciTypeFlow::Block::looping_succ(ciTypeFlow::Loop* lp) {
assert(successors()->length() <= 2, "at most 2 normal successors");
for (SuccIter iter(this); !iter.done(); iter.next()) {
Block* succ = iter.succ();
if (lp->contains(succ->loop())) {
return succ;
}
}
return NULL;
}
#ifndef PRODUCT
void ciTypeFlow::Block::print_value_on(outputStream* st) const {
if (has_pre_order()) st->print("#%-2d ", pre_order());
if (has_rpo()) st->print("rpo#%-2d ", rpo());
st->print("[%d - %d)", start(), limit());
if (is_loop_head()) st->print(" lphd");
if (is_irreducible_entry()) st->print(" irred");
if (_jsrs->size() > 0) { st->print("/"); _jsrs->print_on(st); }
if (is_backedge_copy()) st->print("/backedge_copy");
}
void ciTypeFlow::Block::print_on(outputStream* st) const {
if ((Verbose || WizardMode) && (limit() >= 0)) {
outer()->method()->print_codes_on(start(), limit(), st);
}
st->print_cr(" ==================================================== ");
st->print (" ");
print_value_on(st);
st->print(" Stored locals: "); def_locals()->print_on(st, outer()->method()->max_locals()); tty->cr();
if (loop() && loop()->parent() != NULL) {
st->print(" loops:");
Loop* lp = loop();
do {
st->print(" %d<-%d", lp->head()->pre_order(),lp->tail()->pre_order());
if (lp->is_irreducible()) st->print("(ir)");
lp = lp->parent();
} while (lp->parent() != NULL);
}
st->cr();
_state->print_on(st);
if (_successors == NULL) {
st->print_cr(" No successor information");
} else {
int num_successors = _successors->length();
st->print_cr(" Successors : %d", num_successors);
for (int i = 0; i < num_successors; i++) {
Block* successor = _successors->at(i);
st->print(" ");
successor->print_value_on(st);
st->cr();
}
}
if (_exceptions == NULL) {
st->print_cr(" No exception information");
} else {
int num_exceptions = _exceptions->length();
st->print_cr(" Exceptions : %d", num_exceptions);
for (int i = 0; i < num_exceptions; i++) {
Block* exc_succ = _exceptions->at(i);
ciInstanceKlass* exc_klass = _exc_klasses->at(i);
st->print(" ");
exc_succ->print_value_on(st);
st->print(" -- ");
exc_klass->name()->print_symbol_on(st);
st->cr();
}
}
if (has_trap()) {
st->print_cr(" Traps on %d with trap index %d", trap_bci(), trap_index());
}
st->print_cr(" ==================================================== ");
}
#endif
#ifndef PRODUCT
void ciTypeFlow::LocalSet::print_on(outputStream* st, int limit) const {
st->print("{");
for (int i = 0; i < max; i++) {
if (test(i)) st->print(" %d", i);
}
if (limit > max) {
st->print(" %d..%d ", max, limit);
}
st->print(" }");
}
#endif
ciTypeFlow::ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci) {
_env = env;
_method = method;
_methodBlocks = method->get_method_blocks();
_max_locals = method->max_locals();
_max_stack = method->max_stack();
_code_size = method->code_size();
_has_irreducible_entry = false;
_osr_bci = osr_bci;
_failure_reason = NULL;
assert(0 <= start_bci() && start_bci() < code_size() , err_msg("correct osr_bci argument: 0 <= %d < %d", start_bci(), code_size()));
_work_list = NULL;
_ciblock_count = _methodBlocks->num_blocks();
_idx_to_blocklist = NEW_ARENA_ARRAY(arena(), GrowableArray<Block*>*, _ciblock_count);
for (int i = 0; i < _ciblock_count; i++) {
_idx_to_blocklist[i] = NULL;
}
_block_map = NULL; // until all blocks are seen
_jsr_count = 0;
_jsr_records = NULL;
}
ciTypeFlow::Block* ciTypeFlow::work_list_next() {
assert(!work_list_empty(), "work list must not be empty");
Block* next_block = _work_list;
_work_list = next_block->next();
next_block->set_next(NULL);
next_block->set_on_work_list(false);
return next_block;
}
void ciTypeFlow::add_to_work_list(ciTypeFlow::Block* block) {
assert(!block->is_on_work_list(), "must not already be on work list");
if (CITraceTypeFlow) {
tty->print(">> Adding block ");
block->print_value_on(tty);
tty->print_cr(" to the work list : ");
}
block->set_on_work_list(true);
Block* prev = NULL;
Block* current = _work_list;
int po = block->post_order();
while (current != NULL) {
if (!current->has_post_order() || po > current->post_order())
break;
prev = current;
current = current->next();
}
if (prev == NULL) {
block->set_next(_work_list);
_work_list = block;
} else {
block->set_next(current);
prev->set_next(block);
}
if (CITraceTypeFlow) {
tty->cr();
}
}
ciTypeFlow::Block* ciTypeFlow::block_at(int bci, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
if (CITraceTypeFlow) {
tty->print(">> Requesting block for %d/", bci);
jsrs->print_on(tty);
tty->cr();
}
ciBlock* ciblk = _methodBlocks->block_containing(bci);
assert(ciblk->start_bci() == bci, "bad ciBlock boundaries");
Block* block = get_block_for(ciblk->index(), jsrs, option);
assert(block == NULL? (option == no_create): block->is_backedge_copy() == (option == create_backedge_copy), "create option consistent with result");
if (CITraceTypeFlow) {
if (block != NULL) {
tty->print(">> Found block ");
block->print_value_on(tty);
tty->cr();
} else {
tty->print_cr(">> No such block.");
}
}
return block;
}
ciTypeFlow::JsrRecord* ciTypeFlow::make_jsr_record(int entry_address,
int return_address) {
if (_jsr_records == NULL) {
_jsr_records = new (arena()) GrowableArray<JsrRecord*>(arena(),
_jsr_count,
0,
NULL);
}
JsrRecord* record = NULL;
int len = _jsr_records->length();
for (int i = 0; i < len; i++) {
JsrRecord* record = _jsr_records->at(i);
if (record->entry_address() == entry_address &&
record->return_address() == return_address) {
return record;
}
}
record = new (arena()) JsrRecord(entry_address, return_address);
_jsr_records->append(record);
return record;
}
void ciTypeFlow::flow_exceptions(GrowableArray<ciTypeFlow::Block*>* exceptions,
GrowableArray<ciInstanceKlass*>* exc_klasses,
ciTypeFlow::StateVector* state) {
int len = exceptions->length();
assert(exc_klasses->length() == len, "must have same length");
for (int i = 0; i < len; i++) {
Block* block = exceptions->at(i);
ciInstanceKlass* exception_klass = exc_klasses->at(i);
if (!exception_klass->is_loaded()) {
continue;
}
if (block->meet_exception(exception_klass, state)) {
if (block->has_post_order() &&
!block->is_on_work_list()) {
add_to_work_list(block);
}
}
}
}
void ciTypeFlow::flow_successors(GrowableArray<ciTypeFlow::Block*>* successors,
ciTypeFlow::StateVector* state) {
int len = successors->length();
for (int i = 0; i < len; i++) {
Block* block = successors->at(i);
if (block->meet(state)) {
if (block->has_post_order() &&
!block->is_on_work_list()) {
add_to_work_list(block);
}
}
}
}
bool ciTypeFlow::can_trap(ciBytecodeStream& str) {
if (!Bytecodes::can_trap(str.cur_bc())) return false;
switch (str.cur_bc()) {
case Bytecodes::_ldc:
case Bytecodes::_ldc_w:
case Bytecodes::_ldc2_w:
case Bytecodes::_aload_0:
return false;
case Bytecodes::_ireturn:
case Bytecodes::_lreturn:
case Bytecodes::_freturn:
case Bytecodes::_dreturn:
case Bytecodes::_areturn:
case Bytecodes::_return:
return false;
case Bytecodes::_monitorexit:
return false;
}
return true;
}
bool ciTypeFlow::clone_loop_heads(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
bool rslt = false;
for (PreorderLoops iter(loop_tree_root()); !iter.done(); iter.next()) {
lp = iter.current();
Block* head = lp->head();
if (lp == loop_tree_root() ||
lp->is_irreducible() ||
!head->is_clonable_exit(lp))
continue;
if (EliminateNestedLocks && head->has_monitorenter())
continue;
if (head->backedge_copy_count() != 0)
continue;
if (is_osr_flow() && head->start() == start_bci())
continue;
Loop* ch;
for (ch = lp->child(); ch != NULL && ch->head() != head; ch = ch->sibling());
if (ch != NULL)
continue;
Block* new_head = head->looping_succ(lp);
Block* clone = clone_loop_head(lp, temp_vector, temp_set);
clone->set_loop(lp);
lp->set_head(new_head);
lp->set_tail(clone);
head->set_loop(lp->parent());
rslt = true;
}
return rslt;
}
ciTypeFlow::Block* ciTypeFlow::clone_loop_head(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
Block* head = lp->head();
Block* tail = lp->tail();
if (CITraceTypeFlow) {
tty->print(">> Requesting clone of loop head "); head->print_value_on(tty);
tty->print(" for predecessor "); tail->print_value_on(tty);
tty->cr();
}
Block* clone = block_at(head->start(), head->jsrs(), create_backedge_copy);
assert(clone->backedge_copy_count() == 1, "one backedge copy for all back edges");
assert(!clone->has_pre_order(), "just created");
clone->set_next_pre_order();
clone->set_rpo_next(tail->rpo_next());
tail->set_rpo_next(clone);
for (SuccIter iter(tail); !iter.done(); iter.next()) {
if (iter.succ() == head) {
iter.set_succ(clone);
}
}
flow_block(tail, temp_vector, temp_set);
if (head == tail) {
flow_block(clone, temp_vector, temp_set);
for (SuccIter iter(clone); !iter.done(); iter.next()) {
if (iter.succ() == head) {
iter.set_succ(clone);
break;
}
}
}
flow_block(clone, temp_vector, temp_set);
return clone;
}
void ciTypeFlow::flow_block(ciTypeFlow::Block* block,
ciTypeFlow::StateVector* state,
ciTypeFlow::JsrSet* jsrs) {
if (CITraceTypeFlow) {
tty->print("\n>> ANALYZING BLOCK : ");
tty->cr();
block->print_on(tty);
}
assert(block->has_pre_order(), "pre-order is assigned before 1st flow");
int start = block->start();
int limit = block->limit();
int control = block->control();
if (control != ciBlock::fall_through_bci) {
limit = control;
}
block->copy_state_into(state);
state->def_locals()->clear();
GrowableArray<Block*>* exceptions = block->exceptions();
GrowableArray<ciInstanceKlass*>* exc_klasses = block->exc_klasses();
bool has_exceptions = exceptions->length() > 0;
bool exceptions_used = false;
ciBytecodeStream str(method());
str.reset_to_bci(start);
Bytecodes::Code code;
while ((code = str.next()) != ciBytecodeStream::EOBC() &&
str.cur_bci() < limit) {
if (has_exceptions && can_trap(str)) {
flow_exceptions(exceptions, exc_klasses, state);
exceptions_used = true;
}
bool res = state->apply_one_bytecode(&str);
if (failing()) return;
if (str.cur_bc() == Bytecodes::_monitorenter) {
block->set_has_monitorenter();
}
if (res) {
block->set_trap(state->trap_bci(), state->trap_index());
if (CITraceTypeFlow) {
tty->print_cr(">> Found trap");
block->print_on(tty);
}
block->def_locals()->add(state->def_locals());
block->successors(&str, state, jsrs);
assert(!has_exceptions || exceptions_used, "Not removing exceptions");
return;
}
}
GrowableArray<Block*>* successors = NULL;
if (control != ciBlock::fall_through_bci) {
if (has_exceptions && can_trap(str)) {
flow_exceptions(exceptions, exc_klasses, state);
exceptions_used = true;
}
block->copy_jsrs_into(jsrs);
jsrs->apply_control(this, &str, state);
successors = block->successors(&str, state, jsrs);
state->apply_one_bytecode(&str);
} else {
successors = block->successors(&str, NULL, NULL);
}
block->def_locals()->add(state->def_locals());
if (!exceptions_used)
exceptions->clear();
flow_successors(successors, state);
}
void ciTypeFlow::PostorderLoops::next() {
assert(!done(), "must not be done.");
if (_current->sibling() != NULL) {
_current = _current->sibling();
while (_current->child() != NULL) {
_current = _current->child();
}
} else {
_current = _current->parent();
}
}
void ciTypeFlow::PreorderLoops::next() {
assert(!done(), "must not be done.");
if (_current->child() != NULL) {
_current = _current->child();
} else if (_current->sibling() != NULL) {
_current = _current->sibling();
} else {
while (_current != _root && _current->sibling() == NULL) {
_current = _current->parent();
}
if (_current == _root) {
_current = NULL;
assert(done(), "must be done.");
} else {
assert(_current->sibling() != NULL, "must be more to do");
_current = _current->sibling();
}
}
}
ciTypeFlow::Loop* ciTypeFlow::Loop::sorted_merge(Loop* lp) {
Loop* leaf = this;
Loop* prev = NULL;
Loop* current = leaf;
while (lp != NULL) {
int lp_pre_order = lp->head()->pre_order();
while (current != NULL) {
if (current == lp)
return leaf; // Already in list
if (current->head()->pre_order() < lp_pre_order)
break;
if (current->head()->pre_order() == lp_pre_order &&
current->tail()->pre_order() > lp->tail()->pre_order()) {
break;
}
prev = current;
current = current->parent();
}
Loop* next_lp = lp->parent(); // Save future list of items to insert
lp->set_parent(current);
if (prev != NULL) {
prev->set_parent(lp);
} else {
leaf = lp;
}
prev = lp; // Inserted item is new prev[ious]
lp = next_lp; // Next item to insert
}
return leaf;
}
void ciTypeFlow::build_loop_tree(Block* blk) {
assert(!blk->is_post_visited(), "precondition");
Loop* innermost = NULL; // merge of loop tree branches over all successors
for (SuccIter iter(blk); !iter.done(); iter.next()) {
Loop* lp = NULL;
Block* succ = iter.succ();
if (!succ->is_post_visited()) {
assert(succ->pre_order() <= blk->pre_order(), "should be backedge");
lp = new (arena()) Loop(succ, blk);
if (succ->loop() == NULL)
succ->set_loop(lp);
} else { // Nested loop
lp = succ->loop();
while (lp != NULL && lp->head() == succ) {
lp = lp->parent();
}
if (lp == NULL) {
lp = loop_tree_root();
}
}
while (lp->head()->is_post_visited() && lp != loop_tree_root()) {
_has_irreducible_entry = true;
lp->set_irreducible(succ);
if (!succ->is_on_work_list()) {
add_to_work_list(succ);
}
Loop* plp = lp->parent();
if (plp == NULL) {
break;
}
lp = plp;
}
innermost = innermost == NULL ? lp : innermost->sorted_merge(lp);
} // end loop
if (innermost == NULL) {
assert(blk->successors()->length() == 0, "CFG exit");
blk->set_loop(loop_tree_root());
} else if (innermost->head() == blk) {
if (blk->loop() != innermost) {
#ifdef ASSERT
assert(blk->loop()->head() == innermost->head(), "same head");
Loop* dl;
for (dl = innermost; dl != NULL && dl != blk->loop(); dl = dl->parent());
assert(dl == blk->loop(), "blk->loop() already in innermost list");
#endif
blk->set_loop(innermost);
}
innermost->def_locals()->add(blk->def_locals());
Loop* l = innermost;
Loop* p = l->parent();
while (p && l->head() == blk) {
l->set_sibling(p->child()); // Put self on parents 'next child'
p->set_child(l); // Make self the first child of parent
p->def_locals()->add(l->def_locals());
l = p; // Walk up the parent chain
p = l->parent();
}
} else {
blk->set_loop(innermost);
innermost->def_locals()->add(blk->def_locals());
}
}
bool ciTypeFlow::Loop::contains(ciTypeFlow::Loop* lp) const {
assert(lp != NULL, "");
if (this == lp || head() == lp->head()) return true;
int depth1 = depth();
int depth2 = lp->depth();
if (depth1 > depth2)
return false;
while (depth1 < depth2) {
depth2--;
lp = lp->parent();
}
return this == lp;
}
int ciTypeFlow::Loop::depth() const {
int dp = 0;
for (Loop* lp = this->parent(); lp != NULL; lp = lp->parent())
dp++;
return dp;
}
#ifndef PRODUCT
void ciTypeFlow::Loop::print(outputStream* st, int indent) const {
for (int i = 0; i < indent; i++) st->print(" ");
st->print("%d<-%d %s",
is_root() ? 0 : this->head()->pre_order(),
is_root() ? 0 : this->tail()->pre_order(),
is_irreducible()?" irr":"");
st->print(" defs: ");
def_locals()->print_on(st, _head->outer()->method()->max_locals());
st->cr();
for (Loop* ch = child(); ch != NULL; ch = ch->sibling())
ch->print(st, indent+2);
}
#endif
void ciTypeFlow::df_flow_types(Block* start,
bool do_flow,
StateVector* temp_vector,
JsrSet* temp_set) {
int dft_len = 100;
GrowableArray<Block*> stk(dft_len);
ciBlock* dummy = _methodBlocks->make_dummy_block();
JsrSet* root_set = new JsrSet(NULL, 0);
Block* root_head = new (arena()) Block(this, dummy, root_set);
Block* root_tail = new (arena()) Block(this, dummy, root_set);
root_head->set_pre_order(0);
root_head->set_post_order(0);
root_tail->set_pre_order(max_jint);
root_tail->set_post_order(max_jint);
set_loop_tree_root(new (arena()) Loop(root_head, root_tail));
stk.push(start);
_next_pre_order = 0; // initialize pre_order counter
_rpo_list = NULL;
int next_po = 0; // initialize post_order counter
int size;
while ((size = stk.length()) > 0) {
Block* blk = stk.top(); // Leave node on stack
if (!blk->is_visited()) {
assert (!blk->has_pre_order(), "");
blk->set_next_pre_order();
if (_next_pre_order >= (int)Compile::current()->max_node_limit() / 2) {
record_failure("too many basic blocks");
return;
}
if (do_flow) {
flow_block(blk, temp_vector, temp_set);
if (failing()) return; // Watch for bailouts.
}
} else if (!blk->is_post_visited()) {
for (SuccIter iter(blk); !iter.done(); iter.next()) {
Block* succ = iter.succ();
if (!succ->is_visited()) {
stk.push(succ);
}
}
if (stk.length() == size) {
stk.pop(); // Remove node from stack
build_loop_tree(blk);
blk->set_post_order(next_po++); // Assign post order
prepend_to_rpo_list(blk);
assert(blk->is_post_visited(), "");
if (blk->is_loop_head() && !blk->is_on_work_list()) {
add_to_work_list(blk);
}
}
} else {
stk.pop(); // Remove post-visited node from stack
}
}
}
void ciTypeFlow::flow_types() {
ResourceMark rm;
StateVector* temp_vector = new StateVector(this);
JsrSet* temp_set = new JsrSet(NULL, 16);
Block* start = block_at(start_bci(), temp_set);
const StateVector* start_state = get_start_state();
if (failing()) return;
start->meet(start_state);
df_flow_types(start, true /*do flow*/, temp_vector, temp_set);
if (failing()) return;
assert(_rpo_list == start, "must be start");
if (loop_tree_root()->child() != NULL &&
env()->comp_level() >= CompLevel_full_optimization) {
bool changed = clone_loop_heads(loop_tree_root(), temp_vector, temp_set);
if (changed) {
loop_tree_root()->set_child(NULL);
for (Block* blk = _rpo_list; blk != NULL;) {
Block* next = blk->rpo_next();
blk->df_init();
blk = next;
}
df_flow_types(start, false /*no flow*/, temp_vector, temp_set);
}
}
if (CITraceTypeFlow) {
tty->print_cr("\nLoop tree");
loop_tree_root()->print();
}
debug_only(int max_block = _next_pre_order;)
while (!work_list_empty()) {
Block* blk = work_list_next();
assert (blk->has_post_order(), "post order assigned above");
flow_block(blk, temp_vector, temp_set);
assert (max_block == _next_pre_order, "no new blocks");
assert (!failing(), "no more bailouts");
}
}
void ciTypeFlow::map_blocks() {
assert(_block_map == NULL, "single initialization");
int block_ct = _next_pre_order;
_block_map = NEW_ARENA_ARRAY(arena(), Block*, block_ct);
assert(block_ct == block_count(), "");
Block* blk = _rpo_list;
for (int m = 0; m < block_ct; m++) {
int rpo = blk->rpo();
assert(rpo == m, "should be sequential");
_block_map[rpo] = blk;
blk = blk->rpo_next();
}
assert(blk == NULL, "should be done");
for (int j = 0; j < block_ct; j++) {
assert(_block_map[j] != NULL, "must not drop any blocks");
Block* block = _block_map[j];
for (int e = 0; e <= 1; e++) {
GrowableArray<Block*>* l = e? block->exceptions(): block->successors();
for (int k = 0; k < l->length(); k++) {
Block* s = l->at(k);
if (!s->has_post_order()) {
if (CITraceTypeFlow) {
tty->print("Removing dead %s successor of #%d: ", (e? "exceptional": "normal"), block->pre_order());
s->print_value_on(tty);
tty->cr();
}
l->remove(s);
--k;
}
}
}
}
}
ciTypeFlow::Block* ciTypeFlow::get_block_for(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
Arena* a = arena();
GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
if (blocks == NULL) {
if (option == no_create) return NULL;
blocks = new (a) GrowableArray<Block*>(a, 4, 0, NULL);
_idx_to_blocklist[ciBlockIndex] = blocks;
}
if (option != create_backedge_copy) {
int len = blocks->length();
for (int i = 0; i < len; i++) {
Block* block = blocks->at(i);
if (!block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
return block;
}
}
}
if (option == no_create) return NULL;
Block* new_block = new (a) Block(this, _methodBlocks->block(ciBlockIndex), jsrs);
if (option == create_backedge_copy) new_block->set_backedge_copy(true);
blocks->append(new_block);
return new_block;
}
int ciTypeFlow::backedge_copy_count(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs) const {
GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
if (blocks == NULL) {
return 0;
}
int count = 0;
int len = blocks->length();
for (int i = 0; i < len; i++) {
Block* block = blocks->at(i);
if (block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
count++;
}
}
return count;
}
void ciTypeFlow::do_flow() {
if (CITraceTypeFlow) {
tty->print_cr("\nPerforming flow analysis on method");
method()->print();
if (is_osr_flow()) tty->print(" at OSR bci %d", start_bci());
tty->cr();
method()->print_codes();
}
if (CITraceTypeFlow) {
tty->print_cr("Initial CI Blocks");
print_on(tty);
}
flow_types();
if (failing()) {
return;
}
map_blocks();
if (CIPrintTypeFlow || CITraceTypeFlow) {
rpo_print_on(tty);
}
}
void ciTypeFlow::record_failure(const char* reason) {
if (env()->log() != NULL) {
env()->log()->elem("failure reason='%s' phase='typeflow'", reason);
}
if (_failure_reason == NULL) {
_failure_reason = reason;
}
}
#ifndef PRODUCT
void ciTypeFlow::print_on(outputStream* st) const {
st->print_cr("********************************************************");
st->print ("TypeFlow for ");
method()->name()->print_symbol_on(st);
int limit_bci = code_size();
st->print_cr(" %d bytes", limit_bci);
ciMethodBlocks *mblks = _methodBlocks;
ciBlock* current = NULL;
for (int bci = 0; bci < limit_bci; bci++) {
ciBlock* blk = mblks->block_containing(bci);
if (blk != NULL && blk != current) {
current = blk;
current->print_on(st);
GrowableArray<Block*>* blocks = _idx_to_blocklist[blk->index()];
int num_blocks = (blocks == NULL) ? 0 : blocks->length();
if (num_blocks == 0) {
st->print_cr(" No Blocks");
} else {
for (int i = 0; i < num_blocks; i++) {
Block* block = blocks->at(i);
block->print_on(st);
}
}
st->print_cr("--------------------------------------------------------");
st->cr();
}
}
st->print_cr("********************************************************");
st->cr();
}
void ciTypeFlow::rpo_print_on(outputStream* st) const {
st->print_cr("********************************************************");
st->print ("TypeFlow for ");
method()->name()->print_symbol_on(st);
int limit_bci = code_size();
st->print_cr(" %d bytes", limit_bci);
for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
blk->print_on(st);
st->print_cr("--------------------------------------------------------");
st->cr();
}
st->print_cr("********************************************************");
st->cr();
}
#endif
C:\hotspot-69087d08d473\src\share\vm/ci/ciTypeFlow.hpp
#ifndef SHARE_VM_CI_CITYPEFLOW_HPP
#define SHARE_VM_CI_CITYPEFLOW_HPP
#ifdef COMPILER2
#include "ci/ciEnv.hpp"
#include "ci/ciKlass.hpp"
#include "ci/ciMethodBlocks.hpp"
#endif
#ifdef SHARK
#include "ci/ciEnv.hpp"
#include "ci/ciKlass.hpp"
#include "ci/ciMethodBlocks.hpp"
#include "shark/shark_globals.hpp"
#endif
class ciTypeFlow : public ResourceObj {
private:
ciEnv* _env;
ciMethod* _method;
ciMethodBlocks* _methodBlocks;
int _osr_bci;
int _max_locals;
int _max_stack;
int _code_size;
bool _has_irreducible_entry;
const char* _failure_reason;
public:
class StateVector;
class Loop;
class Block;
ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci = InvocationEntryBci);
ciMethod* method() const { return _method; }
ciEnv* env() { return _env; }
Arena* arena() { return _env->arena(); }
bool is_osr_flow() const{ return _osr_bci != InvocationEntryBci; }
int start_bci() const { return is_osr_flow()? _osr_bci: 0; }
int max_locals() const { return _max_locals; }
int max_stack() const { return _max_stack; }
int max_cells() const { return _max_locals + _max_stack; }
int code_size() const { return _code_size; }
bool has_irreducible_entry() const { return _has_irreducible_entry; }
class JsrRecord : public ResourceObj {
private:
int _entry_address;
int _return_address;
public:
JsrRecord(int entry_address, int return_address) {
_entry_address = entry_address;
_return_address = return_address;
}
int entry_address() const { return _entry_address; }
int return_address() const { return _return_address; }
void print_on(outputStream* st) const {
#ifndef PRODUCT
st->print("%d->%d", entry_address(), return_address());
#endif
}
};
class JsrSet : public ResourceObj {
private:
GrowableArray<JsrRecord*>* _set;
JsrRecord* record_at(int i) {
return _set->at(i);
}
void insert_jsr_record(JsrRecord* record);
void remove_jsr_record(int return_address);
public:
JsrSet(Arena* arena, int default_len = 4);
void copy_into(JsrSet* jsrs);
bool is_compatible_with(JsrSet* other);
void apply_control(ciTypeFlow* analyzer,
ciBytecodeStream* str,
StateVector* state);
int size() const { return _set->length(); }
void print_on(outputStream* st) const PRODUCT_RETURN;
};
class LocalSet VALUE_OBJ_CLASS_SPEC {
private:
enum Constants { max = 63 };
uint64_t _bits;
public:
LocalSet() : _bits(0) {}
void add(uint32_t i) { if (i < (uint32_t)max) _bits |= (1LL << i); }
void add(LocalSet* ls) { _bits |= ls->_bits; }
bool test(uint32_t i) const { return i < (uint32_t)max ? (_bits>>i)&1U : true; }
void clear() { _bits = 0; }
void print_on(outputStream* st, int limit) const PRODUCT_RETURN;
};
enum Cell {
Cell_0, Cell_max = INT_MAX
};
class StateVector : public ResourceObj {
private:
ciType** _types;
int _stack_size;
int _monitor_count;
ciTypeFlow* _outer;
int _trap_bci;
int _trap_index;
LocalSet _def_locals; // For entire block
static ciType* type_meet_internal(ciType* t1, ciType* t2, ciTypeFlow* analyzer);
public:
enum {
T_TOP = T_VOID, // why not?
T_BOTTOM = T_CONFLICT,
T_LONG2 = T_SHORT, // 2nd word of T_LONG
T_DOUBLE2 = T_CHAR, // 2nd word of T_DOUBLE
T_NULL = T_BYTE // for now.
};
static ciType* top_type() { return ciType::make((BasicType)T_TOP); }
static ciType* bottom_type() { return ciType::make((BasicType)T_BOTTOM); }
static ciType* long2_type() { return ciType::make((BasicType)T_LONG2); }
static ciType* double2_type(){ return ciType::make((BasicType)T_DOUBLE2); }
static ciType* null_type() { return ciType::make((BasicType)T_NULL); }
static ciType* half_type(ciType* t) {
switch (t->basic_type()) {
case T_LONG: return long2_type();
case T_DOUBLE: return double2_type();
default: ShouldNotReachHere(); return NULL;
}
}
ciType* type_meet(ciType* t1, ciType* t2) {
return type_meet_internal(t1, t2, outer());
}
ciTypeFlow* outer() const { return _outer; }
int stack_size() const { return _stack_size; }
void set_stack_size(int ss) { _stack_size = ss; }
int monitor_count() const { return _monitor_count; }
void set_monitor_count(int mc) { _monitor_count = mc; }
LocalSet* def_locals() { return &_def_locals; }
const LocalSet* def_locals() const { return &_def_locals; }
static Cell start_cell() { return (Cell)0; }
static Cell next_cell(Cell c) { return (Cell)(((int)c) + 1); }
Cell limit_cell() const {
return (Cell)(outer()->max_locals() + stack_size());
}
Cell local(int lnum) const {
assert(lnum < outer()->max_locals(), "index check");
return (Cell)(lnum);
}
Cell stack(int snum) const {
assert(snum < stack_size(), "index check");
return (Cell)(outer()->max_locals() + snum);
}
Cell tos() const { return stack(stack_size()-1); }
ciType* local_type_at(int i) const { return type_at(local(i)); }
ciType* stack_type_at(int i) const { return type_at(stack(i)); }
ciType* type_at(Cell c) const {
assert(start_cell() <= c && c < limit_cell(), "out of bounds");
return _types[c];
}
void set_type_at(Cell c, ciType* type) {
assert(start_cell() <= c && c < limit_cell(), "out of bounds");
_types[c] = type;
}
void set_type_at_tos(ciType* type) { set_type_at(tos(), type); }
ciType* type_at_tos() const { return type_at(tos()); }
void push(ciType* type) {
_stack_size++;
set_type_at_tos(type);
}
void pop() {
debug_only(set_type_at_tos(bottom_type()));
_stack_size--;
}
ciType* pop_value() {
ciType* t = type_at_tos();
pop();
return t;
}
bool is_reference(ciType* type) const {
return type == null_type() || !type->is_primitive_type();
}
bool is_int(ciType* type) const {
return type->basic_type() == T_INT;
}
bool is_long(ciType* type) const {
return type->basic_type() == T_LONG;
}
bool is_float(ciType* type) const {
return type->basic_type() == T_FLOAT;
}
bool is_double(ciType* type) const {
return type->basic_type() == T_DOUBLE;
}
void store_to_local(int lnum) {
_def_locals.add((uint) lnum);
}
void push_translate(ciType* type);
void push_int() {
push(ciType::make(T_INT));
}
void pop_int() {
assert(is_int(type_at_tos()), "must be integer");
pop();
}
void check_int(Cell c) {
assert(is_int(type_at(c)), "must be integer");
}
void push_double() {
push(ciType::make(T_DOUBLE));
push(double2_type());
}
void pop_double() {
assert(type_at_tos() == double2_type(), "must be 2nd half");
pop();
assert(is_double(type_at_tos()), "must be double");
pop();
}
void push_float() {
push(ciType::make(T_FLOAT));
}
void pop_float() {
assert(is_float(type_at_tos()), "must be float");
pop();
}
void push_long() {
push(ciType::make(T_LONG));
push(long2_type());
}
void pop_long() {
assert(type_at_tos() == long2_type(), "must be 2nd half");
pop();
assert(is_long(type_at_tos()), "must be long");
pop();
}
void push_object(ciKlass* klass) {
push(klass);
}
void pop_object() {
assert(is_reference(type_at_tos()), "must be reference type");
pop();
}
void pop_array() {
assert(type_at_tos() == null_type() ||
type_at_tos()->is_array_klass(), "must be array type");
pop();
}
ciObjArrayKlass* pop_objArray() {
ciType* array = pop_value();
if (array == null_type()) return NULL;
assert(array->is_obj_array_klass(), "must be object array type");
return array->as_obj_array_klass();
}
ciTypeArrayKlass* pop_typeArray() {
ciType* array = pop_value();
if (array == null_type()) return NULL;
assert(array->is_type_array_klass(), "must be prim array type");
return array->as_type_array_klass();
}
void push_null() {
push(null_type());
}
void do_null_assert(ciKlass* unloaded_klass);
void do_aaload(ciBytecodeStream* str);
void do_checkcast(ciBytecodeStream* str);
void do_getfield(ciBytecodeStream* str);
void do_getstatic(ciBytecodeStream* str);
void do_invoke(ciBytecodeStream* str, bool has_receiver);
void do_jsr(ciBytecodeStream* str);
void do_ldc(ciBytecodeStream* str);
void do_multianewarray(ciBytecodeStream* str);
void do_new(ciBytecodeStream* str);
void do_newarray(ciBytecodeStream* str);
void do_putfield(ciBytecodeStream* str);
void do_putstatic(ciBytecodeStream* str);
void do_ret(ciBytecodeStream* str);
void overwrite_local_double_long(int index) {
int prev_index = index - 1;
if (prev_index >= 0 &&
(is_double(type_at(local(prev_index))) ||
is_long(type_at(local(prev_index))))) {
set_type_at(local(prev_index), bottom_type());
}
}
void load_local_object(int index) {
ciType* type = type_at(local(index));
assert(is_reference(type), "must be reference type");
push(type);
}
void store_local_object(int index) {
ciType* type = pop_value();
assert(is_reference(type) || type->is_return_address(),
"must be reference type or return address");
overwrite_local_double_long(index);
set_type_at(local(index), type);
store_to_local(index);
}
void load_local_double(int index) {
ciType* type = type_at(local(index));
ciType* type2 = type_at(local(index+1));
assert(is_double(type), "must be double type");
assert(type2 == double2_type(), "must be 2nd half");
push(type);
push(double2_type());
}
void store_local_double(int index) {
ciType* type2 = pop_value();
ciType* type = pop_value();
assert(is_double(type), "must be double");
assert(type2 == double2_type(), "must be 2nd half");
overwrite_local_double_long(index);
set_type_at(local(index), type);
set_type_at(local(index+1), type2);
store_to_local(index);
store_to_local(index+1);
}
void load_local_float(int index) {
ciType* type = type_at(local(index));
assert(is_float(type), "must be float type");
push(type);
}
void store_local_float(int index) {
ciType* type = pop_value();
assert(is_float(type), "must be float type");
overwrite_local_double_long(index);
set_type_at(local(index), type);
store_to_local(index);
}
void load_local_int(int index) {
ciType* type = type_at(local(index));
assert(is_int(type), "must be int type");
push(type);
}
void store_local_int(int index) {
ciType* type = pop_value();
assert(is_int(type), "must be int type");
overwrite_local_double_long(index);
set_type_at(local(index), type);
store_to_local(index);
}
void load_local_long(int index) {
ciType* type = type_at(local(index));
ciType* type2 = type_at(local(index+1));
assert(is_long(type), "must be long type");
assert(type2 == long2_type(), "must be 2nd half");
push(type);
push(long2_type());
}
void store_local_long(int index) {
ciType* type2 = pop_value();
ciType* type = pop_value();
assert(is_long(type), "must be long");
assert(type2 == long2_type(), "must be 2nd half");
overwrite_local_double_long(index);
set_type_at(local(index), type);
set_type_at(local(index+1), type2);
store_to_local(index);
store_to_local(index+1);
}
void trap(ciBytecodeStream* str, ciKlass* klass, int index);
public:
StateVector(ciTypeFlow* outer);
void copy_into(StateVector* copy) const;
bool meet(const StateVector* incoming);
bool meet_exception(ciInstanceKlass* exc, const StateVector* incoming);
bool apply_one_bytecode(ciBytecodeStream* stream);
int trap_bci() { return _trap_bci; }
int trap_index() { return _trap_index; }
void print_cell_on(outputStream* st, Cell c) const PRODUCT_RETURN;
void print_on(outputStream* st) const PRODUCT_RETURN;
};
enum CreateOption {
create_public_copy,
create_backedge_copy,
no_create
};
class SuccIter : public StackObj {
private:
Block* _pred;
int _index;
Block* _succ;
public:
SuccIter() : _pred(NULL), _index(-1), _succ(NULL) {}
SuccIter(Block* pred) : _pred(pred), _index(-1), _succ(NULL) { next(); }
int index() { return _index; }
Block* pred() { return _pred; } // Return predecessor
bool done() { return _index < 0; } // Finished?
Block* succ() { return _succ; } // Return current successor
void next(); // Advance
void set_succ(Block* succ); // Update current successor
bool is_normal_ctrl() { return index() < _pred->successors()->length(); }
};
class Block : public ResourceObj {
private:
ciBlock* _ciblock;
GrowableArray<Block*>* _exceptions;
GrowableArray<ciInstanceKlass*>* _exc_klasses;
GrowableArray<Block*>* _successors;
StateVector* _state;
JsrSet* _jsrs;
int _trap_bci;
int _trap_index;
int _pre_order;
int _post_order; // used to compute rpo
bool _backedge_copy;
bool _irreducible_entry;
bool _has_monitorenter;
bool _on_work_list; // on the work list
Block* _next;
Block* _rpo_next; // Reverse post order list
Loop* _loop; // nearest loop
ciBlock* ciblock() const { return _ciblock; }
StateVector* state() const { return _state; }
void compute_exceptions();
public:
Block(ciTypeFlow* outer, ciBlock* ciblk, JsrSet* jsrs);
void set_trap(int trap_bci, int trap_index) {
_trap_bci = trap_bci;
_trap_index = trap_index;
assert(has_trap(), "");
}
bool has_trap() const { return _trap_bci != -1; }
int trap_bci() const { assert(has_trap(), ""); return _trap_bci; }
int trap_index() const { assert(has_trap(), ""); return _trap_index; }
ciTypeFlow* outer() const { return state()->outer(); }
int start() const { return _ciblock->start_bci(); }
int limit() const { return _ciblock->limit_bci(); }
int control() const { return _ciblock->control_bci(); }
JsrSet* jsrs() const { return _jsrs; }
bool is_backedge_copy() const { return _backedge_copy; }
void set_backedge_copy(bool z);
int backedge_copy_count() const { return outer()->backedge_copy_count(ciblock()->index(), _jsrs); }
int stack_size() const { return _state->stack_size(); }
int monitor_count() const { return _state->monitor_count(); }
ciType* local_type_at(int i) const { return _state->local_type_at(i); }
ciType* stack_type_at(int i) const { return _state->stack_type_at(i); }
bool is_invariant_local(uint v) const {
assert(is_loop_head(), "only loop heads");
Loop* lp = loop();
while (lp->parent() != NULL) {
if (lp->parent()->head() != lp->head()) break;
lp = lp->parent();
}
return !lp->def_locals()->test(v);
}
LocalSet* def_locals() { return _state->def_locals(); }
const LocalSet* def_locals() const { return _state->def_locals(); }
GrowableArray<Block*>* successors(ciBytecodeStream* str,
StateVector* state,
JsrSet* jsrs);
GrowableArray<Block*>* successors() {
assert(_successors != NULL, "must be filled in");
return _successors;
}
GrowableArray<Block*>* exceptions() {
if (_exceptions == NULL) {
compute_exceptions();
}
return _exceptions;
}
GrowableArray<ciInstanceKlass*>* exc_klasses() {
if (_exc_klasses == NULL) {
compute_exceptions();
}
return _exc_klasses;
}
bool is_compatible_with(JsrSet* other) {
return _jsrs->is_compatible_with(other);
}
void copy_state_into(StateVector* copy) const {
_state->copy_into(copy);
}
void copy_jsrs_into(JsrSet* copy) const {
_jsrs->copy_into(copy);
}
bool meet(const StateVector* incoming) {
return state()->meet(incoming);
}
bool meet_exception(ciInstanceKlass* exc, const StateVector* incoming) {
return state()->meet_exception(exc, incoming);
}
void set_next(Block* block) { _next = block; }
Block* next() const { return _next; }
void set_on_work_list(bool c) { _on_work_list = c; }
bool is_on_work_list() const { return _on_work_list; }
bool has_pre_order() const { return _pre_order >= 0; }
void set_pre_order(int po) { assert(!has_pre_order(), ""); _pre_order = po; }
int pre_order() const { assert(has_pre_order(), ""); return _pre_order; }
void set_next_pre_order() { set_pre_order(outer()->inc_next_pre_order()); }
bool is_start() const { return _pre_order == outer()->start_block_num(); }
void df_init();
bool has_post_order() const { return _post_order >= 0; }
void set_post_order(int po) { assert(!has_post_order() && po >= 0, ""); _post_order = po; }
void reset_post_order(int o){ _post_order = o; }
int post_order() const { assert(has_post_order(), ""); return _post_order; }
bool has_rpo() const { return has_post_order() && outer()->have_block_count(); }
int rpo() const { assert(has_rpo(), ""); return outer()->block_count() - post_order() - 1; }
void set_rpo_next(Block* b) { _rpo_next = b; }
Block* rpo_next() { return _rpo_next; }
Loop* loop() const { return _loop; }
void set_loop(Loop* lp) { _loop = lp; }
bool is_loop_head() const { return _loop && _loop->head() == this; }
void set_irreducible_entry(bool c) { _irreducible_entry = c; }
bool is_irreducible_entry() const { return _irreducible_entry; }
void set_has_monitorenter() { _has_monitorenter = true; }
bool has_monitorenter() const { return _has_monitorenter; }
bool is_visited() const { return has_pre_order(); }
bool is_post_visited() const { return has_post_order(); }
bool is_clonable_exit(Loop* lp);
Block* looping_succ(Loop* lp); // Successor inside of loop
bool is_single_entry_loop_head() const {
if (!is_loop_head()) return false;
for (Loop* lp = loop(); lp != NULL && lp->head() == this; lp = lp->parent())
if (lp->is_irreducible()) return false;
return true;
}
void print_value_on(outputStream* st) const PRODUCT_RETURN;
void print_on(outputStream* st) const PRODUCT_RETURN;
};
class Loop : public ResourceObj {
private:
Loop* _parent;
Loop* _sibling; // List of siblings, null terminated
Loop* _child; // Head of child list threaded thru sibling pointer
Block* _head; // Head of loop
Block* _tail; // Tail of loop
bool _irreducible;
LocalSet _def_locals;
public:
Loop(Block* head, Block* tail) :
_head(head), _tail(tail),
_parent(NULL), _sibling(NULL), _child(NULL),
_irreducible(false), _def_locals() {}
Loop* parent() const { return _parent; }
Loop* sibling() const { return _sibling; }
Loop* child() const { return _child; }
Block* head() const { return _head; }
Block* tail() const { return _tail; }
void set_parent(Loop* p) { _parent = p; }
void set_sibling(Loop* s) { _sibling = s; }
void set_child(Loop* c) { _child = c; }
void set_head(Block* hd) { _head = hd; }
void set_tail(Block* tl) { _tail = tl; }
int depth() const; // nesting depth
bool contains(Loop* lp) const;
bool contains(Block* blk) const { return contains(blk->loop()); }
LocalSet* def_locals() { return &_def_locals; }
const LocalSet* def_locals() const { return &_def_locals; }
Loop* sorted_merge(Loop* lp);
void set_irreducible(Block* entry) {
_irreducible = true;
entry->set_irreducible_entry(true);
}
bool is_irreducible() const { return _irreducible; }
bool is_root() const { return _tail->pre_order() == max_jint; }
void print(outputStream* st = tty, int indent = 0) const PRODUCT_RETURN;
};
class PostorderLoops : public StackObj {
private:
Loop* _root;
Loop* _current;
public:
PostorderLoops(Loop* root) : _root(root), _current(root) {
while (_current->child() != NULL) {
_current = _current->child();
}
}
bool done() { return _current == NULL; } // Finished iterating?
void next(); // Advance to next loop
Loop* current() { return _current; } // Return current loop.
};
class PreorderLoops : public StackObj {
private:
Loop* _root;
Loop* _current;
public:
PreorderLoops(Loop* root) : _root(root), _current(root) {}
bool done() { return _current == NULL; } // Finished iterating?
void next(); // Advance to next loop
Loop* current() { return _current; } // Return current loop.
};
enum {
FALL_THROUGH = 0, // normal control
IF_NOT_TAKEN = 0, // the not-taken branch of an if (i.e., fall-through)
IF_TAKEN = 1, // the taken branch of an if
GOTO_TARGET = 0, // unique successor for goto, jsr, or ret
SWITCH_DEFAULT = 0, // default branch of a switch
SWITCH_CASES = 1 // first index for any non-default switch branches
};
private:
Block** _block_map;
GrowableArray<Block*>** _idx_to_blocklist;
int _ciblock_count;
bool can_trap(ciBytecodeStream& str);
bool clone_loop_heads(Loop* lp, StateVector* temp_vector, JsrSet* temp_set);
Block* clone_loop_head(Loop* lp, StateVector* temp_vector, JsrSet* temp_set);
public:
Block* block_at(int bci, JsrSet* set, CreateOption option = create_public_copy);
Block* get_block_for(int ciBlockIndex, JsrSet* jsrs, CreateOption option = create_public_copy);
int backedge_copy_count(int ciBlockIndex, JsrSet* jsrs) const;
Block* existing_block_at(int bci, JsrSet* set) { return block_at(bci, set, no_create); }
bool failing() { return env()->failing() || _failure_reason != NULL; }
const char* failure_reason() { return _failure_reason; }
void record_failure(const char* reason);
int have_block_count() const { return _block_map != NULL; }
int block_count() const { assert(have_block_count(), "");
return _next_pre_order; }
Block* pre_order_at(int po) const { assert(0 <= po && po < block_count(), "out of bounds");
return _block_map[po]; }
Block* start_block() const { return pre_order_at(start_block_num()); }
int start_block_num() const { return 0; }
Block* rpo_at(int rpo) const { assert(0 <= rpo && rpo < block_count(), "out of bounds");
return _block_map[rpo]; }
int next_pre_order() { return _next_pre_order; }
int inc_next_pre_order() { return _next_pre_order++; }
private:
Block* _work_list;
Block* _rpo_list;
int _next_pre_order;
bool work_list_empty() { return _work_list == NULL; }
Block* work_list_next();
void add_to_work_list(Block* block);
void prepend_to_rpo_list(Block* blk) {
blk->set_rpo_next(_rpo_list);
_rpo_list = blk;
}
Loop* _loop_tree_root;
int _jsr_count;
GrowableArray<JsrRecord*>* _jsr_records;
public:
JsrRecord* make_jsr_record(int entry_address, int return_address);
void set_loop_tree_root(Loop* ltr) { _loop_tree_root = ltr; }
Loop* loop_tree_root() { return _loop_tree_root; }
private:
const StateVector* get_start_state();
void flow_exceptions(GrowableArray<Block*>* exceptions,
GrowableArray<ciInstanceKlass*>* exc_klasses,
StateVector* state);
void flow_successors(GrowableArray<Block*>* successors,
StateVector* state);
void flow_block(Block* block,
StateVector* scratch_state,
JsrSet* scratch_jsrs);
void flow_types();
void df_flow_types(Block* start,
bool do_flow,
StateVector* temp_vector,
JsrSet* temp_set);
void build_loop_tree(Block* blk);
void map_blocks();
public:
void do_flow();
void print_on(outputStream* st) const PRODUCT_RETURN;
void rpo_print_on(outputStream* st) const PRODUCT_RETURN;
};
#endif // SHARE_VM_CI_CITYPEFLOW_HPP
C:\hotspot-69087d08d473\src\share\vm/ci/ciUtilities.cpp
#include "precompiled.hpp"
#include "ci/ciUtilities.hpp"
const char* basictype_to_str(BasicType t) {
const char* str = type2name(t);
if (str == NULL) return "illegal";
return str;
}
const char basictype_to_char(BasicType t) {
char c = type2char(t);
return c ? c : 'X';
}
C:\hotspot-69087d08d473\src\share\vm/ci/ciUtilities.hpp
#ifndef SHARE_VM_CI_CIUTILITIES_HPP
#define SHARE_VM_CI_CIUTILITIES_HPP
#include "ci/ciEnv.hpp"
#include "runtime/interfaceSupport.hpp"
#define VM_ENTRY_MARK \
CompilerThread* thread=CompilerThread::current(); \
ThreadInVMfromNative __tiv(thread); \
ResetNoHandleMark rnhm; \
HandleMarkCleaner __hm(thread); \
Thread* THREAD = thread; \
debug_only(VMNativeEntryWrapper __vew;)
#define VM_QUICK_ENTRY_MARK \
CompilerThread* thread=CompilerThread::current(); \
ThreadInVMfromNative __tiv(thread); \
Thread* THREAD = thread; \
debug_only(VMNativeEntryWrapper __vew;)
#define EXCEPTION_CONTEXT \
CompilerThread* thread=CompilerThread::current(); \
Thread* THREAD = thread;
#define CURRENT_ENV \
ciEnv::current()
#define CURRENT_THREAD_ENV \
ciEnv::current(thread)
#define IS_IN_VM \
ciEnv::is_in_vm()
#define ASSERT_IN_VM \
assert(IS_IN_VM, "must be in vm state");
#define GUARDED_VM_ENTRY(action) \
{if (IS_IN_VM) { action } else { VM_ENTRY_MARK; { action }}}
#define GUARDED_VM_QUICK_ENTRY(action) \
{if (IS_IN_VM) { action } else { VM_QUICK_ENTRY_MARK; { action }}}
#define KILL_COMPILE_ON_FATAL_(result) \
THREAD); \
if (HAS_PENDING_EXCEPTION) { \
if (PENDING_EXCEPTION->klass() == \
SystemDictionary::ThreadDeath_klass()) { \
fatal("unhandled ci exception"); \
return (result); \
} \
CLEAR_PENDING_EXCEPTION; \
return (result); \
} \
(void)(0
#define KILL_COMPILE_ON_ANY \
THREAD); \
if (HAS_PENDING_EXCEPTION) { \
fatal("unhandled ci exception"); \
CLEAR_PENDING_EXCEPTION; \
} \
(void)(0
inline const char* bool_to_str(bool b) {
return ((b) ? "true" : "false");
}
const char* basictype_to_str(BasicType t);
const char basictype_to_char(BasicType t);
#endif // SHARE_VM_CI_CIUTILITIES_HPP
C:\hotspot-69087d08d473\src\share\vm/ci/compilerInterface.hpp
#ifndef SHARE_VM_CI_COMPILERINTERFACE_HPP
#define SHARE_VM_CI_COMPILERINTERFACE_HPP
#include "ci/ciArray.hpp"
#include "ci/ciArrayKlass.hpp"
#include "ci/ciCallProfile.hpp"
#include "ci/ciConstant.hpp"
#include "ci/ciEnv.hpp"
#include "ci/ciExceptionHandler.hpp"
#include "ci/ciField.hpp"
#include "ci/ciFlags.hpp"
#include "ci/ciInstance.hpp"
#include "ci/ciInstanceKlass.hpp"
#include "ci/ciKlass.hpp"
#include "ci/ciMethod.hpp"
#include "ci/ciNullObject.hpp"
#include "ci/ciObjArray.hpp"
#include "ci/ciObjArrayKlass.hpp"
#include "ci/ciObject.hpp"
#include "ci/ciSignature.hpp"
#include "ci/ciStreams.hpp"
#include "ci/ciSymbol.hpp"
#include "ci/ciTypeArray.hpp"
#include "ci/ciTypeArrayKlass.hpp"
#endif // SHARE_VM_CI_COMPILERINTERFACE_HPP
C:\hotspot-69087d08d473\src\share\vm/classfile/altHashing.cpp
#include "precompiled.hpp"
#include "classfile/altHashing.hpp"
#include "classfile/systemDictionary.hpp"
#include "oops/markOop.hpp"
#include "runtime/os.hpp"
intptr_t object_hash(Klass* k) {
intptr_t hc = k->java_mirror()->mark()->hash();
return hc != markOopDesc::no_hash ? hc : os::random();
}
uint64_t AltHashing::compute_seed() {
uint64_t nanos = os::javaTimeNanos();
uint64_t now = os::javaTimeMillis();
uint32_t SEED_MATERIAL[8] = {
(uint32_t) object_hash(SystemDictionary::String_klass()),
(uint32_t) object_hash(SystemDictionary::System_klass()),
(uint32_t) os::random(), // current thread isn't a java thread
(uint32_t) (((uint64_t)nanos) >> 32),
(uint32_t) nanos,
(uint32_t) (((uint64_t)now) >> 32),
(uint32_t) now,
(uint32_t) (os::javaTimeNanos() >> 2)
};
return halfsiphash_64(SEED_MATERIAL, 8);
}
static uint32_t Integer_rotateLeft(uint32_t i, int distance) {
return (i << distance) | (i >> (32 - distance));
}
static void halfsiphash_rounds(uint32_t v[4], int rounds) {
while (rounds-- > 0) {
v[0] += v[1];
v[1] = Integer_rotateLeft(v[1], 5);
v[1] ^= v[0];
v[0] = Integer_rotateLeft(v[0], 16);
v[2] += v[3];
v[3] = Integer_rotateLeft(v[3], 8);
v[3] ^= v[2];
v[0] += v[3];
v[3] = Integer_rotateLeft(v[3], 7);
v[3] ^= v[0];
v[2] += v[1];
v[1] = Integer_rotateLeft(v[1], 13);
v[1] ^= v[2];
v[2] = Integer_rotateLeft(v[2], 16);
}
}
static void halfsiphash_adddata(uint32_t v[4], uint32_t newdata, int rounds) {
v[3] ^= newdata;
halfsiphash_rounds(v, rounds);
v[0] ^= newdata;
}
static void halfsiphash_init32(uint32_t v[4], uint64_t seed) {
v[0] = seed & 0xffffffff;
v[1] = seed >> 32;
v[2] = 0x6c796765 ^ v[0];
v[3] = 0x74656462 ^ v[1];
}
static void halfsiphash_init64(uint32_t v[4], uint64_t seed) {
halfsiphash_init32(v, seed);
v[1] ^= 0xee;
}
uint32_t halfsiphash_finish32(uint32_t v[4], int rounds) {
v[2] ^= 0xff;
halfsiphash_rounds(v, rounds);
return (v[1] ^ v[3]);
}
static uint64_t halfsiphash_finish64(uint32_t v[4], int rounds) {
uint64_t rv;
v[2] ^= 0xee;
halfsiphash_rounds(v, rounds);
rv = v[1] ^ v[3];
v[1] ^= 0xdd;
halfsiphash_rounds(v, rounds);
rv |= (uint64_t)(v[1] ^ v[3]) << 32;
return rv;
}
uint32_t AltHashing::halfsiphash_32(uint64_t seed, const uint8_t* data, int len) {
uint32_t v[4];
uint32_t newdata;
int off = 0;
int count = len;
halfsiphash_init32(v, seed);
while (count >= 4) {
newdata = (data[off] & 0x0FF)
| (data[off + 1] & 0x0FF) << 8
| (data[off + 2] & 0x0FF) << 16
| data[off + 3] << 24;
count -= 4;
off += 4;
halfsiphash_adddata(v, newdata, 2);
}
newdata = ((uint32_t)len) << 24; // (Byte.SIZE / Byte.SIZE);
if (count > 0) {
switch (count) {
case 3:
newdata |= (data[off + 2] & 0x0ff) << 16;
case 2:
newdata |= (data[off + 1] & 0x0ff) << 8;
case 1:
newdata |= (data[off] & 0x0ff);
}
}
halfsiphash_adddata(v, newdata, 2);
return halfsiphash_finish32(v, 4);
}
uint32_t AltHashing::halfsiphash_32(uint64_t seed, const uint16_t* data, int len) {
uint32_t v[4];
uint32_t newdata;
int off = 0;
int count = len;
halfsiphash_init32(v, seed);
while (count >= 2) {
uint16_t d1 = data[off++] & 0x0FFFF;
uint16_t d2 = data[off++];
newdata = (d1 | d2 << 16);
count -= 2;
halfsiphash_adddata(v, newdata, 2);
}
newdata = ((uint32_t)len * 2) << 24; // (Character.SIZE / Byte.SIZE);
if (count > 0) {
newdata |= (uint32_t)data[off];
}
halfsiphash_adddata(v, newdata, 2);
return halfsiphash_finish32(v, 4);
}
uint64_t AltHashing::halfsiphash_64(uint64_t seed, const uint32_t* data, int len) {
uint32_t v[4];
int off = 0;
int end = len;
halfsiphash_init64(v, seed);
while (off < end) {
halfsiphash_adddata(v, (uint32_t)data[off++], 2);
}
halfsiphash_adddata(v, ((uint32_t)len * 4) << 24, 2); // (Integer.SIZE / Byte.SIZE);
return halfsiphash_finish64(v, 4);
}
uint64_t AltHashing::halfsiphash_64(const uint32_t* data, int len) {
return halfsiphash_64((uint64_t)0, data, len);
}
#ifndef PRODUCT
void AltHashing::testHalfsiphash_32_ByteArray() {
const int factor = 4;
uint8_t vector[256];
uint8_t hashes[factor * 256];
for (int i = 0; i < 256; i++) {
vector[i] = (uint8_t) i;
}
for (int i = 0; i < 256; i++) {
uint32_t hash = AltHashing::halfsiphash_32(256 - i, vector, i);
hashes[i * factor] = (uint8_t) hash;
hashes[i * factor + 1] = (uint8_t)(hash >> 8);
hashes[i * factor + 2] = (uint8_t)(hash >> 16);
hashes[i * factor + 3] = (uint8_t)(hash >> 24);
}
uint32_t final_hash = AltHashing::halfsiphash_32(0, hashes, factor*256);
static const uint32_t HALFSIPHASH_32_BYTE_CHECK_VALUE = 0xd2be7fd8;
assert (HALFSIPHASH_32_BYTE_CHECK_VALUE == final_hash,
err_msg(
"Calculated hash result not as expected. Expected " UINT32_FORMAT " got " UINT32_FORMAT,
HALFSIPHASH_32_BYTE_CHECK_VALUE,
final_hash));
}
void AltHashing::testHalfsiphash_32_CharArray() {
const int factor = 2;
uint16_t vector[256];
uint16_t hashes[factor * 256];
for (int i = 0; i < 256; i++) {
vector[i] = (uint16_t) i;
}
for (int i = 0; i < 256; i++) {
uint32_t hash = AltHashing::halfsiphash_32(256 - i, vector, i);
hashes[i * factor] = (uint16_t) hash;
hashes[i * factor + 1] = (uint16_t)(hash >> 16);
}
uint32_t final_hash = AltHashing::halfsiphash_32(0, hashes, factor*256);
static const uint32_t HALFSIPHASH_32_CHAR_CHECK_VALUE = 0x428bf8a5;
assert(HALFSIPHASH_32_CHAR_CHECK_VALUE == final_hash,
err_msg(
"Calculated hash result not as expected. Expected " UINT32_FORMAT " got " UINT32_FORMAT,
HALFSIPHASH_32_CHAR_CHECK_VALUE,
final_hash));
}
void AltHashing::testHalfsiphash_64_FromReference() {
const uint64_t seed = 0x0706050403020100;
const uint64_t results[16] = {
0xc83cb8b9591f8d21, 0xa12ee55b178ae7d5,
0x8c85e4bc20e8feed, 0x99c7f5ae9f1fc77b,
0xb5f37b5fd2aa3673, 0xdba7ee6f0a2bf51b,
0xf1a63fae45107470, 0xb516001efb5f922d,
0x6c6211d8469d7028, 0xdc7642ec407ad686,
0x4caec8671cc8385b, 0x5ab1dc27adf3301e,
0x3e3ea94bc0a8eaa9, 0xe150f598795a4402,
0x1d5ff142f992a4a1, 0x60e426bf902876d6
};
uint32_t vector[16];
for (int i = 0; i < 16; i++)
vector[i] = 0x03020100 + i * 0x04040404;
for (int i = 0; i < 16; i++) {
uint64_t hash = AltHashing::halfsiphash_64(seed, vector, i);
assert(results[i] == hash,
err_msg(
"Calculated hash result not as expected. Round %d: "
"Expected " UINT64_FORMAT_X " got " UINT64_FORMAT_X "\n",
i,
results[i],
hash));
}
}
void AltHashing::test_alt_hash() {
testHalfsiphash_32_ByteArray();
testHalfsiphash_32_CharArray();
testHalfsiphash_64_FromReference();
}
#endif // PRODUCT
C:\hotspot-69087d08d473\src\share\vm/classfile/altHashing.hpp
#ifndef SHARE_VM_CLASSFILE_ALTHASHING_HPP
#define SHARE_VM_CLASSFILE_ALTHASHING_HPP
#include "prims/jni.h"
#include "memory/allocation.hpp"
class AltHashing : AllStatic {
static uint64_t halfsiphash_64(const uint32_t* data, int len);
static uint64_t halfsiphash_64(uint64_t seed, const uint32_t* data, int len);
#ifndef PRODUCT
static void testHalfsiphash_32_ByteArray();
static void testHalfsiphash_32_CharArray();
static void testHalfsiphash_64_FromReference();
#endif // PRODUCT
public:
static uint64_t compute_seed();
static uint32_t halfsiphash_32(uint64_t seed, const uint8_t* data, int len);
static uint32_t halfsiphash_32(uint64_t seed, const uint16_t* data, int len);
NOT_PRODUCT(static void test_alt_hash();)
};
#endif // SHARE_VM_CLASSFILE_ALTHASHING_HPP
C:\hotspot-69087d08d473\src\share\vm/classfile/bytecodeAssembler.cpp
#include "precompiled.hpp"
#include "classfile/bytecodeAssembler.hpp"
#include "interpreter/bytecodes.hpp"
#include "memory/oopFactory.hpp"
#include "oops/constantPool.hpp"
#ifdef TARGET_ARCH_x86
# include "bytes_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "bytes_sparc.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "bytes_zero.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "bytes_arm.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "bytes_ppc.hpp"
#endif
#ifdef TARGET_ARCH_aarch64
# include "bytes_aarch64.hpp"
#endif
u2 BytecodeConstantPool::find_or_add(BytecodeCPEntry const& bcpe) {
u2 index;
u2* probe = _indices.get(bcpe);
if (probe == NULL) {
index = _entries.length();
_entries.append(bcpe);
_indices.put(bcpe, index);
} else {
index = *probe;
}
return index + _orig->length();
}
ConstantPool* BytecodeConstantPool::create_constant_pool(TRAPS) const {
if (_entries.length() == 0) {
return _orig;
}
ConstantPool* cp = ConstantPool::allocate(
_orig->pool_holder()->class_loader_data(),
_orig->length() + _entries.length(), CHECK_NULL);
cp->set_pool_holder(_orig->pool_holder());
_orig->copy_cp_to(1, _orig->length() - 1, cp, 1, CHECK_NULL);
for (int i = 0; i < _entries.length(); ++i) {
BytecodeCPEntry entry = _entries.at(i);
int idx = i + _orig->length();
switch (entry._tag) {
case BytecodeCPEntry::UTF8:
entry._u.utf8->increment_refcount();
cp->symbol_at_put(idx, entry._u.utf8);
break;
case BytecodeCPEntry::KLASS:
cp->unresolved_klass_at_put(
idx, cp->symbol_at(entry._u.klass));
break;
case BytecodeCPEntry::STRING:
cp->unresolved_string_at_put(
idx, cp->symbol_at(entry._u.string));
break;
case BytecodeCPEntry::NAME_AND_TYPE:
cp->name_and_type_at_put(idx,
entry._u.name_and_type.name_index,
entry._u.name_and_type.type_index);
break;
case BytecodeCPEntry::METHODREF:
cp->method_at_put(idx,
entry._u.methodref.class_index,
entry._u.methodref.name_and_type_index);
break;
default:
ShouldNotReachHere();
}
}
return cp;
}
void BytecodeAssembler::append(u1 imm_u1) {
_code->append(imm_u1);
}
void BytecodeAssembler::append(u2 imm_u2) {
_code->append(0);
_code->append(0);
Bytes::put_Java_u2(_code->adr_at(_code->length() - 2), imm_u2);
}
void BytecodeAssembler::append(u4 imm_u4) {
_code->append(0);
_code->append(0);
_code->append(0);
_code->append(0);
Bytes::put_Java_u4(_code->adr_at(_code->length() - 4), imm_u4);
}
void BytecodeAssembler::xload(u4 index, u1 onebyteop, u1 twobyteop) {
if (index < 4) {
_code->append(onebyteop + index);
} else {
_code->append(twobyteop);
_code->append((u2)index);
}
}
void BytecodeAssembler::dup() {
_code->append(Bytecodes::_dup);
}
void BytecodeAssembler::_new(Symbol* sym) {
u2 cpool_index = _cp->klass(sym);
_code->append(Bytecodes::_new);
append(cpool_index);
}
void BytecodeAssembler::load_string(Symbol* sym) {
u2 cpool_index = _cp->string(sym);
if (cpool_index < 0x100) {
ldc(cpool_index);
} else {
ldc_w(cpool_index);
}
}
void BytecodeAssembler::ldc(u1 index) {
_code->append(Bytecodes::_ldc);
append(index);
}
void BytecodeAssembler::ldc_w(u2 index) {
_code->append(Bytecodes::_ldc_w);
append(index);
}
void BytecodeAssembler::athrow() {
_code->append(Bytecodes::_athrow);
}
void BytecodeAssembler::iload(u4 index) {
xload(index, Bytecodes::_iload_0, Bytecodes::_iload);
}
void BytecodeAssembler::lload(u4 index) {
xload(index, Bytecodes::_lload_0, Bytecodes::_lload);
}
void BytecodeAssembler::fload(u4 index) {
xload(index, Bytecodes::_fload_0, Bytecodes::_fload);
}
void BytecodeAssembler::dload(u4 index) {
xload(index, Bytecodes::_dload_0, Bytecodes::_dload);
}
void BytecodeAssembler::aload(u4 index) {
xload(index, Bytecodes::_aload_0, Bytecodes::_aload);
}
void BytecodeAssembler::load(BasicType bt, u4 index) {
switch (bt) {
case T_BOOLEAN:
case T_CHAR:
case T_BYTE:
case T_SHORT:
case T_INT: iload(index); break;
case T_FLOAT: fload(index); break;
case T_DOUBLE: dload(index); break;
case T_LONG: lload(index); break;
case T_OBJECT:
case T_ARRAY: aload(index); break;
default:
ShouldNotReachHere();
}
}
void BytecodeAssembler::checkcast(Symbol* sym) {
u2 cpool_index = _cp->klass(sym);
_code->append(Bytecodes::_checkcast);
append(cpool_index);
}
void BytecodeAssembler::invokespecial(Method* method) {
invokespecial(method->klass_name(), method->name(), method->signature());
}
void BytecodeAssembler::invokespecial(Symbol* klss, Symbol* name, Symbol* sig) {
u2 methodref_index = _cp->methodref(klss, name, sig);
_code->append(Bytecodes::_invokespecial);
append(methodref_index);
}
void BytecodeAssembler::invokevirtual(Method* method) {
invokevirtual(method->klass_name(), method->name(), method->signature());
}
void BytecodeAssembler::invokevirtual(Symbol* klss, Symbol* name, Symbol* sig) {
u2 methodref_index = _cp->methodref(klss, name, sig);
_code->append(Bytecodes::_invokevirtual);
append(methodref_index);
}
void BytecodeAssembler::ireturn() {
_code->append(Bytecodes::_ireturn);
}
void BytecodeAssembler::lreturn() {
_code->append(Bytecodes::_lreturn);
}
void BytecodeAssembler::freturn() {
_code->append(Bytecodes::_freturn);
}
void BytecodeAssembler::dreturn() {
_code->append(Bytecodes::_dreturn);
}
void BytecodeAssembler::areturn() {
_code->append(Bytecodes::_areturn);
}
void BytecodeAssembler::_return() {
_code->append(Bytecodes::_return);
}
void BytecodeAssembler::_return(BasicType bt) {
switch (bt) {
case T_BOOLEAN:
case T_CHAR:
case T_BYTE:
case T_SHORT:
case T_INT: ireturn(); break;
case T_FLOAT: freturn(); break;
case T_DOUBLE: dreturn(); break;
case T_LONG: lreturn(); break;
case T_OBJECT:
case T_ARRAY: areturn(); break;
case T_VOID: _return(); break;
default:
ShouldNotReachHere();
}
}
C:\hotspot-69087d08d473\src\share\vm/classfile/bytecodeAssembler.hpp
#ifndef SHARE_VM_CLASSFILE_BYTECODEASSEMBLER_HPP
#define SHARE_VM_CLASSFILE_BYTECODEASSEMBLER_HPP
#include "memory/allocation.hpp"
#include "oops/method.hpp"
#include "oops/symbol.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/growableArray.hpp"
#include "utilities/resourceHash.hpp"
class BytecodeBuffer : public GrowableArray<u1> {
public:
BytecodeBuffer() : GrowableArray<u1>(20) {}
};
class BytecodeCPEntry VALUE_OBJ_CLASS_SPEC {
public:
enum tag {
ERROR_TAG,
UTF8,
KLASS,
STRING,
NAME_AND_TYPE,
METHODREF
};
u1 _tag;
union {
Symbol* utf8;
u2 klass;
u2 string;
struct {
u2 name_index;
u2 type_index;
} name_and_type;
struct {
u2 class_index;
u2 name_and_type_index;
} methodref;
uintptr_t hash;
} _u;
BytecodeCPEntry() : _tag(ERROR_TAG) { _u.hash = 0; }
BytecodeCPEntry(u1 tag) : _tag(tag) { _u.hash = 0; }
static BytecodeCPEntry utf8(Symbol* symbol) {
BytecodeCPEntry bcpe(UTF8);
bcpe._u.utf8 = symbol;
return bcpe;
}
static BytecodeCPEntry klass(u2 index) {
BytecodeCPEntry bcpe(KLASS);
bcpe._u.klass = index;
return bcpe;
}
static BytecodeCPEntry string(u2 index) {
BytecodeCPEntry bcpe(STRING);
bcpe._u.string = index;
return bcpe;
}
static BytecodeCPEntry name_and_type(u2 name, u2 type) {
BytecodeCPEntry bcpe(NAME_AND_TYPE);
bcpe._u.name_and_type.name_index = name;
bcpe._u.name_and_type.type_index = type;
return bcpe;
}
static BytecodeCPEntry methodref(u2 class_index, u2 nat) {
BytecodeCPEntry bcpe(METHODREF);
bcpe._u.methodref.class_index = class_index;
bcpe._u.methodref.name_and_type_index = nat;
return bcpe;
}
static bool equals(BytecodeCPEntry const& e0, BytecodeCPEntry const& e1) {
return e0._tag == e1._tag && e0._u.hash == e1._u.hash;
}
static unsigned hash(BytecodeCPEntry const& e0) {
return (unsigned)(e0._tag ^ e0._u.hash);
}
};
class BytecodeConstantPool : ResourceObj {
private:
typedef ResourceHashtable<BytecodeCPEntry, u2,
&BytecodeCPEntry::hash, &BytecodeCPEntry::equals> IndexHash;
ConstantPool* _orig;
GrowableArray<BytecodeCPEntry> _entries;
IndexHash _indices;
u2 find_or_add(BytecodeCPEntry const& bcpe);
public:
BytecodeConstantPool(ConstantPool* orig) : _orig(orig) {}
BytecodeCPEntry const& at(u2 index) const { return _entries.at(index); }
InstanceKlass* pool_holder() const {
return InstanceKlass::cast(_orig->pool_holder());
}
u2 utf8(Symbol* sym) {
return find_or_add(BytecodeCPEntry::utf8(sym));
}
u2 klass(Symbol* class_name) {
return find_or_add(BytecodeCPEntry::klass(utf8(class_name)));
}
u2 string(Symbol* str) {
return find_or_add(BytecodeCPEntry::string(utf8(str)));
}
u2 name_and_type(Symbol* name, Symbol* sig) {
return find_or_add(BytecodeCPEntry::name_and_type(utf8(name), utf8(sig)));
}
u2 methodref(Symbol* class_name, Symbol* name, Symbol* sig) {
return find_or_add(BytecodeCPEntry::methodref(
klass(class_name), name_and_type(name, sig)));
}
ConstantPool* create_constant_pool(TRAPS) const;
};
class BytecodeAssembler : StackObj {
private:
BytecodeBuffer* _code;
BytecodeConstantPool* _cp;
void append(u1 imm_u1);
void append(u2 imm_u2);
void append(u4 imm_u4);
void xload(u4 index, u1 quick, u1 twobyte);
public:
BytecodeAssembler(BytecodeBuffer* buffer, BytecodeConstantPool* cp)
: _code(buffer), _cp(cp) {}
void aload(u4 index);
void areturn();
void athrow();
void checkcast(Symbol* sym);
void dload(u4 index);
void dreturn();
void dup();
void fload(u4 index);
void freturn();
void iload(u4 index);
void invokespecial(Method* method);
void invokespecial(Symbol* cls, Symbol* name, Symbol* sig);
void invokevirtual(Method* method);
void invokevirtual(Symbol* cls, Symbol* name, Symbol* sig);
void ireturn();
void ldc(u1 index);
void ldc_w(u2 index);
void lload(u4 index);
void lreturn();
void _new(Symbol* sym);
void _return();
void load_string(Symbol* sym);
void load(BasicType bt, u4 index);
void _return(BasicType bt);
};
#endif // SHARE_VM_CLASSFILE_BYTECODEASSEMBLER_HPP
C:\hotspot-69087d08d473\src\share\vm/classfile/classFileError.cpp
#include "precompiled.hpp"
#include "classfile/classFileParser.hpp"
#include "classfile/stackMapTable.hpp"
#include "classfile/verifier.hpp"
PRAGMA_DIAG_PUSH
PRAGMA_FORMAT_NONLITERAL_IGNORED
void ClassFileParser::classfile_parse_error(const char* msg, TRAPS) {
ResourceMark rm(THREAD);
Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_ClassFormatError(),
msg, _class_name->as_C_string());
}
void ClassFileParser::classfile_parse_error(const char* msg, int index, TRAPS) {
ResourceMark rm(THREAD);
Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_ClassFormatError(),
msg, index, _class_name->as_C_string());
}
void ClassFileParser::classfile_parse_error(const char* msg, const char *name, TRAPS) {
ResourceMark rm(THREAD);
Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_ClassFormatError(),
msg, name, _class_name->as_C_string());
}
void ClassFileParser::classfile_parse_error(const char* msg, int index, const char *name, TRAPS) {
ResourceMark rm(THREAD);
Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_ClassFormatError(),
msg, index, name, _class_name->as_C_string());
}
void ClassFileParser::classfile_parse_error(const char* msg, const char* name, const char* signature, TRAPS) {
assert(_class_name != NULL, "invariant");
ResourceMark rm(THREAD);
Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_ClassFormatError(),
msg, name, signature, _class_name->as_C_string());
}
PRAGMA_DIAG_POP
void StackMapStream::stackmap_format_error(const char* msg, TRAPS) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"StackMapTable format error: %s", msg
);
}
C:\hotspot-69087d08d473\src\share\vm/classfile/classFileParser.cpp
#include "precompiled.hpp"
#include "classfile/classFileParser.hpp"
#include "classfile/classLoader.hpp"
#include "classfile/classLoaderData.hpp"
#include "classfile/classLoaderData.inline.hpp"
#include "classfile/defaultMethods.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#if INCLUDE_CDS
#include "classfile/systemDictionaryShared.hpp"
#endif
#include "classfile/verificationType.hpp"
#include "classfile/verifier.hpp"
#include "classfile/vmSymbols.hpp"
#include "memory/allocation.hpp"
#include "memory/gcLocker.hpp"
#include "memory/metadataFactory.hpp"
#include "memory/oopFactory.hpp"
#include "memory/referenceType.hpp"
#include "memory/universe.inline.hpp"
#include "oops/constantPool.hpp"
#include "oops/fieldStreams.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/instanceMirrorKlass.hpp"
#include "oops/klass.inline.hpp"
#include "oops/klassVtable.hpp"
#include "oops/method.hpp"
#include "oops/symbol.hpp"
#include "prims/jvm.h"
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/perfData.hpp"
#include "runtime/reflection.hpp"
#include "runtime/signature.hpp"
#include "runtime/timer.hpp"
#include "services/classLoadingService.hpp"
#include "services/threadService.hpp"
#include "utilities/array.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/ostream.hpp"
#define JAVA_CLASSFILE_MAGIC 0xCAFEBABE
#define JAVA_MIN_SUPPORTED_VERSION 45
#define JAVA_MAX_SUPPORTED_VERSION 52
#define JAVA_MAX_SUPPORTED_MINOR_VERSION 0
#define JAVA_1_5_VERSION 49
#define JAVA_6_VERSION 50
#define JAVA_7_VERSION 51
#define JAVA_8_VERSION 52
void ClassFileParser::parse_constant_pool_entries(int length, TRAPS) {
ClassFileStream* cfs0 = stream();
ClassFileStream cfs1 = *cfs0;
ClassFileStream* cfs = &cfs1;
#ifdef ASSERT
assert(cfs->allocated_on_stack(),"should be local");
u1* old_current = cfs0->current();
#endif
Handle class_loader(THREAD, _loader_data->class_loader());
const char* names[SymbolTable::symbol_alloc_batch_size];
int lengths[SymbolTable::symbol_alloc_batch_size];
int indices[SymbolTable::symbol_alloc_batch_size];
unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
int names_count = 0;
for (int index = 1; index < length; index++) {
u1 tag = cfs->get_u1_fast();
switch (tag) {
case JVM_CONSTANT_Class :
{
cfs->guarantee_more(3, CHECK); // name_index, tag/access_flags
u2 name_index = cfs->get_u2_fast();
_cp->klass_index_at_put(index, name_index);
}
break;
case JVM_CONSTANT_Fieldref :
{
cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
u2 class_index = cfs->get_u2_fast();
u2 name_and_type_index = cfs->get_u2_fast();
_cp->field_at_put(index, class_index, name_and_type_index);
}
break;
case JVM_CONSTANT_Methodref :
{
cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
u2 class_index = cfs->get_u2_fast();
u2 name_and_type_index = cfs->get_u2_fast();
_cp->method_at_put(index, class_index, name_and_type_index);
}
break;
case JVM_CONSTANT_InterfaceMethodref :
{
cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags
u2 class_index = cfs->get_u2_fast();
u2 name_and_type_index = cfs->get_u2_fast();
_cp->interface_method_at_put(index, class_index, name_and_type_index);
}
break;
case JVM_CONSTANT_String :
{
cfs->guarantee_more(3, CHECK); // string_index, tag/access_flags
u2 string_index = cfs->get_u2_fast();
_cp->string_index_at_put(index, string_index);
}
break;
case JVM_CONSTANT_MethodHandle :
case JVM_CONSTANT_MethodType :
if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
classfile_parse_error(
"Class file version does not support constant tag %u in class file %s",
tag, CHECK);
}
if (!EnableInvokeDynamic) {
classfile_parse_error(
"This JVM does not support constant tag %u in class file %s",
tag, CHECK);
}
if (tag == JVM_CONSTANT_MethodHandle) {
cfs->guarantee_more(4, CHECK); // ref_kind, method_index, tag/access_flags
u1 ref_kind = cfs->get_u1_fast();
u2 method_index = cfs->get_u2_fast();
_cp->method_handle_index_at_put(index, ref_kind, method_index);
} else if (tag == JVM_CONSTANT_MethodType) {
cfs->guarantee_more(3, CHECK); // signature_index, tag/access_flags
u2 signature_index = cfs->get_u2_fast();
_cp->method_type_index_at_put(index, signature_index);
} else {
ShouldNotReachHere();
}
break;
case JVM_CONSTANT_InvokeDynamic :
{
if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
classfile_parse_error(
"Class file version does not support constant tag %u in class file %s",
tag, CHECK);
}
if (!EnableInvokeDynamic) {
classfile_parse_error(
"This JVM does not support constant tag %u in class file %s",
tag, CHECK);
}
cfs->guarantee_more(5, CHECK); // bsm_index, nt, tag/access_flags
u2 bootstrap_specifier_index = cfs->get_u2_fast();
u2 name_and_type_index = cfs->get_u2_fast();
if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index)
_max_bootstrap_specifier_index = (int) bootstrap_specifier_index; // collect for later
_cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
}
break;
case JVM_CONSTANT_Integer :
{
cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags
u4 bytes = cfs->get_u4_fast();
_cp->int_at_put(index, (jint) bytes);
}
break;
case JVM_CONSTANT_Float :
{
cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags
u4 bytes = cfs->get_u4_fast();
_cp->float_at_put(index, *(jfloat*)&bytes);
}
break;
case JVM_CONSTANT_Long :
guarantee_property(index+1 < length,
"Invalid constant pool entry %u in class file %s",
index, CHECK);
{
cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags
u8 bytes = cfs->get_u8_fast();
_cp->long_at_put(index, bytes);
}
index++; // Skip entry following eigth-byte constant, see JVM book p. 98
break;
case JVM_CONSTANT_Double :
guarantee_property(index+1 < length,
"Invalid constant pool entry %u in class file %s",
index, CHECK);
{
cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags
u8 bytes = cfs->get_u8_fast();
_cp->double_at_put(index, *(jdouble*)&bytes);
}
index++; // Skip entry following eigth-byte constant, see JVM book p. 98
break;
case JVM_CONSTANT_NameAndType :
{
cfs->guarantee_more(5, CHECK); // name_index, signature_index, tag/access_flags
u2 name_index = cfs->get_u2_fast();
u2 signature_index = cfs->get_u2_fast();
_cp->name_and_type_at_put(index, name_index, signature_index);
}
break;
case JVM_CONSTANT_Utf8 :
{
cfs->guarantee_more(2, CHECK); // utf8_length
u2 utf8_length = cfs->get_u2_fast();
u1* utf8_buffer = cfs->get_u1_buffer();
assert(utf8_buffer != NULL, "null utf8 buffer");
cfs->guarantee_more(utf8_length+1, CHECK); // utf8 string, tag/access_flags
cfs->skip_u1_fast(utf8_length);
if (_need_verify) {
verify_legal_utf8((unsigned char*)utf8_buffer, utf8_length, CHECK);
}
if (EnableInvokeDynamic && has_cp_patch_at(index)) {
Handle patch = clear_cp_patch_at(index);
guarantee_property(java_lang_String::is_instance(patch()),
"Illegal utf8 patch at %d in class file %s",
index, CHECK);
char* str = java_lang_String::as_utf8_string(patch());
utf8_buffer = (u1*) str;
utf8_length = (u2) strlen(str);
}
unsigned int hash;
Symbol* result = SymbolTable::lookup_only((char*)utf8_buffer, utf8_length, hash);
if (result == NULL) {
names[names_count] = (char*)utf8_buffer;
lengths[names_count] = utf8_length;
indices[names_count] = index;
hashValues[names_count++] = hash;
if (names_count == SymbolTable::symbol_alloc_batch_size) {
SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);
names_count = 0;
}
} else {
_cp->symbol_at_put(index, result);
}
}
break;
default:
classfile_parse_error(
"Unknown constant tag %u in class file %s", tag, CHECK);
break;
}
}
if (names_count > 0) {
SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);
}
#ifdef ASSERT
assert(cfs0->current() == old_current, "non-exclusive use of stream()");
#endif
cfs0->set_current(cfs1.current());
}
bool inline valid_cp_range(int index, int length) { return (index > 0 && index < length); }
inline Symbol* check_symbol_at(constantPoolHandle cp, int index) {
if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8())
return cp->symbol_at(index);
else
return NULL;
}
constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {
ClassFileStream* cfs = stream();
constantPoolHandle nullHandle;
cfs->guarantee_more(3, CHECK_(nullHandle)); // length, first cp tag
u2 length = cfs->get_u2_fast();
guarantee_property(
length >= 1, "Illegal constant pool size %u in class file %s",
length, CHECK_(nullHandle));
ConstantPool* constant_pool = ConstantPool::allocate(_loader_data, length,
CHECK_(nullHandle));
_cp = constant_pool; // save in case of errors
constantPoolHandle cp (THREAD, constant_pool);
parse_constant_pool_entries(length, CHECK_(nullHandle));
int index = 1; // declared outside of loops for portability
for (index = 1; index < length; index++) { // Index 0 is unused
jbyte tag = cp->tag_at(index).value();
switch (tag) {
case JVM_CONSTANT_Class :
ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
break;
case JVM_CONSTANT_Fieldref :
case JVM_CONSTANT_Methodref :
case JVM_CONSTANT_InterfaceMethodref : {
if (!_need_verify) break;
int klass_ref_index = cp->klass_ref_index_at(index);
int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
check_property(valid_klass_reference_at(klass_ref_index),
"Invalid constant pool index %u in class file %s",
klass_ref_index,
CHECK_(nullHandle));
check_property(valid_cp_range(name_and_type_ref_index, length) &&
cp->tag_at(name_and_type_ref_index).is_name_and_type(),
"Invalid constant pool index %u in class file %s",
name_and_type_ref_index,
CHECK_(nullHandle));
break;
}
case JVM_CONSTANT_String :
ShouldNotReachHere(); // Only JVM_CONSTANT_StringIndex should be present
break;
case JVM_CONSTANT_Integer :
break;
case JVM_CONSTANT_Float :
break;
case JVM_CONSTANT_Long :
case JVM_CONSTANT_Double :
index++;
check_property(
(index < length && cp->tag_at(index).is_invalid()),
"Improper constant pool long/double index %u in class file %s",
index, CHECK_(nullHandle));
break;
case JVM_CONSTANT_NameAndType : {
if (!_need_verify) break;
int name_ref_index = cp->name_ref_index_at(index);
int signature_ref_index = cp->signature_ref_index_at(index);
check_property(valid_symbol_at(name_ref_index),
"Invalid constant pool index %u in class file %s",
name_ref_index, CHECK_(nullHandle));
check_property(valid_symbol_at(signature_ref_index),
"Invalid constant pool index %u in class file %s",
signature_ref_index, CHECK_(nullHandle));
break;
}
case JVM_CONSTANT_Utf8 :
break;
case JVM_CONSTANT_UnresolvedClass : // fall-through
case JVM_CONSTANT_UnresolvedClassInError:
ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
break;
case JVM_CONSTANT_ClassIndex :
{
int class_index = cp->klass_index_at(index);
check_property(valid_symbol_at(class_index),
"Invalid constant pool index %u in class file %s",
class_index, CHECK_(nullHandle));
cp->unresolved_klass_at_put(index, cp->symbol_at(class_index));
}
break;
case JVM_CONSTANT_StringIndex :
{
int string_index = cp->string_index_at(index);
check_property(valid_symbol_at(string_index),
"Invalid constant pool index %u in class file %s",
string_index, CHECK_(nullHandle));
Symbol* sym = cp->symbol_at(string_index);
cp->unresolved_string_at_put(index, sym);
}
break;
case JVM_CONSTANT_MethodHandle :
{
int ref_index = cp->method_handle_index_at(index);
check_property(
valid_cp_range(ref_index, length) &&
EnableInvokeDynamic,
"Invalid constant pool index %u in class file %s",
ref_index, CHECK_(nullHandle));
constantTag tag = cp->tag_at(ref_index);
int ref_kind = cp->method_handle_ref_kind_at(index);
switch (ref_kind) {
case JVM_REF_getField:
case JVM_REF_getStatic:
case JVM_REF_putField:
case JVM_REF_putStatic:
check_property(
tag.is_field(),
"Invalid constant pool index %u in class file %s (not a field)",
ref_index, CHECK_(nullHandle));
break;
case JVM_REF_invokeVirtual:
case JVM_REF_newInvokeSpecial:
check_property(
tag.is_method(),
"Invalid constant pool index %u in class file %s (not a method)",
ref_index, CHECK_(nullHandle));
break;
case JVM_REF_invokeStatic:
case JVM_REF_invokeSpecial:
check_property(tag.is_method() ||
((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
"Invalid constant pool index %u in class file %s (not a method)",
ref_index, CHECK_(nullHandle));
break;
case JVM_REF_invokeInterface:
check_property(
tag.is_interface_method(),
"Invalid constant pool index %u in class file %s (not an interface method)",
ref_index, CHECK_(nullHandle));
break;
default:
classfile_parse_error(
"Bad method handle kind at constant pool index %u in class file %s",
index, CHECK_(nullHandle));
}
}
break;
case JVM_CONSTANT_MethodType :
{
int ref_index = cp->method_type_index_at(index);
check_property(valid_symbol_at(ref_index) && EnableInvokeDynamic,
"Invalid constant pool index %u in class file %s",
ref_index, CHECK_(nullHandle));
}
break;
case JVM_CONSTANT_InvokeDynamic :
{
int name_and_type_ref_index = cp->invoke_dynamic_name_and_type_ref_index_at(index);
check_property(valid_cp_range(name_and_type_ref_index, length) &&
cp->tag_at(name_and_type_ref_index).is_name_and_type(),
"Invalid constant pool index %u in class file %s",
name_and_type_ref_index,
CHECK_(nullHandle));
break;
}
default:
fatal(err_msg("bad constant pool tag value %u",
cp->tag_at(index).value()));
ShouldNotReachHere();
break;
} // end of switch
} // end of for
if (_cp_patches != NULL) {
assert(EnableInvokeDynamic, "");
int this_class_index;
{
cfs->guarantee_more(8, CHECK_(nullHandle)); // flags, this_class, super_class, infs_len
u1* mark = cfs->current();
u2 flags = cfs->get_u2_fast();
this_class_index = cfs->get_u2_fast();
cfs->set_current(mark); // revert to mark
}
for (index = 1; index < length; index++) { // Index 0 is unused
if (has_cp_patch_at(index)) {
guarantee_property(index != this_class_index,
"Illegal constant pool patch to self at %d in class file %s",
index, CHECK_(nullHandle));
patch_constant_pool(cp, index, cp_patch_at(index), CHECK_(nullHandle));
}
}
}
if (!_need_verify) {
return cp;
}
for (index = 1; index < length; index++) {
jbyte tag = cp->tag_at(index).value();
switch (tag) {
case JVM_CONSTANT_UnresolvedClass: {
Symbol* class_name = cp->unresolved_klass_at(index);
verify_legal_class_name(class_name, CHECK_(nullHandle));
break;
}
case JVM_CONSTANT_NameAndType: {
if (_need_verify && _major_version >= JAVA_7_VERSION) {
int sig_index = cp->signature_ref_index_at(index);
int name_index = cp->name_ref_index_at(index);
Symbol* name = cp->symbol_at(name_index);
Symbol* sig = cp->symbol_at(sig_index);
guarantee_property(sig->utf8_length() != 0,
"Illegal zero length constant pool entry at %d in class %s",
sig_index, CHECK_(nullHandle));
if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
verify_legal_method_signature(name, sig, CHECK_(nullHandle));
} else {
verify_legal_field_signature(name, sig, CHECK_(nullHandle));
}
}
break;
}
case JVM_CONSTANT_InvokeDynamic:
case JVM_CONSTANT_Fieldref:
case JVM_CONSTANT_Methodref:
case JVM_CONSTANT_InterfaceMethodref: {
int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
int signature_ref_index = cp->signature_ref_index_at(name_and_type_ref_index);
Symbol* name = cp->symbol_at(name_ref_index);
Symbol* signature = cp->symbol_at(signature_ref_index);
if (tag == JVM_CONSTANT_Fieldref) {
verify_legal_field_name(name, CHECK_(nullHandle));
if (_need_verify && _major_version >= JAVA_7_VERSION) {
if (signature->utf8_length() == 0 ||
signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
throwIllegalSignature(
"Field", name, signature, CHECK_(nullHandle));
}
} else {
verify_legal_field_signature(name, signature, CHECK_(nullHandle));
}
} else {
verify_legal_method_name(name, CHECK_(nullHandle));
if (_need_verify && _major_version >= JAVA_7_VERSION) {
if (signature->utf8_length() == 0 ||
signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
throwIllegalSignature(
"Method", name, signature, CHECK_(nullHandle));
}
} else {
verify_legal_method_signature(name, signature, CHECK_(nullHandle));
}
if (tag == JVM_CONSTANT_Methodref) {
assert(name != NULL, "method name in constant pool is null");
unsigned int name_len = name->utf8_length();
if (name_len != 0 && name->byte_at(0) == '<') {
if (name != vmSymbols::object_initializer_name()) {
classfile_parse_error(
"Bad method name at constant pool index %u in class file %s",
name_ref_index, CHECK_(nullHandle));
}
}
}
}
break;
}
case JVM_CONSTANT_MethodHandle: {
int ref_index = cp->method_handle_index_at(index);
int ref_kind = cp->method_handle_ref_kind_at(index);
switch (ref_kind) {
case JVM_REF_invokeVirtual:
case JVM_REF_invokeStatic:
case JVM_REF_invokeSpecial:
case JVM_REF_newInvokeSpecial:
{
int name_and_type_ref_index = cp->name_and_type_ref_index_at(ref_index);
int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
Symbol* name = cp->symbol_at(name_ref_index);
if (ref_kind == JVM_REF_newInvokeSpecial) {
if (name != vmSymbols::object_initializer_name()) {
classfile_parse_error(
"Bad constructor name at constant pool index %u in class file %s",
name_ref_index, CHECK_(nullHandle));
}
} else {
if (name == vmSymbols::object_initializer_name()) {
classfile_parse_error(
"Bad method name at constant pool index %u in class file %s",
name_ref_index, CHECK_(nullHandle));
}
}
}
break;
}
break;
}
case JVM_CONSTANT_MethodType: {
Symbol* no_name = vmSymbols::type_name(); // place holder
Symbol* signature = cp->method_type_signature_at(index);
verify_legal_method_signature(no_name, signature, CHECK_(nullHandle));
break;
}
case JVM_CONSTANT_Utf8: {
assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
}
} // end of switch
} // end of for
return cp;
}
void ClassFileParser::patch_constant_pool(constantPoolHandle cp, int index, Handle patch, TRAPS) {
assert(EnableInvokeDynamic, "");
BasicType patch_type = T_VOID;
switch (cp->tag_at(index).value()) {
case JVM_CONSTANT_UnresolvedClass :
if (java_lang_Class::is_instance(patch())) {
guarantee_property(!java_lang_Class::is_primitive(patch()),
"Illegal class patch at %d in class file %s",
index, CHECK);
cp->klass_at_put(index, java_lang_Class::as_Klass(patch()));
} else {
guarantee_property(java_lang_String::is_instance(patch()),
"Illegal class patch at %d in class file %s",
index, CHECK);
Symbol* name = java_lang_String::as_symbol(patch(), CHECK);
cp->unresolved_klass_at_put(index, name);
}
break;
case JVM_CONSTANT_String :
return;
case JVM_CONSTANT_Integer : patch_type = T_INT; goto patch_prim;
case JVM_CONSTANT_Float : patch_type = T_FLOAT; goto patch_prim;
case JVM_CONSTANT_Long : patch_type = T_LONG; goto patch_prim;
case JVM_CONSTANT_Double : patch_type = T_DOUBLE; goto patch_prim;
patch_prim:
{
jvalue value;
BasicType value_type = java_lang_boxing_object::get_value(patch(), &value);
guarantee_property(value_type == patch_type,
"Illegal primitive patch at %d in class file %s",
index, CHECK);
switch (value_type) {
case T_INT: cp->int_at_put(index, value.i); break;
case T_FLOAT: cp->float_at_put(index, value.f); break;
case T_LONG: cp->long_at_put(index, value.j); break;
case T_DOUBLE: cp->double_at_put(index, value.d); break;
default: assert(false, "");
}
}
break;
default:
guarantee_property(!has_cp_patch_at(index),
"Illegal unexpected patch at %d in class file %s",
index, CHECK);
return;
}
clear_cp_patch_at(index);
}
class NameSigHash: public ResourceObj {
public:
Symbol* _name; // name
Symbol* _sig; // signature
NameSigHash* _next; // Next entry in hash table
};
#define HASH_ROW_SIZE 256
unsigned int hash(Symbol* name, Symbol* sig) {
unsigned int raw_hash = 0;
raw_hash += ((unsigned int)(uintptr_t)name) >> (LogHeapWordSize + 2);
raw_hash += ((unsigned int)(uintptr_t)sig) >> LogHeapWordSize;
return (raw_hash + (unsigned int)(uintptr_t)name) % HASH_ROW_SIZE;
}
void initialize_hashtable(NameSigHash** table) {
memset((void*)table, 0, sizeof(NameSigHash*) * HASH_ROW_SIZE);
}
bool put_after_lookup(Symbol* name, Symbol* sig, NameSigHash** table) {
assert(name != NULL, "name in constant pool is NULL");
int index = hash(name, sig);
NameSigHash* entry = table[index];
while (entry != NULL) {
if (entry->_name == name && entry->_sig == sig) {
return false;
}
entry = entry->_next;
}
entry = new NameSigHash();
entry->_name = name;
entry->_sig = sig;
entry->_next = table[index];
table[index] = entry;
return true;
}
Array<Klass*>* ClassFileParser::parse_interfaces(int length,
Handle protection_domain,
Symbol* class_name,
bool* has_default_methods,
TRAPS) {
if (length == 0) {
_local_interfaces = Universe::the_empty_klass_array();
} else {
ClassFileStream* cfs = stream();
assert(length > 0, "only called for length>0");
_local_interfaces = MetadataFactory::new_array<Klass*>(_loader_data, length, NULL, CHECK_NULL);
int index;
for (index = 0; index < length; index++) {
u2 interface_index = cfs->get_u2(CHECK_NULL);
KlassHandle interf;
check_property(
valid_klass_reference_at(interface_index),
"Interface name has bad constant pool index %u in class file %s",
interface_index, CHECK_NULL);
if (_cp->tag_at(interface_index).is_klass()) {
interf = KlassHandle(THREAD, _cp->resolved_klass_at(interface_index));
} else {
Symbol* unresolved_klass = _cp->klass_name_at(interface_index);
guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,
"Bad interface name in class file %s", CHECK_NULL);
Handle class_loader(THREAD, _loader_data->class_loader());
Klass* k = SystemDictionary::resolve_super_or_fail(class_name,
unresolved_klass, class_loader, protection_domain,
false, CHECK_NULL);
interf = KlassHandle(THREAD, k);
}
if (!interf()->is_interface()) {
THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(), "Implementing class", NULL);
}
if (InstanceKlass::cast(interf())->has_default_methods()) {
}
_local_interfaces->at_put(index, interf());
}
if (!_need_verify || length <= 1) {
return _local_interfaces;
}
ResourceMark rm(THREAD);
NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, NameSigHash*, HASH_ROW_SIZE);
initialize_hashtable(interface_names);
bool dup = false;
Symbol* name = NULL;
{
debug_only(No_Safepoint_Verifier nsv;)
for (index = 0; index < length; index++) {
Klass* k = _local_interfaces->at(index);
name = InstanceKlass::cast(k)->name();
if (!put_after_lookup(name, NULL, interface_names)) {
dup = true;
break;
}
}
}
if (dup) {
classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
name->as_C_string(), CHECK_NULL);
}
}
return _local_interfaces;
}
void ClassFileParser::verify_constantvalue(int constantvalue_index, int signature_index, TRAPS) {
guarantee_property(
(constantvalue_index > 0 &&
constantvalue_index < _cp->length()),
"Bad initial value index %u in ConstantValue attribute in class file %s",
constantvalue_index, CHECK);
constantTag value_type = _cp->tag_at(constantvalue_index);
switch ( _cp->basic_type_for_signature_at(signature_index) ) {
case T_LONG:
guarantee_property(value_type.is_long(), "Inconsistent constant value type in class file %s", CHECK);
break;
case T_FLOAT:
guarantee_property(value_type.is_float(), "Inconsistent constant value type in class file %s", CHECK);
break;
case T_DOUBLE:
guarantee_property(value_type.is_double(), "Inconsistent constant value type in class file %s", CHECK);
break;
case T_BYTE: case T_CHAR: case T_SHORT: case T_BOOLEAN: case T_INT:
guarantee_property(value_type.is_int(), "Inconsistent constant value type in class file %s", CHECK);
break;
case T_OBJECT:
guarantee_property((_cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
&& value_type.is_string()),
"Bad string initial value in class file %s", CHECK);
break;
default:
classfile_parse_error(
"Unable to set initial value %u in class file %s",
constantvalue_index, CHECK);
}
}
void ClassFileParser::parse_field_attributes(u2 attributes_count,
bool is_static, u2 signature_index,
u2* constantvalue_index_addr,
bool* is_synthetic_addr,
u2* generic_signature_index_addr,
ClassFileParser::FieldAnnotationCollector* parsed_annotations,
TRAPS) {
ClassFileStream* cfs = stream();
assert(attributes_count > 0, "length should be greater than 0");
u2 constantvalue_index = 0;
u2 generic_signature_index = 0;
bool is_synthetic = false;
u1* runtime_visible_annotations = NULL;
int runtime_visible_annotations_length = 0;
u1* runtime_invisible_annotations = NULL;
int runtime_invisible_annotations_length = 0;
u1* runtime_visible_type_annotations = NULL;
int runtime_visible_type_annotations_length = 0;
u1* runtime_invisible_type_annotations = NULL;
int runtime_invisible_type_annotations_length = 0;
bool runtime_invisible_type_annotations_exists = false;
while (attributes_count--) {
cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
u2 attribute_name_index = cfs->get_u2_fast();
u4 attribute_length = cfs->get_u4_fast();
check_property(valid_symbol_at(attribute_name_index),
"Invalid field attribute index %u in class file %s",
attribute_name_index,
CHECK);
Symbol* attribute_name = _cp->symbol_at(attribute_name_index);
if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
if (constantvalue_index != 0) {
classfile_parse_error("Duplicate ConstantValue attribute in class file %s", CHECK);
}
check_property(
attribute_length == 2,
"Invalid ConstantValue field attribute length %u in class file %s",
attribute_length, CHECK);
constantvalue_index = cfs->get_u2(CHECK);
if (_need_verify) {
verify_constantvalue(constantvalue_index, signature_index, CHECK);
}
} else if (attribute_name == vmSymbols::tag_synthetic()) {
if (attribute_length != 0) {
classfile_parse_error(
"Invalid Synthetic field attribute length %u in class file %s",
attribute_length, CHECK);
}
is_synthetic = true;
} else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
if (attribute_length != 0) {
classfile_parse_error(
"Invalid Deprecated field attribute length %u in class file %s",
attribute_length, CHECK);
}
} else if (_major_version >= JAVA_1_5_VERSION) {
if (attribute_name == vmSymbols::tag_signature()) {
if (attribute_length != 2) {
classfile_parse_error(
"Wrong size %u for field's Signature attribute in class file %s",
attribute_length, CHECK);
}
generic_signature_index = parse_generic_signature_attribute(CHECK);
} else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
runtime_visible_annotations_length = attribute_length;
runtime_visible_annotations = cfs->get_u1_buffer();
assert(runtime_visible_annotations != NULL, "null visible annotations");
cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
parse_annotations(runtime_visible_annotations,
runtime_visible_annotations_length,
parsed_annotations,
CHECK);
cfs->skip_u1_fast(runtime_visible_annotations_length);
} else if (PreserveAllAnnotations && attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
runtime_invisible_annotations_length = attribute_length;
runtime_invisible_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_annotations != NULL, "null invisible annotations");
cfs->skip_u1(runtime_invisible_annotations_length, CHECK);
} else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
if (runtime_visible_type_annotations != NULL) {
classfile_parse_error(
"Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", CHECK);
}
runtime_visible_type_annotations_length = attribute_length;
runtime_visible_type_annotations = cfs->get_u1_buffer();
assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
} else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
if (runtime_invisible_type_annotations_exists) {
classfile_parse_error(
"Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", CHECK);
} else {
runtime_invisible_type_annotations_exists = true;
}
if (PreserveAllAnnotations) {
runtime_invisible_type_annotations_length = attribute_length;
runtime_invisible_type_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
}
cfs->skip_u1(attribute_length, CHECK);
} else {
cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes
}
} else {
cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes
}
}
AnnotationArray* a = assemble_annotations(runtime_visible_annotations,
runtime_visible_annotations_length,
runtime_invisible_annotations,
runtime_invisible_annotations_length,
CHECK);
parsed_annotations->set_field_annotations(a);
a = assemble_annotations(runtime_visible_type_annotations,
runtime_visible_type_annotations_length,
runtime_invisible_type_annotations,
runtime_invisible_type_annotations_length,
CHECK);
parsed_annotations->set_field_type_annotations(a);
return;
}
enum FieldAllocationType {
STATIC_OOP, // Oops
STATIC_BYTE, // Boolean, Byte, char
STATIC_SHORT, // shorts
STATIC_WORD, // ints
STATIC_DOUBLE, // aligned long or double
NONSTATIC_OOP,
NONSTATIC_BYTE,
NONSTATIC_SHORT,
NONSTATIC_WORD,
NONSTATIC_DOUBLE,
MAX_FIELD_ALLOCATION_TYPE,
BAD_ALLOCATION_TYPE = -1
};
static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
BAD_ALLOCATION_TYPE, // 0
BAD_ALLOCATION_TYPE, // 1
BAD_ALLOCATION_TYPE, // 2
BAD_ALLOCATION_TYPE, // 3
NONSTATIC_BYTE , // T_BOOLEAN = 4,
NONSTATIC_SHORT, // T_CHAR = 5,
NONSTATIC_WORD, // T_FLOAT = 6,
NONSTATIC_DOUBLE, // T_DOUBLE = 7,
NONSTATIC_BYTE, // T_BYTE = 8,
NONSTATIC_SHORT, // T_SHORT = 9,
NONSTATIC_WORD, // T_INT = 10,
NONSTATIC_DOUBLE, // T_LONG = 11,
NONSTATIC_OOP, // T_OBJECT = 12,
NONSTATIC_OOP, // T_ARRAY = 13,
BAD_ALLOCATION_TYPE, // T_VOID = 14,
BAD_ALLOCATION_TYPE, // T_ADDRESS = 15,
BAD_ALLOCATION_TYPE, // T_NARROWOOP = 16,
BAD_ALLOCATION_TYPE, // T_METADATA = 17,
BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
BAD_ALLOCATION_TYPE, // T_CONFLICT = 19,
BAD_ALLOCATION_TYPE, // 0
BAD_ALLOCATION_TYPE, // 1
BAD_ALLOCATION_TYPE, // 2
BAD_ALLOCATION_TYPE, // 3
STATIC_BYTE , // T_BOOLEAN = 4,
STATIC_SHORT, // T_CHAR = 5,
STATIC_WORD, // T_FLOAT = 6,
STATIC_DOUBLE, // T_DOUBLE = 7,
STATIC_BYTE, // T_BYTE = 8,
STATIC_SHORT, // T_SHORT = 9,
STATIC_WORD, // T_INT = 10,
STATIC_DOUBLE, // T_LONG = 11,
STATIC_OOP, // T_OBJECT = 12,
STATIC_OOP, // T_ARRAY = 13,
BAD_ALLOCATION_TYPE, // T_VOID = 14,
BAD_ALLOCATION_TYPE, // T_ADDRESS = 15,
BAD_ALLOCATION_TYPE, // T_NARROWOOP = 16,
BAD_ALLOCATION_TYPE, // T_METADATA = 17,
BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
BAD_ALLOCATION_TYPE, // T_CONFLICT = 19,
};
static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
assert(result != BAD_ALLOCATION_TYPE, "bad type");
return result;
}
class FieldAllocationCount: public ResourceObj {
public:
u2 count[MAX_FIELD_ALLOCATION_TYPE];
FieldAllocationCount() {
for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
count[i] = 0;
}
}
FieldAllocationType update(bool is_static, BasicType type) {
FieldAllocationType atype = basic_type_to_atype(is_static, type);
assert(count[atype] < 0xFFFF, "More than 65535 fields");
count[atype]++;
return atype;
}
};
Array<u2>* ClassFileParser::parse_fields(Symbol* class_name,
bool is_interface,
FieldAllocationCount *fac,
u2* java_fields_count_ptr, TRAPS) {
ClassFileStream* cfs = stream();
cfs->guarantee_more(2, CHECK_NULL); // length
u2 length = cfs->get_u2_fast();
int num_injected = 0;
InjectedField* injected = JavaClasses::get_injected(class_name, &num_injected);
int total_fields = length + num_injected;
ResourceMark rm(THREAD);
u2* fa = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2, total_fields * (FieldInfo::field_slots + 1));
int generic_signature_slot = total_fields * FieldInfo::field_slots;
int num_generic_signature = 0;
for (int n = 0; n < length; n++) {
cfs->guarantee_more(8, CHECK_NULL); // access_flags, name_index, descriptor_index, attributes_count
AccessFlags access_flags;
jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
verify_legal_field_modifiers(flags, is_interface, CHECK_NULL);
access_flags.set_flags(flags);
u2 name_index = cfs->get_u2_fast();
int cp_size = _cp->length();
check_property(valid_symbol_at(name_index),
"Invalid constant pool index %u for field name in class file %s",
name_index,
CHECK_NULL);
Symbol* name = _cp->symbol_at(name_index);
verify_legal_field_name(name, CHECK_NULL);
u2 signature_index = cfs->get_u2_fast();
check_property(valid_symbol_at(signature_index),
"Invalid constant pool index %u for field signature in class file %s",
signature_index, CHECK_NULL);
Symbol* sig = _cp->symbol_at(signature_index);
verify_legal_field_signature(name, sig, CHECK_NULL);
u2 constantvalue_index = 0;
bool is_synthetic = false;
u2 generic_signature_index = 0;
bool is_static = access_flags.is_static();
FieldAnnotationCollector parsed_annotations(_loader_data);
u2 attributes_count = cfs->get_u2_fast();
if (attributes_count > 0) {
parse_field_attributes(attributes_count, is_static, signature_index,
&constantvalue_index, &is_synthetic,
&generic_signature_index, &parsed_annotations,
CHECK_NULL);
if (parsed_annotations.field_annotations() != NULL) {
if (_fields_annotations == NULL) {
_fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
_loader_data, length, NULL,
CHECK_NULL);
}
_fields_annotations->at_put(n, parsed_annotations.field_annotations());
parsed_annotations.set_field_annotations(NULL);
}
if (parsed_annotations.field_type_annotations() != NULL) {
if (_fields_type_annotations == NULL) {
_fields_type_annotations = MetadataFactory::new_array<AnnotationArray*>(
_loader_data, length, NULL,
CHECK_NULL);
}
_fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
parsed_annotations.set_field_type_annotations(NULL);
}
if (is_synthetic) {
access_flags.set_is_synthetic();
}
if (generic_signature_index != 0) {
access_flags.set_field_has_generic_signature();
fa[generic_signature_slot] = generic_signature_index;
generic_signature_slot ++;
num_generic_signature ++;
}
}
FieldInfo* field = FieldInfo::from_field_array(fa, n);
field->initialize(access_flags.as_short(),
name_index,
signature_index,
constantvalue_index);
BasicType type = _cp->basic_type_for_signature_at(signature_index);
FieldAllocationType atype = fac->update(is_static, type);
field->set_allocation_type(atype);
if (parsed_annotations.has_any_annotations())
parsed_annotations.apply_to(field);
}
int index = length;
if (num_injected != 0) {
for (int n = 0; n < num_injected; n++) {
if (injected[n].may_be_java) {
Symbol* name = injected[n].name();
Symbol* signature = injected[n].signature();
bool duplicate = false;
for (int i = 0; i < length; i++) {
FieldInfo* f = FieldInfo::from_field_array(fa, i);
if (name == _cp->symbol_at(f->name_index()) &&
signature == _cp->symbol_at(f->signature_index())) {
duplicate = true;
break;
}
}
if (duplicate) {
continue;
}
}
FieldInfo* field = FieldInfo::from_field_array(fa, index);
field->initialize(JVM_ACC_FIELD_INTERNAL,
injected[n].name_index,
injected[n].signature_index,
0);
BasicType type = FieldType::basic_type(injected[n].signature());
FieldAllocationType atype = fac->update(false, type);
field->set_allocation_type(atype);
index++;
}
}
Array<u2>* fields = MetadataFactory::new_array<u2>(
_loader_data, index * FieldInfo::field_slots + num_generic_signature,
CHECK_NULL);
_fields = fields; // save in case of error
{
int i = 0;
for (; i < index * FieldInfo::field_slots; i++) {
fields->at_put(i, fa[i]);
}
for (int j = total_fields * FieldInfo::field_slots;
j < generic_signature_slot; j++) {
fields->at_put(i++, fa[j]);
}
assert(i == fields->length(), "");
}
if (_need_verify && length > 1) {
ResourceMark rm(THREAD);
NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, NameSigHash*, HASH_ROW_SIZE);
initialize_hashtable(names_and_sigs);
bool dup = false;
Symbol* name = NULL;
Symbol* sig = NULL;
{
debug_only(No_Safepoint_Verifier nsv;)
for (AllFieldStream fs(fields, _cp); !fs.done(); fs.next()) {
name = fs.name();
sig = fs.signature();
if (!put_after_lookup(name, sig, names_and_sigs)) {
dup = true;
break;
}
}
}
if (dup) {
classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);
}
}
return fields;
}
static void copy_u2_with_conversion(u2* dest, u2* src, int length) {
while (length-- > 0) {
}
}
u2* ClassFileParser::parse_exception_table(u4 code_length,
u4 exception_table_length,
TRAPS) {
ClassFileStream* cfs = stream();
u2* exception_table_start = cfs->get_u2_buffer();
assert(exception_table_start != NULL, "null exception table");
cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc, end_pc, handler_pc, catch_type_index
if (_need_verify) {
for (unsigned int i = 0; i < exception_table_length; i++) {
u2 start_pc = cfs->get_u2_fast();
u2 end_pc = cfs->get_u2_fast();
u2 handler_pc = cfs->get_u2_fast();
u2 catch_type_index = cfs->get_u2_fast();
guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
"Illegal exception table range in class file %s",
CHECK_NULL);
guarantee_property(handler_pc < code_length,
"Illegal exception table handler in class file %s",
CHECK_NULL);
if (catch_type_index != 0) {
guarantee_property(valid_klass_reference_at(catch_type_index),
"Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
}
}
} else {
cfs->skip_u2_fast(exception_table_length * 4);
}
return exception_table_start;
}
void ClassFileParser::parse_linenumber_table(
u4 code_attribute_length, u4 code_length,
CompressedLineNumberWriteStream** write_stream, TRAPS) {
ClassFileStream* cfs = stream();
unsigned int num_entries = cfs->get_u2(CHECK);
unsigned int length_in_bytes = num_entries * (sizeof(u2) + sizeof(u2));
check_property(
code_attribute_length == sizeof(u2) + length_in_bytes,
"LineNumberTable attribute has wrong length in class file %s", CHECK);
cfs->guarantee_more(length_in_bytes, CHECK);
if ((*write_stream) == NULL) {
if (length_in_bytes > fixed_buffer_size) {
(*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
} else {
(*write_stream) = new CompressedLineNumberWriteStream(
linenumbertable_buffer, fixed_buffer_size);
}
}
while (num_entries-- > 0) {
u2 bci = cfs->get_u2_fast(); // start_pc
u2 line = cfs->get_u2_fast(); // line_number
guarantee_property(bci < code_length,
"Invalid pc in LineNumberTable in class file %s", CHECK);
(*write_stream)->write_pair(bci, line);
}
}
class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {
public:
u2 start_bci;
u2 length;
u2 name_cp_index;
u2 descriptor_cp_index;
u2 slot;
};
class LVT_Hash: public CHeapObj<mtClass> {
public:
LocalVariableTableElement *_elem; // element
LVT_Hash* _next; // Next entry in hash table
};
unsigned int hash(LocalVariableTableElement *elem) {
unsigned int raw_hash = elem->start_bci;
raw_hash = elem->length + raw_hash * 37;
raw_hash = elem->name_cp_index + raw_hash * 37;
raw_hash = elem->slot + raw_hash * 37;
return raw_hash % HASH_ROW_SIZE;
}
void initialize_hashtable(LVT_Hash** table) {
for (int i = 0; i < HASH_ROW_SIZE; i++) {
table[i] = NULL;
}
}
void clear_hashtable(LVT_Hash** table) {
for (int i = 0; i < HASH_ROW_SIZE; i++) {
LVT_Hash* current = table[i];
LVT_Hash* next;
while (current != NULL) {
next = current->_next;
current->_next = NULL;
delete(current);
current = next;
}
table[i] = NULL;
}
}
LVT_Hash* LVT_lookup(LocalVariableTableElement *elem, int index, LVT_Hash** table) {
LVT_Hash* entry = table[index];
while (entry != NULL) {
if (elem->start_bci == entry->_elem->start_bci
&& elem->length == entry->_elem->length
&& elem->name_cp_index == entry->_elem->name_cp_index
&& elem->slot == entry->_elem->slot
) {
return entry;
}
entry = entry->_next;
}
return NULL;
}
bool LVT_put_after_lookup(LocalVariableTableElement *elem, LVT_Hash** table) {
int index = hash(elem);
LVT_Hash* entry = LVT_lookup(elem, index, table);
if (entry != NULL) {
return false;
}
if ((entry = new LVT_Hash()) == NULL) {
return false;
}
entry->_elem = elem;
entry->_next = table[index];
table[index] = entry;
return true;
}
void copy_lvt_element(Classfile_LVT_Element *src, LocalVariableTableElement *lvt) {
lvt->start_bci = Bytes::get_Java_u2((u1*) &src->start_bci);
lvt->length = Bytes::get_Java_u2((u1*) &src->length);
lvt->name_cp_index = Bytes::get_Java_u2((u1*) &src->name_cp_index);
lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
lvt->signature_cp_index = 0;
lvt->slot = Bytes::get_Java_u2((u1*) &src->slot);
}
u2* ClassFileParser::parse_localvariable_table(u4 code_length,
u2 max_locals,
u4 code_attribute_length,
u2* localvariable_table_length,
bool isLVTT,
TRAPS) {
ClassFileStream* cfs = stream();
const char * tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
unsigned int size = (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
if (_need_verify) {
guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
"%s has wrong length in class file %s", tbl_name, CHECK_NULL);
}
u2* localvariable_table_start = cfs->get_u2_buffer();
assert(localvariable_table_start != NULL, "null local variable table");
if (!_need_verify) {
cfs->skip_u2_fast(size);
} else {
cfs->guarantee_more(size * 2, CHECK_NULL);
for(int i = 0; i < (*localvariable_table_length); i++) {
u2 start_pc = cfs->get_u2_fast();
u2 length = cfs->get_u2_fast();
u2 name_index = cfs->get_u2_fast();
u2 descriptor_index = cfs->get_u2_fast();
u2 index = cfs->get_u2_fast();
u4 end_pc = (u4)start_pc + (u4)length;
if (start_pc >= code_length) {
classfile_parse_error(
"Invalid start_pc %u in %s in class file %s",
start_pc, tbl_name, CHECK_NULL);
}
if (end_pc > code_length) {
classfile_parse_error(
"Invalid length %u in %s in class file %s",
length, tbl_name, CHECK_NULL);
}
int cp_size = _cp->length();
guarantee_property(valid_symbol_at(name_index),
"Name index %u in %s has bad constant type in class file %s",
name_index, tbl_name, CHECK_NULL);
guarantee_property(valid_symbol_at(descriptor_index),
"Signature index %u in %s has bad constant type in class file %s",
descriptor_index, tbl_name, CHECK_NULL);
Symbol* name = _cp->symbol_at(name_index);
Symbol* sig = _cp->symbol_at(descriptor_index);
verify_legal_field_name(name, CHECK_NULL);
u2 extra_slot = 0;
if (!isLVTT) {
verify_legal_field_signature(name, sig, CHECK_NULL);
if (sig == vmSymbols::type_signature(T_DOUBLE) ||
sig == vmSymbols::type_signature(T_LONG)) {
extra_slot = 1;
}
}
guarantee_property((index + extra_slot) < max_locals,
"Invalid index %u in %s in class file %s",
index, tbl_name, CHECK_NULL);
}
}
return localvariable_table_start;
}
void ClassFileParser::parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,
u1* u1_array, u2* u2_array, TRAPS) {
ClassFileStream* cfs = stream();
u2 index = 0; // index in the array with long/double occupying two slots
u4 i1 = *u1_index;
u4 i2 = *u2_index + 1;
for(int i = 0; i < array_length; i++) {
u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);
index++;
if (tag == ITEM_Long || tag == ITEM_Double) {
index++;
} else if (tag == ITEM_Object) {
u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
guarantee_property(valid_klass_reference_at(class_index),
"Bad class index %u in StackMap in class file %s",
class_index, CHECK);
} else if (tag == ITEM_Uninitialized) {
u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);
guarantee_property(
offset < code_length,
"Bad uninitialized type offset %u in StackMap in class file %s",
offset, CHECK);
} else {
guarantee_property(
tag <= (u1)ITEM_Uninitialized,
"Unknown variable type %u in StackMap in class file %s",
tag, CHECK);
}
}
u2_array[*u2_index] = index;
}
u1* ClassFileParser::parse_stackmap_table(
u4 code_attribute_length, TRAPS) {
if (code_attribute_length == 0)
return NULL;
ClassFileStream* cfs = stream();
u1* stackmap_table_start = cfs->get_u1_buffer();
assert(stackmap_table_start != NULL, "null stackmap table");
stream()->skip_u1(code_attribute_length, CHECK_NULL);
if (!_need_verify && !DumpSharedSpaces) {
return NULL;
}
return stackmap_table_start;
}
u2* ClassFileParser::parse_checked_exceptions(u2* checked_exceptions_length,
u4 method_attribute_length,
TRAPS) {
ClassFileStream* cfs = stream();
cfs->guarantee_more(2, CHECK_NULL); // checked_exceptions_length
unsigned int size = (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
u2* checked_exceptions_start = cfs->get_u2_buffer();
assert(checked_exceptions_start != NULL, "null checked exceptions");
if (!_need_verify) {
cfs->skip_u2_fast(size);
} else {
u2 checked_exception;
u2 len = *checked_exceptions_length;
cfs->guarantee_more(2 * len, CHECK_NULL);
for (int i = 0; i < len; i++) {
checked_exception = cfs->get_u2_fast();
check_property(
valid_klass_reference_at(checked_exception),
"Exception name has bad type at constant pool %u in class file %s",
checked_exception, CHECK_NULL);
}
}
if (_need_verify) {
guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
sizeof(u2) * size),
"Exceptions attribute has wrong length in class file %s", CHECK_NULL);
}
return checked_exceptions_start;
}
void ClassFileParser::throwIllegalSignature(
const char* type, Symbol* name, Symbol* sig, TRAPS) {
ResourceMark rm(THREAD);
Exceptions::fthrow(THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"%s \"%s\" in class %s has illegal signature \"%s\"", type,
name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
}
int ClassFileParser::skip_annotation(u1* buffer, int limit, int index) {
index += 2; // skip atype
if ((index += 2) >= limit) return limit; // read nmem
int nmem = Bytes::get_Java_u2(buffer+index-2);
while (--nmem >= 0 && index < limit) {
index += 2; // skip member
index = skip_annotation_value(buffer, limit, index);
}
return index;
}
#define SAFE_ADD(index, limit, val) \
if (index >= limit - val) return limit; \
index += val;
int ClassFileParser::skip_annotation_value(u1* buffer, int limit, int index) {
SAFE_ADD(index, limit, 1); // read tag
u1 tag = buffer[index-1];
switch (tag) {
case 'B': case 'C': case 'I': case 'S': case 'Z':
case 'D': case 'F': case 'J': case 'c': case 's':
SAFE_ADD(index, limit, 2); // skip con or s_con
break;
case 'e':
SAFE_ADD(index, limit, 4); // skip e_class, e_name
break;
case '[':
{
SAFE_ADD(index, limit, 2); // read nval
int nval = Bytes::get_Java_u2(buffer+index-2);
while (--nval >= 0 && index < limit) {
index = skip_annotation_value(buffer, limit, index);
}
}
break;
case '@':
index = skip_annotation(buffer, limit, index);
break;
default:
assert(false, "annotation tag");
return limit; // bad tag byte
}
return index;
}
void ClassFileParser::parse_annotations(u1* buffer, int limit,
ClassFileParser::AnnotationCollector* coll,
TRAPS) {
int index = 2;
if (index >= limit) return; // read nann
int nann = Bytes::get_Java_u2(buffer+index-2);
enum { // initial annotation layout
atype_off = 0, // utf8 such as 'Ljava/lang/annotation/Retention;'
count_off = 2, // u2 such as 1 (one value)
member_off = 4, // utf8 such as 'value'
tag_off = 6, // u1 such as 'c' (type) or 'e' (enum)
e_tag_val = 'e',
e_type_off = 7, // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
e_con_off = 9, // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
e_size = 11, // end of 'e' annotation
c_tag_val = 'c', // payload is type
c_con_off = 7, // utf8 payload, such as 'I'
c_size = 9, // end of 'c' annotation
s_tag_val = 's', // payload is String
s_con_off = 7, // utf8 payload, such as 'Ljava/lang/String;'
s_size = 9,
min_size = 6 // smallest possible size (zero members)
};
while ((--nann) >= 0 && (index-2 <= limit - min_size)) {
int index0 = index;
index = skip_annotation(buffer, limit, index);
u1* abase = buffer + index0;
int atype = Bytes::get_Java_u2(abase + atype_off);
int count = Bytes::get_Java_u2(abase + count_off);
Symbol* aname = check_symbol_at(_cp, atype);
if (aname == NULL) break; // invalid annotation name
Symbol* member = NULL;
if (count >= 1) {
int member_index = Bytes::get_Java_u2(abase + member_off);
member = check_symbol_at(_cp, member_index);
if (member == NULL) break; // invalid member name
}
AnnotationCollector::ID id = coll->annotation_index(_loader_data, aname);
if (id == AnnotationCollector::_unknown) continue;
coll->set_annotation(id);
if (id == AnnotationCollector::_sun_misc_Contended) {
u2 group_index = 0; // default contended group
if (count == 1
&& s_size == (index - index0) // match size
&& s_tag_val == *(abase + tag_off)
&& member == vmSymbols::value_name()) {
group_index = Bytes::get_Java_u2(abase + s_con_off);
if (_cp->symbol_at(group_index)->utf8_length() == 0) {
group_index = 0; // default contended group
}
}
coll->set_contended_group(group_index);
}
}
}
ClassFileParser::AnnotationCollector::ID
ClassFileParser::AnnotationCollector::annotation_index(ClassLoaderData* loader_data,
Symbol* name) {
vmSymbols::SID sid = vmSymbols::find_sid(name);
const bool privileged = loader_data->is_the_null_class_loader_data() ||
loader_data->is_ext_class_loader_data() ||
loader_data->is_anonymous();
switch (sid) {
case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_reflect_CallerSensitive_signature):
if (_location != _in_method) break; // only allow for methods
if (!privileged) break; // only allow in privileged code
return _method_CallerSensitive;
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_ForceInline_signature):
if (_location != _in_method) break; // only allow for methods
if (!privileged) break; // only allow in privileged code
return _method_ForceInline;
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_DontInline_signature):
if (_location != _in_method) break; // only allow for methods
if (!privileged) break; // only allow in privileged code
return _method_DontInline;
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature):
if (_location != _in_method) break; // only allow for methods
if (!privileged) break; // only allow in privileged code
return _method_InjectedProfile;
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature):
if (_location != _in_method) break; // only allow for methods
if (!privileged) break; // only allow in privileged code
return _method_LambdaForm_Compiled;
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Hidden_signature):
if (_location != _in_method) break; // only allow for methods
if (!privileged) break; // only allow in privileged code
return _method_LambdaForm_Hidden;
case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_Stable_signature):
if (_location != _in_field) break; // only allow for fields
if (!privileged) break; // only allow in privileged code
return _field_Stable;
case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_misc_Contended_signature):
if (_location != _in_field && _location != _in_class) break; // only allow for fields and classes
if (!EnableContended || (RestrictContended && !privileged)) break; // honor privileges
return _sun_misc_Contended;
default: break;
}
return AnnotationCollector::_unknown;
}
void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
if (is_contended())
f->set_contended_group(contended_group());
if (is_stable())
f->set_stable(true);
}
ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
}
void ClassFileParser::MethodAnnotationCollector::apply_to(methodHandle m) {
if (has_annotation(_method_CallerSensitive))
m->set_caller_sensitive(true);
if (has_annotation(_method_ForceInline))
m->set_force_inline(true);
if (has_annotation(_method_DontInline))
m->set_dont_inline(true);
if (has_annotation(_method_InjectedProfile))
m->set_has_injected_profile(true);
if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
if (has_annotation(_method_LambdaForm_Hidden))
m->set_hidden(true);
}
void ClassFileParser::ClassAnnotationCollector::apply_to(instanceKlassHandle k) {
k->set_is_contended(is_contended());
}
#define MAX_ARGS_SIZE 255
#define MAX_CODE_SIZE 65535
#define INITIAL_MAX_LVT_NUMBER 256
void ClassFileParser::copy_localvariable_table(ConstMethod* cm,
int lvt_cnt,
u2* localvariable_table_length,
u2** localvariable_table_start,
int lvtt_cnt,
u2* localvariable_type_table_length,
u2** localvariable_type_table_start,
TRAPS) {
LVT_Hash** lvt_Hash = NEW_RESOURCE_ARRAY(LVT_Hash*, HASH_ROW_SIZE);
initialize_hashtable(lvt_Hash);
Classfile_LVT_Element* cf_lvt;
LocalVariableTableElement* lvt = cm->localvariable_table_start();
for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
copy_lvt_element(&cf_lvt[idx], lvt);
if (LVT_put_after_lookup(lvt, lvt_Hash) == false
&& _need_verify
&& _major_version >= JAVA_1_5_VERSION) {
clear_hashtable(lvt_Hash);
classfile_parse_error("Duplicated LocalVariableTable attribute "
"entry for '%s' in class file %s",
_cp->symbol_at(lvt->name_cp_index)->as_utf8(),
CHECK);
}
}
}
Classfile_LVT_Element* cf_lvtt;
LocalVariableTableElement lvtt_elem;
for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
int index = hash(&lvtt_elem);
LVT_Hash* entry = LVT_lookup(&lvtt_elem, index, lvt_Hash);
if (entry == NULL) {
if (_need_verify) {
clear_hashtable(lvt_Hash);
classfile_parse_error("LVTT entry for '%s' in class file %s "
"does not match any LVT entry",
_cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
CHECK);
}
} else if (entry->_elem->signature_cp_index != 0 && _need_verify) {
clear_hashtable(lvt_Hash);
classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
"entry for '%s' in class file %s",
_cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
CHECK);
} else {
entry->_elem->signature_cp_index = lvtt_elem.descriptor_cp_index;
}
}
}
clear_hashtable(lvt_Hash);
}
void ClassFileParser::copy_method_annotations(ConstMethod* cm,
u1* runtime_visible_annotations,
int runtime_visible_annotations_length,
u1* runtime_invisible_annotations,
int runtime_invisible_annotations_length,
u1* runtime_visible_parameter_annotations,
int runtime_visible_parameter_annotations_length,
u1* runtime_invisible_parameter_annotations,
int runtime_invisible_parameter_annotations_length,
u1* runtime_visible_type_annotations,
int runtime_visible_type_annotations_length,
u1* runtime_invisible_type_annotations,
int runtime_invisible_type_annotations_length,
u1* annotation_default,
int annotation_default_length,
TRAPS) {
AnnotationArray* a;
if (runtime_visible_annotations_length +
runtime_invisible_annotations_length > 0) {
a = assemble_annotations(runtime_visible_annotations,
runtime_visible_annotations_length,
runtime_invisible_annotations,
runtime_invisible_annotations_length,
CHECK);
cm->set_method_annotations(a);
}
if (runtime_visible_parameter_annotations_length +
runtime_invisible_parameter_annotations_length > 0) {
a = assemble_annotations(runtime_visible_parameter_annotations,
runtime_visible_parameter_annotations_length,
runtime_invisible_parameter_annotations,
runtime_invisible_parameter_annotations_length,
CHECK);
cm->set_parameter_annotations(a);
}
if (annotation_default_length > 0) {
a = assemble_annotations(annotation_default,
annotation_default_length,
NULL,
0,
CHECK);
cm->set_default_annotations(a);
}
if (runtime_visible_type_annotations_length +
runtime_invisible_type_annotations_length > 0) {
a = assemble_annotations(runtime_visible_type_annotations,
runtime_visible_type_annotations_length,
runtime_invisible_type_annotations,
runtime_invisible_type_annotations_length,
CHECK);
cm->set_type_annotations(a);
}
}
methodHandle ClassFileParser::parse_method(bool is_interface,
AccessFlags *promoted_flags,
TRAPS) {
ClassFileStream* cfs = stream();
methodHandle nullHandle;
ResourceMark rm(THREAD);
cfs->guarantee_more(8, CHECK_(nullHandle)); // access_flags, name_index, descriptor_index, attributes_count
int flags = cfs->get_u2_fast();
u2 name_index = cfs->get_u2_fast();
int cp_size = _cp->length();
check_property(
valid_symbol_at(name_index),
"Illegal constant pool index %u for method name in class file %s",
name_index, CHECK_(nullHandle));
Symbol* name = _cp->symbol_at(name_index);
verify_legal_method_name(name, CHECK_(nullHandle));
u2 signature_index = cfs->get_u2_fast();
guarantee_property(
valid_symbol_at(signature_index),
"Illegal constant pool index %u for method signature in class file %s",
signature_index, CHECK_(nullHandle));
Symbol* signature = _cp->symbol_at(signature_index);
AccessFlags access_flags;
if (name == vmSymbols::class_initializer_name()) {
if (_major_version < 51) { // backward compatibility
flags = JVM_ACC_STATIC;
} else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;
}
} else {
verify_legal_method_modifiers(flags, is_interface, name, CHECK_(nullHandle));
}
int args_size = -1; // only used when _need_verify is true
if (_need_verify) {
args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
verify_legal_method_signature(name, signature, CHECK_(nullHandle));
if (args_size > MAX_ARGS_SIZE) {
classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_(nullHandle));
}
}
access_flags.set_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
u2 max_stack = 0;
u2 max_locals = 0;
u4 code_length = 0;
u1* code_start = 0;
u2 exception_table_length = 0;
u2* exception_table_start = NULL;
Array<int>* exception_handlers = Universe::the_empty_int_array();
u2 checked_exceptions_length = 0;
u2* checked_exceptions_start = NULL;
CompressedLineNumberWriteStream* linenumber_table = NULL;
int linenumber_table_length = 0;
int total_lvt_length = 0;
u2 lvt_cnt = 0;
u2 lvtt_cnt = 0;
bool lvt_allocated = false;
u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
u2* localvariable_table_length;
u2** localvariable_table_start;
u2* localvariable_type_table_length;
u2** localvariable_type_table_start;
u2 method_parameters_length = 0;
u1* method_parameters_data = NULL;
bool method_parameters_seen = false;
bool parsed_code_attribute = false;
bool parsed_checked_exceptions_attribute = false;
bool parsed_stackmap_attribute = false;
u1* stackmap_data = NULL;
int stackmap_data_length = 0;
u2 generic_signature_index = 0;
MethodAnnotationCollector parsed_annotations;
u1* runtime_visible_annotations = NULL;
int runtime_visible_annotations_length = 0;
u1* runtime_invisible_annotations = NULL;
int runtime_invisible_annotations_length = 0;
u1* runtime_visible_parameter_annotations = NULL;
int runtime_visible_parameter_annotations_length = 0;
u1* runtime_invisible_parameter_annotations = NULL;
int runtime_invisible_parameter_annotations_length = 0;
u1* runtime_visible_type_annotations = NULL;
int runtime_visible_type_annotations_length = 0;
u1* runtime_invisible_type_annotations = NULL;
int runtime_invisible_type_annotations_length = 0;
bool runtime_invisible_type_annotations_exists = false;
u1* annotation_default = NULL;
int annotation_default_length = 0;
u2 method_attributes_count = cfs->get_u2_fast();
while (method_attributes_count--) {
cfs->guarantee_more(6, CHECK_(nullHandle)); // method_attribute_name_index, method_attribute_length
u2 method_attribute_name_index = cfs->get_u2_fast();
u4 method_attribute_length = cfs->get_u4_fast();
check_property(
valid_symbol_at(method_attribute_name_index),
"Invalid method attribute name index %u in class file %s",
method_attribute_name_index, CHECK_(nullHandle));
Symbol* method_attribute_name = _cp->symbol_at(method_attribute_name_index);
if (method_attribute_name == vmSymbols::tag_code()) {
if (_need_verify) {
guarantee_property(
!access_flags.is_native() && !access_flags.is_abstract(),
"Code attribute in native or abstract methods in class file %s",
CHECK_(nullHandle));
}
if (parsed_code_attribute) {
classfile_parse_error("Multiple Code attributes in class file %s", CHECK_(nullHandle));
}
parsed_code_attribute = true;
if (_major_version == 45 && _minor_version <= 2) {
cfs->guarantee_more(4, CHECK_(nullHandle));
max_stack = cfs->get_u1_fast();
max_locals = cfs->get_u1_fast();
code_length = cfs->get_u2_fast();
} else {
cfs->guarantee_more(8, CHECK_(nullHandle));
max_stack = cfs->get_u2_fast();
max_locals = cfs->get_u2_fast();
code_length = cfs->get_u4_fast();
}
if (_need_verify) {
guarantee_property(args_size <= max_locals,
"Arguments can't fit into locals in class file %s", CHECK_(nullHandle));
guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
"Invalid method Code length %u in class file %s",
code_length, CHECK_(nullHandle));
}
code_start = cfs->get_u1_buffer();
assert(code_start != NULL, "null code start");
cfs->guarantee_more(code_length, CHECK_(nullHandle));
cfs->skip_u1_fast(code_length);
cfs->guarantee_more(2, CHECK_(nullHandle)); // exception_table_length
exception_table_length = cfs->get_u2_fast();
if (exception_table_length > 0) {
exception_table_start =
parse_exception_table(code_length, exception_table_length, CHECK_(nullHandle));
}
cfs->guarantee_more(2, CHECK_(nullHandle)); // code_attributes_count
u2 code_attributes_count = cfs->get_u2_fast();
unsigned int calculated_attribute_length = 0;
if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
calculated_attribute_length =
sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
} else {
calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
}
calculated_attribute_length +=
code_length +
sizeof(exception_table_length) +
sizeof(code_attributes_count) +
exception_table_length *
( sizeof(u2) + // start_pc
sizeof(u2) + // end_pc
sizeof(u2) + // handler_pc
sizeof(u2) ); // catch_type_index
while (code_attributes_count--) {
cfs->guarantee_more(6, CHECK_(nullHandle)); // code_attribute_name_index, code_attribute_length
u2 code_attribute_name_index = cfs->get_u2_fast();
u4 code_attribute_length = cfs->get_u4_fast();
calculated_attribute_length += code_attribute_length +
sizeof(code_attribute_name_index) +
sizeof(code_attribute_length);
check_property(valid_symbol_at(code_attribute_name_index),
"Invalid code attribute name index %u in class file %s",
code_attribute_name_index,
CHECK_(nullHandle));
if (LoadLineNumberTables &&
_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
parse_linenumber_table(code_attribute_length, code_length,
&linenumber_table, CHECK_(nullHandle));
} else if (LoadLocalVariableTables &&
_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
if (!lvt_allocated) {
localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2, INITIAL_MAX_LVT_NUMBER);
localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2, INITIAL_MAX_LVT_NUMBER);
localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
lvt_allocated = true;
}
if (lvt_cnt == max_lvt_cnt) {
max_lvt_cnt <<= 1;
localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
localvariable_table_start = REALLOC_RESOURCE_ARRAY(u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
}
localvariable_table_start[lvt_cnt] =
parse_localvariable_table(code_length,
max_locals,
code_attribute_length,
&localvariable_table_length[lvt_cnt],
false, // is not LVTT
CHECK_(nullHandle));
total_lvt_length += localvariable_table_length[lvt_cnt];
lvt_cnt++;
} else if (LoadLocalVariableTypeTables &&
_major_version >= JAVA_1_5_VERSION &&
_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
if (!lvt_allocated) {
localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2, INITIAL_MAX_LVT_NUMBER);
localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2, INITIAL_MAX_LVT_NUMBER);
localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
lvt_allocated = true;
}
if (lvtt_cnt == max_lvtt_cnt) {
max_lvtt_cnt <<= 1;
localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
localvariable_type_table_start = REALLOC_RESOURCE_ARRAY(u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
}
localvariable_type_table_start[lvtt_cnt] =
parse_localvariable_table(code_length,
max_locals,
code_attribute_length,
&localvariable_type_table_length[lvtt_cnt],
true, // is LVTT
CHECK_(nullHandle));
lvtt_cnt++;
} else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
if (parsed_stackmap_attribute) {
classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_(nullHandle));
}
stackmap_data = parse_stackmap_table(code_attribute_length, CHECK_(nullHandle));
stackmap_data_length = code_attribute_length;
parsed_stackmap_attribute = true;
} else {
cfs->skip_u1(code_attribute_length, CHECK_(nullHandle));
}
}
if (_need_verify) {
guarantee_property(method_attribute_length == calculated_attribute_length,
"Code segment has wrong length in class file %s", CHECK_(nullHandle));
}
} else if (method_attribute_name == vmSymbols::tag_exceptions()) {
if (parsed_checked_exceptions_attribute) {
classfile_parse_error("Multiple Exceptions attributes in class file %s", CHECK_(nullHandle));
}
parsed_checked_exceptions_attribute = true;
checked_exceptions_start =
parse_checked_exceptions(&checked_exceptions_length,
method_attribute_length,
CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
if (method_parameters_seen) {
classfile_parse_error("Multiple MethodParameters attributes in class file %s", CHECK_(nullHandle));
}
method_parameters_seen = true;
method_parameters_length = cfs->get_u1_fast();
if (method_attribute_length != (method_parameters_length * 4u) + 1u) {
classfile_parse_error(
"Invalid MethodParameters method attribute length %u in class file",
method_attribute_length, CHECK_(nullHandle));
}
method_parameters_data = cfs->get_u1_buffer();
cfs->skip_u2_fast(method_parameters_length);
cfs->skip_u2_fast(method_parameters_length);
if (!SystemDictionary::Parameter_klass_loaded())
method_parameters_length = 0;
} else if (method_attribute_name == vmSymbols::tag_synthetic()) {
if (method_attribute_length != 0) {
classfile_parse_error(
"Invalid Synthetic method attribute length %u in class file %s",
method_attribute_length, CHECK_(nullHandle));
}
access_flags.set_is_synthetic();
} else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
if (method_attribute_length != 0) {
classfile_parse_error(
"Invalid Deprecated method attribute length %u in class file %s",
method_attribute_length, CHECK_(nullHandle));
}
} else if (_major_version >= JAVA_1_5_VERSION) {
if (method_attribute_name == vmSymbols::tag_signature()) {
if (method_attribute_length != 2) {
classfile_parse_error(
"Invalid Signature attribute length %u in class file %s",
method_attribute_length, CHECK_(nullHandle));
}
generic_signature_index = parse_generic_signature_attribute(CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
runtime_visible_annotations_length = method_attribute_length;
runtime_visible_annotations = cfs->get_u1_buffer();
assert(runtime_visible_annotations != NULL, "null visible annotations");
cfs->guarantee_more(runtime_visible_annotations_length, CHECK_(nullHandle));
parse_annotations(runtime_visible_annotations,
runtime_visible_annotations_length, &parsed_annotations,
CHECK_(nullHandle));
cfs->skip_u1_fast(runtime_visible_annotations_length);
} else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
runtime_invisible_annotations_length = method_attribute_length;
runtime_invisible_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_annotations != NULL, "null invisible annotations");
cfs->skip_u1(runtime_invisible_annotations_length, CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
runtime_visible_parameter_annotations_length = method_attribute_length;
runtime_visible_parameter_annotations = cfs->get_u1_buffer();
assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_(nullHandle));
} else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
runtime_invisible_parameter_annotations_length = method_attribute_length;
runtime_invisible_parameter_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_parameter_annotations != NULL, "null invisible parameter annotations");
cfs->skip_u1(runtime_invisible_parameter_annotations_length, CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
annotation_default_length = method_attribute_length;
annotation_default = cfs->get_u1_buffer();
assert(annotation_default != NULL, "null annotation default");
cfs->skip_u1(annotation_default_length, CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
if (runtime_visible_type_annotations != NULL) {
classfile_parse_error(
"Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
CHECK_(nullHandle));
}
runtime_visible_type_annotations_length = method_attribute_length;
runtime_visible_type_annotations = cfs->get_u1_buffer();
assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_(nullHandle));
} else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
if (runtime_invisible_type_annotations_exists) {
classfile_parse_error(
"Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
CHECK_(nullHandle));
} else {
runtime_invisible_type_annotations_exists = true;
}
if (PreserveAllAnnotations) {
runtime_invisible_type_annotations_length = method_attribute_length;
runtime_invisible_type_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
}
cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
} else {
cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
}
} else {
cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
}
}
if (linenumber_table != NULL) {
linenumber_table->write_terminator();
linenumber_table_length = linenumber_table->position();
}
if (_need_verify) {
guarantee_property(access_flags.is_native() || access_flags.is_abstract() || parsed_code_attribute,
"Absent Code attribute in method that is not native or abstract in class file %s", CHECK_(nullHandle));
}
InlineTableSizes sizes(
total_lvt_length,
linenumber_table_length,
exception_table_length,
checked_exceptions_length,
method_parameters_length,
generic_signature_index,
runtime_visible_annotations_length +
runtime_invisible_annotations_length,
runtime_visible_parameter_annotations_length +
runtime_invisible_parameter_annotations_length,
runtime_visible_type_annotations_length +
runtime_invisible_type_annotations_length,
annotation_default_length,
0);
Method* m = Method::allocate(
_loader_data, code_length, access_flags, &sizes,
ConstMethod::NORMAL, CHECK_(nullHandle));
ClassLoadingService::add_class_method_size(m->size()*HeapWordSize);
m->set_constants(_cp);
m->set_name_index(name_index);
m->set_signature_index(signature_index);
ResultTypeFinder rtf(_cp->symbol_at(signature_index));
m->constMethod()->set_result_type(rtf.type());
if (args_size >= 0) {
m->set_size_of_parameters(args_size);
} else {
m->compute_size_of_parameters(THREAD);
}
#ifdef ASSERT
if (args_size >= 0) {
m->compute_size_of_parameters(THREAD);
assert(args_size == m->size_of_parameters(), "");
}
#endif
m->set_max_stack(max_stack);
m->set_max_locals(max_locals);
if (stackmap_data != NULL) {
m->constMethod()->copy_stackmap_data(_loader_data, stackmap_data,
stackmap_data_length, CHECK_NULL);
}
m->set_code(code_start);
if (linenumber_table != NULL) {
memcpy(m->compressed_linenumber_table(),
linenumber_table->buffer(), linenumber_table_length);
}
if (exception_table_length > 0) {
int size =
exception_table_length * sizeof(ExceptionTableElement) / sizeof(u2);
copy_u2_with_conversion((u2*) m->exception_table_start(),
exception_table_start, size);
}
if (method_parameters_length > 0) {
MethodParametersElement* elem = m->constMethod()->method_parameters_start();
for (int i = 0; i < method_parameters_length; i++) {
elem[i].name_cp_index = Bytes::get_Java_u2(method_parameters_data);
method_parameters_data += 2;
elem[i].flags = Bytes::get_Java_u2(method_parameters_data);
method_parameters_data += 2;
}
}
if (checked_exceptions_length > 0) {
int size = checked_exceptions_length * sizeof(CheckedExceptionElement) / sizeof(u2);
copy_u2_with_conversion((u2*) m->checked_exceptions_start(), checked_exceptions_start, size);
}
if (total_lvt_length > 0) {
promoted_flags->set_has_localvariable_table();
copy_localvariable_table(m->constMethod(), lvt_cnt,
localvariable_table_length,
localvariable_table_start,
lvtt_cnt,
localvariable_type_table_length,
localvariable_type_table_start, CHECK_NULL);
}
if (parsed_annotations.has_any_annotations())
parsed_annotations.apply_to(m);
copy_method_annotations(m->constMethod(),
runtime_visible_annotations,
runtime_visible_annotations_length,
runtime_invisible_annotations,
runtime_invisible_annotations_length,
runtime_visible_parameter_annotations,
runtime_visible_parameter_annotations_length,
runtime_invisible_parameter_annotations,
runtime_invisible_parameter_annotations_length,
runtime_visible_type_annotations,
runtime_visible_type_annotations_length,
runtime_invisible_type_annotations,
runtime_invisible_type_annotations_length,
annotation_default,
annotation_default_length,
CHECK_NULL);
if (name == vmSymbols::finalize_method_name() &&
signature == vmSymbols::void_method_signature()) {
if (m->is_empty_method()) {
_has_empty_finalizer = true;
} else {
_has_finalizer = true;
}
}
if (name == vmSymbols::object_initializer_name() &&
signature == vmSymbols::void_method_signature() &&
m->is_vanilla_constructor()) {
_has_vanilla_constructor = true;
}
NOT_PRODUCT(m->verify());
return m;
}
Array<Method*>* ClassFileParser::parse_methods(bool is_interface,
AccessFlags* promoted_flags,
bool* has_final_method,
bool* declares_default_methods,
TRAPS) {
ClassFileStream* cfs = stream();
cfs->guarantee_more(2, CHECK_NULL); // length
u2 length = cfs->get_u2_fast();
if (length == 0) {
_methods = Universe::the_empty_method_array();
} else {
_methods = MetadataFactory::new_array<Method*>(_loader_data, length, NULL, CHECK_NULL);
HandleMark hm(THREAD);
for (int index = 0; index < length; index++) {
methodHandle method = parse_method(is_interface,
promoted_flags,
CHECK_NULL);
if (method->is_final()) {
}
if (is_interface && !(*declares_default_methods)
&& !method->is_abstract() && !method->is_static()) {
}
_methods->at_put(index, method());
}
if (_need_verify && length > 1) {
ResourceMark rm(THREAD);
NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, NameSigHash*, HASH_ROW_SIZE);
initialize_hashtable(names_and_sigs);
bool dup = false;
Symbol* name = NULL;
Symbol* sig = NULL;
{
debug_only(No_Safepoint_Verifier nsv;)
for (int i = 0; i < length; i++) {
Method* m = _methods->at(i);
name = m->name();
sig = m->signature();
if (!put_after_lookup(name, sig, names_and_sigs)) {
dup = true;
break;
}
}
}
if (dup) {
classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);
}
}
}
return _methods;
}
intArray* ClassFileParser::sort_methods(Array<Method*>* methods) {
int length = methods->length();
if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
for (int index = 0; index < length; index++) {
Method* m = methods->at(index);
assert(!m->valid_vtable_index(), "vtable index should not be set");
m->set_vtable_index(index);
}
}
Method::sort_methods(methods);
intArray* method_ordering = NULL;
if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
method_ordering = new intArray(length);
for (int index = 0; index < length; index++) {
Method* m = methods->at(index);
int old_index = m->vtable_index();
assert(old_index >= 0 && old_index < length, "invalid method index");
method_ordering->at_put(index, old_index);
m->set_vtable_index(Method::invalid_vtable_index);
}
}
return method_ordering;
}
u2 ClassFileParser::parse_generic_signature_attribute(TRAPS) {
ClassFileStream* cfs = stream();
cfs->guarantee_more(2, CHECK_0); // generic_signature_index
u2 generic_signature_index = cfs->get_u2_fast();
check_property(
valid_symbol_at(generic_signature_index),
"Invalid Signature attribute at constant pool index %u in class file %s",
generic_signature_index, CHECK_0);
return generic_signature_index;
}
void ClassFileParser::parse_classfile_sourcefile_attribute(TRAPS) {
ClassFileStream* cfs = stream();
cfs->guarantee_more(2, CHECK); // sourcefile_index
u2 sourcefile_index = cfs->get_u2_fast();
check_property(
valid_symbol_at(sourcefile_index),
"Invalid SourceFile attribute at constant pool index %u in class file %s",
sourcefile_index, CHECK);
set_class_sourcefile_index(sourcefile_index);
}
void ClassFileParser::parse_classfile_source_debug_extension_attribute(int length, TRAPS) {
ClassFileStream* cfs = stream();
u1* sde_buffer = cfs->get_u1_buffer();
assert(sde_buffer != NULL, "null sde buffer");
if (JvmtiExport::can_get_source_debug_extension()) {
assert((length+1) > length, "Overflow checking");
u1* sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
for (int i = 0; i < length; i++) {
sde[i] = sde_buffer[i];
}
sde[length] = '\0';
set_class_sde_buffer((char*)sde, length);
}
cfs->skip_u1(length, CHECK);
}
#define RECOGNIZED_INNER_CLASS_MODIFIERS (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED | JVM_ACC_STATIC)
static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
Symbol* cp_klass_name = cp->klass_name_at(inner);
for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
if (cp->klass_name_at(idx_inner) == cp_klass_name) {
return idx;
}
}
return -1;
}
static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {
if (inner == 0) return -1;
int idx = inner_classes_find_index(inner_classes, inner, cp, length);
if (idx == -1) return -1;
int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
return result;
}
static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {
int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);
int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);
while (fast != -1 && fast != 0) {
if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {
return true; // found a circularity
}
fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
if (fast == -1) return false;
fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);
if (fast == -1) return false;
slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length);
assert(slow != -1, "sanity check");
}
return false;
}
bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) {
for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {
if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) {
return true;
}
for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;
y += InstanceKlass::inner_class_next_offset) {
guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||
_inner_classes->at(idx+1) != _inner_classes->at(y+1) ||
_inner_classes->at(idx+2) != _inner_classes->at(y+2) ||
_inner_classes->at(idx+3) != _inner_classes->at(y+3)),
"Duplicate entry in InnerClasses attribute in class file %s",
CHECK_(true));
if (_inner_classes->at(y) == _inner_classes->at(idx)) {
return true;
}
}
}
return false;
}
u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ConstantPool* cp,
u1* inner_classes_attribute_start,
bool parsed_enclosingmethod_attribute,
u2 enclosing_method_class_index,
u2 enclosing_method_method_index,
TRAPS) {
ClassFileStream* cfs = stream();
u1* current_mark = cfs->current();
u2 length = 0;
if (inner_classes_attribute_start != NULL) {
cfs->set_current(inner_classes_attribute_start);
cfs->guarantee_more(2, CHECK_0); // length
length = cfs->get_u2_fast();
}
int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
_inner_classes = inner_classes;
int index = 0;
int cp_size = _cp->length();
cfs->guarantee_more(8 * length, CHECK_0); // 4-tuples of u2
for (int n = 0; n < length; n++) {
u2 inner_class_info_index = cfs->get_u2_fast();
check_property(
valid_klass_reference_at(inner_class_info_index),
"inner_class_info_index %u has bad constant type in class file %s",
inner_class_info_index, CHECK_0);
u2 outer_class_info_index = cfs->get_u2_fast();
check_property(
outer_class_info_index == 0 ||
valid_klass_reference_at(outer_class_info_index),
"outer_class_info_index %u has bad constant type in class file %s",
outer_class_info_index, CHECK_0);
if (outer_class_info_index != 0) {
const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index);
char* bytes = (char*)outer_class_name->bytes();
guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY,
"Outer class is an array class in class file %s", CHECK_0);
}
u2 inner_name_index = cfs->get_u2_fast();
check_property(
inner_name_index == 0 || valid_symbol_at(inner_name_index),
"inner_name_index %u has bad constant type in class file %s",
inner_name_index, CHECK_0);
if (_need_verify) {
guarantee_property(inner_class_info_index != outer_class_info_index,
"Class is both outer and inner class in class file %s", CHECK_0);
}
AccessFlags inner_access_flags;
jint flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
flags |= JVM_ACC_ABSTRACT;
}
verify_legal_class_modifiers(flags, CHECK_0);
inner_access_flags.set_flags(flags);
inner_classes->at_put(index++, inner_class_info_index);
inner_classes->at_put(index++, outer_class_info_index);
inner_classes->at_put(index++, inner_name_index);
inner_classes->at_put(index++, inner_access_flags.as_short());
}
bool has_circularity = false;
if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);
if (has_circularity) {
MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
index = 0;
if (parsed_enclosingmethod_attribute) {
inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);
_inner_classes = inner_classes;
} else {
_inner_classes = Universe::the_empty_short_array();
}
}
}
if (parsed_enclosingmethod_attribute) {
inner_classes->at_put(index++, enclosing_method_class_index);
inner_classes->at_put(index++, enclosing_method_method_index);
}
assert(index == size || has_circularity, "wrong size");
cfs->set_current(current_mark);
return length;
}
void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
set_class_synthetic_flag(true);
}
void ClassFileParser::parse_classfile_signature_attribute(TRAPS) {
ClassFileStream* cfs = stream();
u2 signature_index = cfs->get_u2(CHECK);
check_property(
valid_symbol_at(signature_index),
"Invalid constant pool index %u in Signature attribute in class file %s",
signature_index, CHECK);
set_class_generic_signature_index(signature_index);
}
void ClassFileParser::parse_classfile_bootstrap_methods_attribute(u4 attribute_byte_length, TRAPS) {
ClassFileStream* cfs = stream();
u1* current_start = cfs->current();
guarantee_property(attribute_byte_length >= sizeof(u2),
"Invalid BootstrapMethods attribute length %u in class file %s",
attribute_byte_length,
CHECK);
cfs->guarantee_more(attribute_byte_length, CHECK);
int attribute_array_length = cfs->get_u2_fast();
guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
"Short length on BootstrapMethods in class file %s",
CHECK);
int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
int index_size = (attribute_array_length * 2);
Array<u2>* operands = MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
_cp->set_operands(operands);
int operand_fill_index = index_size;
int cp_size = _cp->length();
for (int n = 0; n < attribute_array_length; n++) {
ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
cfs->guarantee_more(sizeof(u2) * 2, CHECK); // bsm, argc
u2 bootstrap_method_index = cfs->get_u2_fast();
u2 argument_count = cfs->get_u2_fast();
check_property(
valid_cp_range(bootstrap_method_index, cp_size) &&
_cp->tag_at(bootstrap_method_index).is_method_handle(),
"bootstrap_method_index %u has bad constant type in class file %s",
bootstrap_method_index,
CHECK);
guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
"Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
CHECK);
operands->at_put(operand_fill_index++, bootstrap_method_index);
operands->at_put(operand_fill_index++, argument_count);
cfs->guarantee_more(sizeof(u2) * argument_count, CHECK); // argv[argc]
for (int j = 0; j < argument_count; j++) {
u2 argument_index = cfs->get_u2_fast();
check_property(
valid_cp_range(argument_index, cp_size) &&
_cp->tag_at(argument_index).is_loadable_constant(),
"argument_index %u has bad constant type in class file %s",
argument_index,
CHECK);
operands->at_put(operand_fill_index++, argument_index);
}
}
assert(operand_fill_index == operands->length(), "exact fill");
u1* current_end = cfs->current();
guarantee_property(current_end == current_start + attribute_byte_length,
"Bad length on BootstrapMethods in class file %s",
CHECK);
}
void ClassFileParser::parse_classfile_attributes(ClassFileParser::ClassAnnotationCollector* parsed_annotations,
TRAPS) {
ClassFileStream* cfs = stream();
_inner_classes = Universe::the_empty_short_array();
cfs->guarantee_more(2, CHECK); // attributes_count
u2 attributes_count = cfs->get_u2_fast();
bool parsed_sourcefile_attribute = false;
bool parsed_innerclasses_attribute = false;
bool parsed_enclosingmethod_attribute = false;
bool parsed_bootstrap_methods_attribute = false;
u1* runtime_visible_annotations = NULL;
int runtime_visible_annotations_length = 0;
u1* runtime_invisible_annotations = NULL;
int runtime_invisible_annotations_length = 0;
u1* runtime_visible_type_annotations = NULL;
int runtime_visible_type_annotations_length = 0;
u1* runtime_invisible_type_annotations = NULL;
int runtime_invisible_type_annotations_length = 0;
bool runtime_invisible_type_annotations_exists = false;
u1* inner_classes_attribute_start = NULL;
u4 inner_classes_attribute_length = 0;
u2 enclosing_method_class_index = 0;
u2 enclosing_method_method_index = 0;
while (attributes_count--) {
cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length
u2 attribute_name_index = cfs->get_u2_fast();
u4 attribute_length = cfs->get_u4_fast();
check_property(
valid_symbol_at(attribute_name_index),
"Attribute name has bad constant pool index %u in class file %s",
attribute_name_index, CHECK);
Symbol* tag = _cp->symbol_at(attribute_name_index);
if (tag == vmSymbols::tag_source_file()) {
if (_need_verify) {
guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
}
if (parsed_sourcefile_attribute) {
classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
} else {
parsed_sourcefile_attribute = true;
}
parse_classfile_sourcefile_attribute(CHECK);
} else if (tag == vmSymbols::tag_source_debug_extension()) {
parse_classfile_source_debug_extension_attribute((int)attribute_length, CHECK);
} else if (tag == vmSymbols::tag_inner_classes()) {
if (parsed_innerclasses_attribute) {
classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
} else {
parsed_innerclasses_attribute = true;
}
inner_classes_attribute_start = cfs->get_u1_buffer();
inner_classes_attribute_length = attribute_length;
cfs->skip_u1(inner_classes_attribute_length, CHECK);
} else if (tag == vmSymbols::tag_synthetic()) {
if (attribute_length != 0) {
classfile_parse_error(
"Invalid Synthetic classfile attribute length %u in class file %s",
attribute_length, CHECK);
}
parse_classfile_synthetic_attribute(CHECK);
} else if (tag == vmSymbols::tag_deprecated()) {
if (attribute_length != 0) {
classfile_parse_error(
"Invalid Deprecated classfile attribute length %u in class file %s",
attribute_length, CHECK);
}
} else if (_major_version >= JAVA_1_5_VERSION) {
if (tag == vmSymbols::tag_signature()) {
if (attribute_length != 2) {
classfile_parse_error(
"Wrong Signature attribute length %u in class file %s",
attribute_length, CHECK);
}
parse_classfile_signature_attribute(CHECK);
} else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
runtime_visible_annotations_length = attribute_length;
runtime_visible_annotations = cfs->get_u1_buffer();
assert(runtime_visible_annotations != NULL, "null visible annotations");
cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
parse_annotations(runtime_visible_annotations,
runtime_visible_annotations_length,
parsed_annotations,
CHECK);
cfs->skip_u1_fast(runtime_visible_annotations_length);
} else if (PreserveAllAnnotations && tag == vmSymbols::tag_runtime_invisible_annotations()) {
runtime_invisible_annotations_length = attribute_length;
runtime_invisible_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_annotations != NULL, "null invisible annotations");
cfs->skip_u1(runtime_invisible_annotations_length, CHECK);
} else if (tag == vmSymbols::tag_enclosing_method()) {
if (parsed_enclosingmethod_attribute) {
classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
} else {
parsed_enclosingmethod_attribute = true;
}
cfs->guarantee_more(4, CHECK); // class_index, method_index
enclosing_method_class_index = cfs->get_u2_fast();
enclosing_method_method_index = cfs->get_u2_fast();
if (enclosing_method_class_index == 0) {
classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
}
check_property(valid_klass_reference_at(enclosing_method_class_index),
"Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
if (enclosing_method_method_index != 0 &&
(!_cp->is_within_bounds(enclosing_method_method_index) ||
!_cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
}
} else if (tag == vmSymbols::tag_bootstrap_methods() &&
_major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
if (parsed_bootstrap_methods_attribute)
classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
parsed_bootstrap_methods_attribute = true;
parse_classfile_bootstrap_methods_attribute(attribute_length, CHECK);
} else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
if (runtime_visible_type_annotations != NULL) {
classfile_parse_error(
"Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
}
runtime_visible_type_annotations_length = attribute_length;
runtime_visible_type_annotations = cfs->get_u1_buffer();
assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
} else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
if (runtime_invisible_type_annotations_exists) {
classfile_parse_error(
"Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
} else {
runtime_invisible_type_annotations_exists = true;
}
if (PreserveAllAnnotations) {
runtime_invisible_type_annotations_length = attribute_length;
runtime_invisible_type_annotations = cfs->get_u1_buffer();
assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
}
cfs->skip_u1(attribute_length, CHECK);
} else {
cfs->skip_u1(attribute_length, CHECK);
}
} else {
cfs->skip_u1(attribute_length, CHECK);
}
}
_annotations = assemble_annotations(runtime_visible_annotations,
runtime_visible_annotations_length,
runtime_invisible_annotations,
runtime_invisible_annotations_length,
CHECK);
_type_annotations = assemble_annotations(runtime_visible_type_annotations,
runtime_visible_type_annotations_length,
runtime_invisible_type_annotations,
runtime_invisible_type_annotations_length,
CHECK);
if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
u2 num_of_classes = parse_classfile_inner_classes_attribute(
_cp,
inner_classes_attribute_start,
parsed_innerclasses_attribute,
enclosing_method_class_index,
enclosing_method_method_index,
CHECK);
if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
guarantee_property(
inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
"Wrong InnerClasses attribute length in class file %s", CHECK);
}
}
if (_max_bootstrap_specifier_index >= 0) {
guarantee_property(parsed_bootstrap_methods_attribute,
"Missing BootstrapMethods attribute in class file %s", CHECK);
}
}
void ClassFileParser::apply_parsed_class_attributes(instanceKlassHandle k) {
if (_synthetic_flag)
k->set_is_synthetic();
if (_sourcefile_index != 0) {
k->set_source_file_name_index(_sourcefile_index);
}
if (_generic_signature_index != 0) {
k->set_generic_signature_index(_generic_signature_index);
}
if (_sde_buffer != NULL) {
k->set_source_debug_extension(_sde_buffer, _sde_length);
}
}
void ClassFileParser::create_combined_annotations(TRAPS) {
if (_annotations == NULL &&
_type_annotations == NULL &&
_fields_annotations == NULL &&
_fields_type_annotations == NULL) {
return;
}
Annotations* annotations = Annotations::allocate(_loader_data, CHECK);
annotations->set_class_annotations(_annotations);
annotations->set_class_type_annotations(_type_annotations);
annotations->set_fields_annotations(_fields_annotations);
annotations->set_fields_type_annotations(_fields_type_annotations);
_combined_annotations = annotations;
_annotations = NULL;
_type_annotations = NULL;
_fields_annotations = NULL;
_fields_type_annotations = NULL;
}
void ClassFileParser::apply_parsed_class_metadata(
instanceKlassHandle this_klass,
int java_fields_count, TRAPS) {
_cp->set_pool_holder(this_klass());
this_klass->set_constants(_cp);
this_klass->set_fields(_fields, java_fields_count);
this_klass->set_methods(_methods);
this_klass->set_inner_classes(_inner_classes);
this_klass->set_local_interfaces(_local_interfaces);
this_klass->set_transitive_interfaces(_transitive_interfaces);
this_klass->set_annotations(_combined_annotations);
clear_class_metadata();
}
AnnotationArray* ClassFileParser::assemble_annotations(u1* runtime_visible_annotations,
int runtime_visible_annotations_length,
u1* runtime_invisible_annotations,
int runtime_invisible_annotations_length, TRAPS) {
AnnotationArray* annotations = NULL;
if (runtime_visible_annotations != NULL ||
runtime_invisible_annotations != NULL) {
annotations = MetadataFactory::new_array<u1>(_loader_data,
runtime_visible_annotations_length +
runtime_invisible_annotations_length,
CHECK_(annotations));
if (runtime_visible_annotations != NULL) {
for (int i = 0; i < runtime_visible_annotations_length; i++) {
annotations->at_put(i, runtime_visible_annotations[i]);
}
}
if (runtime_invisible_annotations != NULL) {
for (int i = 0; i < runtime_invisible_annotations_length; i++) {
int append = runtime_visible_annotations_length+i;
annotations->at_put(append, runtime_invisible_annotations[i]);
}
}
}
return annotations;
}
instanceKlassHandle ClassFileParser::parse_super_class(int super_class_index,
TRAPS) {
instanceKlassHandle super_klass;
if (super_class_index == 0) {
check_property(_class_name == vmSymbols::java_lang_Object(),
"Invalid superclass index %u in class file %s",
super_class_index,
CHECK_NULL);
} else {
check_property(valid_klass_reference_at(super_class_index),
"Invalid superclass index %u in class file %s",
super_class_index,
CHECK_NULL);
bool is_array = false;
if (_cp->tag_at(super_class_index).is_klass()) {
super_klass = instanceKlassHandle(THREAD, _cp->resolved_klass_at(super_class_index));
if (_need_verify)
is_array = super_klass->oop_is_array();
} else if (_need_verify) {
is_array = (_cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
}
if (_need_verify) {
guarantee_property(!is_array,
"Bad superclass name in class file %s", CHECK_NULL);
}
}
return super_klass;
}
class FieldLayoutInfo : public StackObj {
public:
int* nonstatic_oop_offsets;
unsigned int* nonstatic_oop_counts;
unsigned int nonstatic_oop_map_count;
unsigned int total_oop_map_count;
int instance_size;
int nonstatic_field_size;
int static_field_size;
bool has_nonstatic_fields;
};
void ClassFileParser::layout_fields(Handle class_loader,
FieldAllocationCount* fac,
ClassAnnotationCollector* parsed_annotations,
FieldLayoutInfo* info,
TRAPS) {
int nonstatic_field_size = _super_klass() == NULL ? 0 : _super_klass()->nonstatic_field_size();
int next_static_oop_offset = 0;
int next_static_double_offset = 0;
int next_static_word_offset = 0;
int next_static_short_offset = 0;
int next_static_byte_offset = 0;
int next_nonstatic_oop_offset = 0;
int next_nonstatic_double_offset = 0;
int next_nonstatic_word_offset = 0;
int next_nonstatic_short_offset = 0;
int next_nonstatic_byte_offset = 0;
int first_nonstatic_oop_offset = 0;
int next_nonstatic_field_offset = 0;
int next_nonstatic_padded_offset = 0;
int nonstatic_contended_count = 0;
FieldAllocationCount fac_contended;
for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
if (fs.is_contended()) {
fac_contended.count[atype]++;
if (!fs.access_flags().is_static()) {
nonstatic_contended_count++;
}
}
}
next_static_oop_offset = InstanceMirrorKlass::offset_of_static_fields();
next_static_double_offset = next_static_oop_offset +
((fac->count[STATIC_OOP]) * heapOopSize);
if ( fac->count[STATIC_DOUBLE] &&
(Universe::field_type_should_be_aligned(T_DOUBLE) ||
Universe::field_type_should_be_aligned(T_LONG)) ) {
next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);
}
next_static_word_offset = next_static_double_offset +
((fac->count[STATIC_DOUBLE]) * BytesPerLong);
next_static_short_offset = next_static_word_offset +
((fac->count[STATIC_WORD]) * BytesPerInt);
next_static_byte_offset = next_static_short_offset +
((fac->count[STATIC_SHORT]) * BytesPerShort);
int nonstatic_fields_start = instanceOopDesc::base_offset_in_bytes() +
nonstatic_field_size * heapOopSize;
next_nonstatic_field_offset = nonstatic_fields_start;
bool is_contended_class = parsed_annotations->is_contended();
if (is_contended_class) {
next_nonstatic_field_offset += ContendedPaddingWidth;
}
unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
unsigned int nonstatic_word_count = fac->count[NONSTATIC_WORD] - fac_contended.count[NONSTATIC_WORD];
unsigned int nonstatic_short_count = fac->count[NONSTATIC_SHORT] - fac_contended.count[NONSTATIC_SHORT];
unsigned int nonstatic_byte_count = fac->count[NONSTATIC_BYTE] - fac_contended.count[NONSTATIC_BYTE];
unsigned int nonstatic_oop_count = fac->count[NONSTATIC_OOP] - fac_contended.count[NONSTATIC_OOP];
unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
fac->count[NONSTATIC_OOP];
bool super_has_nonstatic_fields =
(_super_klass() != NULL && _super_klass->has_nonstatic_fields());
bool has_nonstatic_fields = super_has_nonstatic_fields || (nonstatic_fields_count != 0);
int* nonstatic_oop_offsets;
unsigned int* nonstatic_oop_counts;
unsigned int nonstatic_oop_map_count = 0;
unsigned int max_nonstatic_oop_maps = fac->count[NONSTATIC_OOP] + 1;
nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, int, max_nonstatic_oop_maps);
nonstatic_oop_counts = NEW_RESOURCE_ARRAY_IN_THREAD(
THREAD, unsigned int, max_nonstatic_oop_maps);
first_nonstatic_oop_offset = 0; // will be set for first oop field
bool compact_fields = CompactFields;
int allocation_style = FieldsAllocationStyle;
if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
assert(false, "0 <= FieldsAllocationStyle <= 2");
allocation_style = 1; // Optimistic
}
if( (allocation_style != 0 || compact_fields ) && class_loader.is_null() &&
(_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
_class_name == vmSymbols::java_lang_Class() ||
_class_name == vmSymbols::java_lang_ClassLoader() ||
_class_name == vmSymbols::java_lang_ref_Reference() ||
_class_name == vmSymbols::java_lang_ref_SoftReference() ||
_class_name == vmSymbols::java_lang_StackTraceElement() ||
_class_name == vmSymbols::java_lang_String() ||
_class_name == vmSymbols::java_lang_Throwable() ||
_class_name == vmSymbols::java_lang_Boolean() ||
_class_name == vmSymbols::java_lang_Character() ||
_class_name == vmSymbols::java_lang_Float() ||
_class_name == vmSymbols::java_lang_Double() ||
_class_name == vmSymbols::java_lang_Byte() ||
_class_name == vmSymbols::java_lang_Short() ||
_class_name == vmSymbols::java_lang_Integer() ||
_class_name == vmSymbols::java_lang_Long())) {
allocation_style = 0; // Allocate oops first
compact_fields = false; // Don't compact fields
}
if( allocation_style == 0 ) {
next_nonstatic_oop_offset = next_nonstatic_field_offset;
next_nonstatic_double_offset = next_nonstatic_oop_offset +
(nonstatic_oop_count * heapOopSize);
} else if( allocation_style == 1 ) {
next_nonstatic_double_offset = next_nonstatic_field_offset;
} else if( allocation_style == 2 ) {
if( nonstatic_field_size > 0 && _super_klass() != NULL &&
_super_klass->nonstatic_oop_map_size() > 0 ) {
unsigned int map_count = _super_klass->nonstatic_oop_map_count();
OopMapBlock* first_map = _super_klass->start_of_nonstatic_oop_maps();
OopMapBlock* last_map = first_map + map_count - 1;
int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
if (next_offset == next_nonstatic_field_offset) {
allocation_style = 0; // allocate oops first
next_nonstatic_oop_offset = next_nonstatic_field_offset;
next_nonstatic_double_offset = next_nonstatic_oop_offset +
(nonstatic_oop_count * heapOopSize);
}
}
if( allocation_style == 2 ) {
allocation_style = 1; // allocate oops last
next_nonstatic_double_offset = next_nonstatic_field_offset;
}
} else {
ShouldNotReachHere();
}
int nonstatic_oop_space_count = 0;
int nonstatic_word_space_count = 0;
int nonstatic_short_space_count = 0;
int nonstatic_byte_space_count = 0;
int nonstatic_oop_space_offset = 0;
int nonstatic_word_space_offset = 0;
int nonstatic_short_space_offset = 0;
int nonstatic_byte_space_offset = 0;
if( nonstatic_double_count > 0 ) {
int offset = next_nonstatic_double_offset;
next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);
if( compact_fields && offset != next_nonstatic_double_offset ) {
int length = next_nonstatic_double_offset - offset;
assert(length == BytesPerInt, "");
nonstatic_word_space_offset = offset;
if( nonstatic_word_count > 0 ) {
nonstatic_word_count -= 1;
nonstatic_word_space_count = 1; // Only one will fit
length -= BytesPerInt;
offset += BytesPerInt;
}
nonstatic_short_space_offset = offset;
while( length >= BytesPerShort && nonstatic_short_count > 0 ) {
nonstatic_short_count -= 1;
nonstatic_short_space_count += 1;
length -= BytesPerShort;
offset += BytesPerShort;
}
nonstatic_byte_space_offset = offset;
while( length > 0 && nonstatic_byte_count > 0 ) {
nonstatic_byte_count -= 1;
nonstatic_byte_space_count += 1;
length -= 1;
}
nonstatic_oop_space_offset = offset;
if( length >= heapOopSize && nonstatic_oop_count > 0 &&
allocation_style != 0 ) { // when oop fields not first
nonstatic_oop_count -= 1;
nonstatic_oop_space_count = 1; // Only one will fit
length -= heapOopSize;
offset += heapOopSize;
}
}
}
next_nonstatic_word_offset = next_nonstatic_double_offset +
(nonstatic_double_count * BytesPerLong);
next_nonstatic_short_offset = next_nonstatic_word_offset +
(nonstatic_word_count * BytesPerInt);
next_nonstatic_byte_offset = next_nonstatic_short_offset +
(nonstatic_short_count * BytesPerShort);
next_nonstatic_padded_offset = next_nonstatic_byte_offset +
nonstatic_byte_count;
if( allocation_style == 1 ) {
next_nonstatic_oop_offset = next_nonstatic_padded_offset;
if( nonstatic_oop_count > 0 ) {
next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);
}
next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
}
for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
if (fs.is_offset_set()) continue;
if (fs.is_contended() && !fs.access_flags().is_static()) continue;
int real_offset = 0;
FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
switch (atype) {
case STATIC_OOP:
real_offset = next_static_oop_offset;
next_static_oop_offset += heapOopSize;
break;
case STATIC_BYTE:
real_offset = next_static_byte_offset;
next_static_byte_offset += 1;
break;
case STATIC_SHORT:
real_offset = next_static_short_offset;
next_static_short_offset += BytesPerShort;
break;
case STATIC_WORD:
real_offset = next_static_word_offset;
next_static_word_offset += BytesPerInt;
break;
case STATIC_DOUBLE:
real_offset = next_static_double_offset;
next_static_double_offset += BytesPerLong;
break;
case NONSTATIC_OOP:
if( nonstatic_oop_space_count > 0 ) {
real_offset = nonstatic_oop_space_offset;
nonstatic_oop_space_offset += heapOopSize;
nonstatic_oop_space_count -= 1;
} else {
real_offset = next_nonstatic_oop_offset;
next_nonstatic_oop_offset += heapOopSize;
}
if( nonstatic_oop_map_count > 0 &&
nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
real_offset -
int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
heapOopSize ) {
assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");
nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
} else {
assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
nonstatic_oop_map_count += 1;
if( first_nonstatic_oop_offset == 0 ) { // Undefined
first_nonstatic_oop_offset = real_offset;
}
}
break;
case NONSTATIC_BYTE:
if( nonstatic_byte_space_count > 0 ) {
real_offset = nonstatic_byte_space_offset;
nonstatic_byte_space_offset += 1;
nonstatic_byte_space_count -= 1;
} else {
real_offset = next_nonstatic_byte_offset;
next_nonstatic_byte_offset += 1;
}
break;
case NONSTATIC_SHORT:
if( nonstatic_short_space_count > 0 ) {
real_offset = nonstatic_short_space_offset;
nonstatic_short_space_offset += BytesPerShort;
nonstatic_short_space_count -= 1;
} else {
real_offset = next_nonstatic_short_offset;
next_nonstatic_short_offset += BytesPerShort;
}
break;
case NONSTATIC_WORD:
if( nonstatic_word_space_count > 0 ) {
real_offset = nonstatic_word_space_offset;
nonstatic_word_space_offset += BytesPerInt;
nonstatic_word_space_count -= 1;
} else {
real_offset = next_nonstatic_word_offset;
next_nonstatic_word_offset += BytesPerInt;
}
break;
case NONSTATIC_DOUBLE:
real_offset = next_nonstatic_double_offset;
next_nonstatic_double_offset += BytesPerLong;
break;
default:
ShouldNotReachHere();
}
fs.set_offset(real_offset);
}
if (nonstatic_contended_count > 0) {
next_nonstatic_padded_offset += ContendedPaddingWidth;
BitMap bm(_cp->size());
for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
if (fs.is_offset_set()) continue;
if (fs.is_contended()) {
bm.set_bit(fs.contended_group());
}
}
int current_group = -1;
while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
if (fs.is_offset_set()) continue;
if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
if (fs.access_flags().is_static()) continue;
int real_offset = 0;
FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
switch (atype) {
case NONSTATIC_BYTE:
next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, 1);
real_offset = next_nonstatic_padded_offset;
next_nonstatic_padded_offset += 1;
break;
case NONSTATIC_SHORT:
next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerShort);
real_offset = next_nonstatic_padded_offset;
next_nonstatic_padded_offset += BytesPerShort;
break;
case NONSTATIC_WORD:
next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerInt);
real_offset = next_nonstatic_padded_offset;
next_nonstatic_padded_offset += BytesPerInt;
break;
case NONSTATIC_DOUBLE:
next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);
real_offset = next_nonstatic_padded_offset;
next_nonstatic_padded_offset += BytesPerLong;
break;
case NONSTATIC_OOP:
next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, heapOopSize);
real_offset = next_nonstatic_padded_offset;
next_nonstatic_padded_offset += heapOopSize;
assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
nonstatic_oop_map_count += 1;
if( first_nonstatic_oop_offset == 0 ) { // Undefined
first_nonstatic_oop_offset = real_offset;
}
break;
default:
ShouldNotReachHere();
}
if (fs.contended_group() == 0) {
next_nonstatic_padded_offset += ContendedPaddingWidth;
}
fs.set_offset(real_offset);
} // for
if (current_group != 0) {
next_nonstatic_padded_offset += ContendedPaddingWidth;
}
}
}
if (is_contended_class) {
next_nonstatic_padded_offset += ContendedPaddingWidth;
}
int notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
int nonstatic_fields_end = align_size_up(notaligned_nonstatic_fields_end, heapOopSize);
int instance_end = align_size_up(notaligned_nonstatic_fields_end, wordSize);
int static_fields_end = align_size_up(next_static_byte_offset, wordSize);
int static_field_size = (static_fields_end -
InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
nonstatic_field_size = nonstatic_field_size +
(nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
int instance_size = align_object_size(instance_end / wordSize);
assert(instance_size == align_object_size(align_size_up(
(instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize),
wordSize) / wordSize), "consistent layout helper value");
assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
is_contended_class ||
(nonstatic_fields_count > 0), "double-check nonstatic start/end");
const unsigned int total_oop_map_count =
compute_oop_map_count(_super_klass, nonstatic_oop_map_count,
first_nonstatic_oop_offset);
#ifndef PRODUCT
if (PrintFieldLayout) {
print_field_layout(_class_name,
_fields,
_cp,
instance_size,
nonstatic_fields_start,
nonstatic_fields_end,
static_fields_end);
}
#endif
info->nonstatic_oop_offsets = nonstatic_oop_offsets;
info->nonstatic_oop_counts = nonstatic_oop_counts;
info->nonstatic_oop_map_count = nonstatic_oop_map_count;
info->total_oop_map_count = total_oop_map_count;
info->instance_size = instance_size;
info->static_field_size = static_field_size;
info->nonstatic_field_size = nonstatic_field_size;
info->has_nonstatic_fields = has_nonstatic_fields;
}
static bool relax_format_check_for(ClassLoaderData* loader_data) {
bool trusted = (loader_data->is_the_null_class_loader_data() ||
SystemDictionary::is_ext_class_loader(loader_data->class_loader()));
bool need_verify =
(BytecodeVerificationLocal && BytecodeVerificationRemote) ||
(!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
return !need_verify;
}
instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,
ClassLoaderData* loader_data,
Handle protection_domain,
KlassHandle host_klass,
GrowableArray<Handle>* cp_patches,
TempNewSymbol& parsed_name,
bool verify,
TRAPS) {
JvmtiCachedClassFileData *cached_class_file = NULL;
Handle class_loader(THREAD, loader_data->class_loader());
bool has_default_methods = false;
bool declares_default_methods = false;
ClassFileStream* cfs = stream();
assert(THREAD->is_Java_thread(), "must be a JavaThread");
JavaThread* jt = (JavaThread*) THREAD;
PerfClassTraceTime ctimer(ClassLoader::perf_class_parse_time(),
ClassLoader::perf_class_parse_selftime(),
NULL,
jt->get_thread_stat()->perf_recursion_counts_addr(),
jt->get_thread_stat()->perf_timers_addr(),
PerfClassTraceTime::PARSE_CLASS);
init_parsed_class_attributes(loader_data);
if (JvmtiExport::should_post_class_file_load_hook()) {
JvmtiThreadState *state = jt->jvmti_thread_state();
if (state != NULL) {
KlassHandle *h_class_being_redefined =
state->get_class_being_redefined();
if (h_class_being_redefined != NULL) {
instanceKlassHandle ikh_class_being_redefined =
instanceKlassHandle(THREAD, (*h_class_being_redefined)());
cached_class_file = ikh_class_being_redefined->get_cached_class_file();
}
}
unsigned char* ptr = cfs->buffer();
unsigned char* end_ptr = cfs->buffer() + cfs->length();
JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain,
&ptr, &end_ptr, &cached_class_file);
if (ptr != cfs->buffer()) {
cfs = new ClassFileStream(ptr, end_ptr - ptr, cfs->source());
set_stream(cfs);
}
}
_host_klass = host_klass;
_cp_patches = cp_patches;
instanceKlassHandle nullHandle;
if (DumpSharedSpaces) {
_need_verify = (verify) ? BytecodeVerificationRemote :
BytecodeVerificationLocal;
} else {
_need_verify = Verifier::should_verify_for(class_loader(), verify);
}
cfs->set_verify(_need_verify);
_class_name = (name != NULL) ? name : vmSymbols::unknown_class_name();
cfs->guarantee_more(8, CHECK_(nullHandle)); // magic, major, minor
u4 magic = cfs->get_u4_fast();
guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
"Incompatible magic value %u in class file %s",
magic, CHECK_(nullHandle));
u2 minor_version = cfs->get_u2_fast();
u2 major_version = cfs->get_u2_fast();
if (DumpSharedSpaces && major_version < JAVA_1_5_VERSION) {
ResourceMark rm;
warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
major_version, minor_version, name->as_C_string());
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_UnsupportedClassVersionError(),
"Unsupported major.minor version for dump time %u.%u",
major_version,
minor_version);
}
if (!is_supported_version(major_version, minor_version)) {
if (name == NULL) {
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_UnsupportedClassVersionError(),
"Unsupported class file version %u.%u, "
"this version of the Java Runtime only recognizes class file versions up to %u.%u",
major_version,
minor_version,
JAVA_MAX_SUPPORTED_VERSION,
JAVA_MAX_SUPPORTED_MINOR_VERSION);
} else {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_UnsupportedClassVersionError(),
"%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
"this version of the Java Runtime only recognizes class file versions up to %u.%u",
name->as_C_string(),
major_version,
minor_version,
JAVA_MAX_SUPPORTED_VERSION,
JAVA_MAX_SUPPORTED_MINOR_VERSION);
}
return nullHandle;
}
_major_version = major_version;
_minor_version = minor_version;
_relax_verify = relax_format_check_for(_loader_data);
constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));
int cp_size = cp->length();
cfs->guarantee_more(8, CHECK_(nullHandle)); // flags, this_class, super_class, infs_len
AccessFlags access_flags;
jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
flags |= JVM_ACC_ABSTRACT;
}
verify_legal_class_modifiers(flags, CHECK_(nullHandle));
access_flags.set_flags(flags);
_this_class_index = cfs->get_u2_fast();
check_property(
valid_cp_range(_this_class_index, cp_size) &&
cp->tag_at(_this_class_index).is_unresolved_klass(),
"Invalid this class index %u in constant pool in class file %s",
_this_class_index, CHECK_(nullHandle));
Symbol* class_name = cp->unresolved_klass_at(_this_class_index);
assert(class_name != NULL, "class_name can't be null");
parsed_name = class_name;
parsed_name->increment_refcount();
_class_name = class_name;
if (_need_verify) {
guarantee_property(class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
"Bad class name in class file %s",
CHECK_(nullHandle));
}
Klass* preserve_this_klass; // for storing result across HandleMark
{ HandleMark hm(THREAD);
if (name != NULL && class_name != name) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_NoClassDefFoundError(),
"%s (wrong name: %s)",
name->as_C_string(),
class_name->as_C_string()
);
return nullHandle;
}
if (TraceClassLoadingPreorder) {
tty->print("[Loading %s", (name != NULL) ? name->as_klass_external_name() : "NoName");
if (cfs->source() != NULL) tty->print(" from %s", cfs->source());
tty->print_cr("]");
}
#if INCLUDE_CDS
if (DumpLoadedClassList != NULL && cfs->source() != NULL && classlist_file->is_open()) {
if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
if (name != NULL) {
ResourceMark rm(THREAD);
classlist_file->print_cr("%s", name->as_C_string());
classlist_file->flush();
}
}
}
#endif
u2 super_class_index = cfs->get_u2_fast();
instanceKlassHandle super_klass = parse_super_class(super_class_index,
CHECK_NULL);
u2 itfs_len = cfs->get_u2_fast();
Array<Klass*>* local_interfaces =
parse_interfaces(itfs_len, protection_domain, _class_name,
&has_default_methods, CHECK_(nullHandle));
u2 java_fields_count = 0;
FieldAllocationCount fac;
Array<u2>* fields = parse_fields(class_name,
access_flags.is_interface(),
&fac, &java_fields_count,
CHECK_(nullHandle));
bool has_final_method = false;
AccessFlags promoted_flags;
promoted_flags.set_flags(0);
Array<Method*>* methods = parse_methods(access_flags.is_interface(),
&promoted_flags,
&has_final_method,
&declares_default_methods,
CHECK_(nullHandle));
if (declares_default_methods) {
has_default_methods = true;
}
ClassAnnotationCollector parsed_annotations;
parse_classfile_attributes(&parsed_annotations, CHECK_(nullHandle));
create_combined_annotations(CHECK_(nullHandle));
guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));
if (_class_name == vmSymbols::java_lang_Object()) {
check_property(_local_interfaces == Universe::the_empty_klass_array(),
"java.lang.Object cannot implement an interface in class file %s",
CHECK_(nullHandle));
}
if (super_class_index > 0 && super_klass.is_null()) {
Symbol* sk = cp->klass_name_at(super_class_index);
if (access_flags.is_interface()) {
guarantee_property(sk == vmSymbols::java_lang_Object(),
"Interfaces must have java.lang.Object as superclass in class file %s",
CHECK_(nullHandle));
}
Klass* k = SystemDictionary::resolve_super_or_fail(class_name, sk,
class_loader,
protection_domain,
true,
CHECK_(nullHandle));
KlassHandle kh (THREAD, k);
super_klass = instanceKlassHandle(THREAD, kh());
}
if (super_klass.not_null()) {
if (super_klass->has_default_methods()) {
has_default_methods = true;
}
if (super_klass->is_interface()) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_IncompatibleClassChangeError(),
"class %s has interface %s as super class",
class_name->as_klass_external_name(),
super_klass->external_name()
);
return nullHandle;
}
if (super_klass->is_final()) {
THROW_MSG_(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class", nullHandle);
}
}
_super_klass = super_klass;
_transitive_interfaces =
compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));
intArray* method_ordering = sort_methods(methods);
access_flags.add_promoted_flags(promoted_flags.as_int());
int vtable_size = 0;
int itable_size = 0;
int num_miranda_methods = 0;
GrowableArray<Method*> all_mirandas(20);
klassVtable::compute_vtable_size_and_num_mirandas(
&vtable_size, &num_miranda_methods, &all_mirandas, super_klass(), methods,
access_flags, class_loader, class_name, local_interfaces,
CHECK_(nullHandle));
itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(_transitive_interfaces);
FieldLayoutInfo info;
layout_fields(class_loader, &fac, &parsed_annotations, &info, CHECK_NULL);
int total_oop_map_size2 =
InstanceKlass::nonstatic_oop_map_size(info.total_oop_map_count);
ReferenceType rt;
if (super_klass() == NULL) {
rt = REF_NONE;
} else {
rt = super_klass->reference_type();
}
_klass = InstanceKlass::allocate_instance_klass(loader_data,
vtable_size,
itable_size,
info.static_field_size,
total_oop_map_size2,
rt,
access_flags,
name,
super_klass(),
!host_klass.is_null(),
CHECK_(nullHandle));
instanceKlassHandle this_klass (THREAD, _klass);
assert(this_klass->static_field_size() == info.static_field_size, "sanity");
assert(this_klass->nonstatic_oop_map_count() == info.total_oop_map_count,
"sanity");
this_klass->set_should_verify_class(verify);
jint lh = Klass::instance_layout_helper(info.instance_size, false);
this_klass->set_layout_helper(lh);
assert(this_klass->oop_is_instance(), "layout is correct");
assert(this_klass->size_helper() == info.instance_size, "correct size_helper");
this_klass->set_class_loader_data(loader_data);
this_klass->set_nonstatic_field_size(info.nonstatic_field_size);
this_klass->set_has_nonstatic_fields(info.has_nonstatic_fields);
this_klass->set_static_oop_field_count(fac.count[STATIC_OOP]);
apply_parsed_class_metadata(this_klass, java_fields_count, CHECK_NULL);
if (has_final_method) {
this_klass->set_has_final_method();
}
this_klass->copy_method_ordering(method_ordering, CHECK_NULL);
this_klass->set_initial_method_idnum(methods->length());
this_klass->set_name(cp->klass_name_at(_this_class_index));
if (is_anonymous()) // I am well known to myself
cp->klass_at_put(_this_class_index, this_klass()); // eagerly resolve
this_klass->set_minor_version(minor_version);
this_klass->set_major_version(major_version);
this_klass->set_has_default_methods(has_default_methods);
this_klass->set_declares_default_methods(declares_default_methods);
if (!host_klass.is_null()) {
assert (this_klass->is_anonymous(), "should be the same");
this_klass->set_host_klass(host_klass());
}
if (Method::klass_id_for_intrinsics(this_klass()) != vmSymbols::NO_SID) {
for (int j = 0; j < methods->length(); j++) {
methods->at(j)->init_intrinsic_id();
}
}
if (cached_class_file != NULL) {
this_klass->set_cached_class_file(cached_class_file);
}
if (parsed_annotations.has_any_annotations())
parsed_annotations.apply_to(this_klass);
apply_parsed_class_attributes(this_klass);
if ((num_miranda_methods > 0) ||
(super_klass.not_null() && (super_klass->has_miranda_methods()))
) {
this_klass->set_has_miranda_methods(); // then set a flag
}
this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));
klassItable::setup_itable_offset_table(this_klass);
fill_oop_maps(this_klass, info.nonstatic_oop_map_count, info.nonstatic_oop_offsets, info.nonstatic_oop_counts);
set_precomputed_flags(this_klass);
int computed_modifiers = this_klass->compute_modifier_flags(CHECK_(nullHandle));
this_klass->set_modifier_flags(computed_modifiers);
check_super_class_access(this_klass, CHECK_(nullHandle));
check_super_interface_access(this_klass, CHECK_(nullHandle));
check_final_method_override(this_klass, CHECK_(nullHandle));
if (this_klass->is_interface()) {
if (_major_version < JAVA_8_VERSION) {
check_illegal_static_method(this_klass, CHECK_(nullHandle));
}
}
java_lang_Class::create_mirror(this_klass, class_loader, protection_domain,
CHECK_(nullHandle));
if (has_default_methods ) {
DefaultMethods::generate_default_methods(
this_klass(), &all_mirandas, CHECK_(nullHandle));
}
ClassLoadingService::notify_class_loaded(InstanceKlass::cast(this_klass()),
false /* not shared class */);
if (TraceClassLoading) {
ResourceMark rm;
if (cfs->source() != NULL) {
tty->print("[Loaded %s from %s]\n", this_klass->external_name(),
cfs->source());
} else if (class_loader.is_null()) {
Klass* caller =
THREAD->is_Java_thread()
? ((JavaThread*)THREAD)->security_get_caller_class(1)
: NULL;
if (caller != NULL) {
tty->print("[Loaded %s by instance of %s]\n",
this_klass->external_name(),
InstanceKlass::cast(caller)->external_name());
} else {
tty->print("[Loaded %s]\n", this_klass->external_name());
}
} else {
tty->print("[Loaded %s from %s]\n", this_klass->external_name(),
InstanceKlass::cast(class_loader->klass())->external_name());
}
}
if (TraceClassResolution) {
ResourceMark rm;
const char * from = this_klass()->external_name();
if (this_klass->java_super() != NULL) {
tty->print("RESOLVE %s %s (super)\n", from, InstanceKlass::cast(this_klass->java_super())->external_name());
}
Array<Klass*>* local_interfaces = this_klass->local_interfaces();
if (local_interfaces != NULL) {
int length = local_interfaces->length();
for (int i = 0; i < length; i++) {
Klass* k = local_interfaces->at(i);
InstanceKlass* to_class = InstanceKlass::cast(k);
const char * to = to_class->external_name();
tty->print("RESOLVE %s %s (interface)\n", from, to);
}
}
}
preserve_this_klass = this_klass();
}
JFR_ONLY(INIT_ID(preserve_this_klass);)
instanceKlassHandle this_klass (THREAD, preserve_this_klass);
debug_only(this_klass->verify();)
_klass = NULL;
return this_klass;
}
ClassFileParser::~ClassFileParser() {
MetadataFactory::free_metadata(_loader_data, _cp);
MetadataFactory::free_array<u2>(_loader_data, _fields);
InstanceKlass::deallocate_methods(_loader_data, _methods);
if (_inner_classes != Universe::the_empty_short_array()) {
MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
}
InstanceKlass::deallocate_interfaces(_loader_data, _super_klass(),
_local_interfaces, _transitive_interfaces);
if (_combined_annotations != NULL) {
_combined_annotations->deallocate_contents(_loader_data);
assert(_annotations == NULL, "Should have been cleared");
assert(_type_annotations == NULL, "Should have been cleared");
assert(_fields_annotations == NULL, "Should have been cleared");
assert(_fields_type_annotations == NULL, "Should have been cleared");
} else {
MetadataFactory::free_array<u1>(_loader_data, _annotations);
MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
Annotations::free_contents(_loader_data, _fields_annotations);
Annotations::free_contents(_loader_data, _fields_type_annotations);
}
clear_class_metadata();
if (_klass != NULL) {
_loader_data->add_to_deallocate_list(_klass);
}
_klass = NULL;
}
void ClassFileParser::print_field_layout(Symbol* name,
Array<u2>* fields,
constantPoolHandle cp,
int instance_size,
int instance_fields_start,
int instance_fields_end,
int static_fields_end) {
tty->print("%s: field layout\n", name->as_klass_external_name());
tty->print(" @%3d %s\n", instance_fields_start, "--- instance fields start ---");
for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
if (!fs.access_flags().is_static()) {
tty->print(" @%3d \"%s\" %s\n",
fs.offset(),
fs.name()->as_klass_external_name(),
fs.signature()->as_klass_external_name());
}
}
tty->print(" @%3d %s\n", instance_fields_end, "--- instance fields end ---");
tty->print(" @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
tty->print(" @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
if (fs.access_flags().is_static()) {
tty->print(" @%3d \"%s\" %s\n",
fs.offset(),
fs.name()->as_klass_external_name(),
fs.signature()->as_klass_external_name());
}
}
tty->print(" @%3d %s\n", static_fields_end, "--- static fields end ---");
tty->print("\n");
}
unsigned int
ClassFileParser::compute_oop_map_count(instanceKlassHandle super,
unsigned int nonstatic_oop_map_count,
int first_nonstatic_oop_offset) {
unsigned int map_count =
super.is_null() ? 0 : super->nonstatic_oop_map_count();
if (nonstatic_oop_map_count > 0) {
if (map_count == 0) {
map_count = nonstatic_oop_map_count;
} else {
OopMapBlock* const first_map = super->start_of_nonstatic_oop_maps();
OopMapBlock* const last_map = first_map + map_count - 1;
int next_offset = last_map->offset() + last_map->count() * heapOopSize;
if (next_offset == first_nonstatic_oop_offset) {
nonstatic_oop_map_count -= 1;
} else {
assert(next_offset < first_nonstatic_oop_offset, "just checking");
}
map_count += nonstatic_oop_map_count;
}
}
return map_count;
}
void ClassFileParser::fill_oop_maps(instanceKlassHandle k,
unsigned int nonstatic_oop_map_count,
int* nonstatic_oop_offsets,
unsigned int* nonstatic_oop_counts) {
OopMapBlock* this_oop_map = k->start_of_nonstatic_oop_maps();
const InstanceKlass* const super = k->superklass();
const unsigned int super_count = super ? super->nonstatic_oop_map_count() : 0;
if (super_count > 0) {
OopMapBlock* super_oop_map = super->start_of_nonstatic_oop_maps();
for (unsigned int i = 0; i < super_count; ++i) {
}
}
if (nonstatic_oop_map_count > 0) {
if (super_count + nonstatic_oop_map_count > k->nonstatic_oop_map_count()) {
nonstatic_oop_map_count--;
nonstatic_oop_offsets++;
this_oop_map--;
this_oop_map->set_count(this_oop_map->count() + *nonstatic_oop_counts++);
this_oop_map++;
}
while (nonstatic_oop_map_count-- > 0) {
this_oop_map->set_offset(*nonstatic_oop_offsets++);
this_oop_map->set_count(*nonstatic_oop_counts++);
this_oop_map++;
}
assert(k->start_of_nonstatic_oop_maps() + k->nonstatic_oop_map_count() ==
this_oop_map, "sanity");
}
}
void ClassFileParser::set_precomputed_flags(instanceKlassHandle k) {
Klass* super = k->super();
if (!_has_empty_finalizer) {
if (_has_finalizer ||
(super != NULL && super->has_finalizer())) {
k->set_has_finalizer();
}
}
#ifdef ASSERT
bool f = false;
Method* m = k->lookup_method(vmSymbols::finalize_method_name(),
vmSymbols::void_method_signature());
if (m != NULL && !m->is_empty_method()) {
f = true;
}
if (!k->has_redefined_this_or_super()) {
assert(f == k->has_finalizer(), "inconsistent has_finalizer");
}
#endif
if (SystemDictionary::Cloneable_klass_loaded()) {
if (k->is_subtype_of(SystemDictionary::Cloneable_klass())) {
k->set_is_cloneable();
}
}
if (super == NULL) {
k->set_has_vanilla_constructor();
} else {
if (super->has_vanilla_constructor() &&
_has_vanilla_constructor) {
k->set_has_vanilla_constructor();
}
#ifdef ASSERT
bool v = false;
if (super->has_vanilla_constructor()) {
Method* constructor = k->find_method(vmSymbols::object_initializer_name(
), vmSymbols::void_method_signature());
if (constructor != NULL && constructor->is_vanilla_constructor()) {
v = true;
}
}
assert(v == k->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
#endif
}
assert(k->size_helper() > 0, "layout_helper is initialized");
if ((!RegisterFinalizersAtInit && k->has_finalizer())
|| k->is_abstract() || k->is_interface()
|| (k->name() == vmSymbols::java_lang_Class() && k->class_loader() == NULL)
|| k->size_helper() >= FastAllocateSizeLimit) {
jint lh = Klass::instance_layout_helper(k->size_helper(), true);
k->set_layout_helper(lh);
}
}
void append_interfaces(GrowableArray<Klass*>* result, Array<Klass*>* ifs) {
for (int i = 0; i < ifs->length(); i++) {
Klass* e = ifs->at(i);
assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
result->append_if_missing(e);
}
}
Array<Klass*>* ClassFileParser::compute_transitive_interfaces(
instanceKlassHandle super,
Array<Klass*>* local_ifs, TRAPS) {
int max_transitive_size = 0;
int super_size = 0;
if (super.not_null()) {
super_size = super->transitive_interfaces()->length();
max_transitive_size += super_size;
}
int local_size = local_ifs->length();
for (int i = 0; i < local_size; i++) {
Klass* l = local_ifs->at(i);
max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
}
max_transitive_size += local_size;
if (max_transitive_size == 0) {
return Universe::the_empty_klass_array();
} else if (max_transitive_size == super_size) {
return super->transitive_interfaces();
} else if (max_transitive_size == local_size) {
return local_ifs;
} else {
ResourceMark rm;
GrowableArray<Klass*>* result = new GrowableArray<Klass*>(max_transitive_size);
if (super.not_null()) {
append_interfaces(result, super->transitive_interfaces());
}
for (int i = 0; i < local_ifs->length(); i++) {
Klass* l = local_ifs->at(i);
append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
}
append_interfaces(result, local_ifs);
int length = result->length();
assert(length <= max_transitive_size, "just checking");
Array<Klass*>* new_result = MetadataFactory::new_array<Klass*>(_loader_data, length, CHECK_NULL);
for (int i = 0; i < length; i++) {
Klass* e = result->at(i);
assert(e != NULL, "just checking");
new_result->at_put(i, e);
}
return new_result;
}
}
void ClassFileParser::check_super_class_access(instanceKlassHandle this_klass, TRAPS) {
Klass* super = this_klass->super();
if ((super != NULL) &&
(!Reflection::verify_class_access(this_klass(), super, false))) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_IllegalAccessError(),
"class %s cannot access its superclass %s",
this_klass->external_name(),
InstanceKlass::cast(super)->external_name()
);
return;
}
}
void ClassFileParser::check_super_interface_access(instanceKlassHandle this_klass, TRAPS) {
Array<Klass*>* local_interfaces = this_klass->local_interfaces();
int lng = local_interfaces->length();
for (int i = lng - 1; i >= 0; i--) {
Klass* k = local_interfaces->at(i);
assert (k != NULL && k->is_interface(), "invalid interface");
if (!Reflection::verify_class_access(this_klass(), k, false)) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_IllegalAccessError(),
"class %s cannot access its superinterface %s",
this_klass->external_name(),
InstanceKlass::cast(k)->external_name()
);
return;
}
}
}
void ClassFileParser::check_final_method_override(instanceKlassHandle this_klass, TRAPS) {
Array<Method*>* methods = this_klass->methods();
int num_methods = methods->length();
for (int index = 0; index < num_methods; index++) {
Method* m = methods->at(index);
if ((!m->is_private() && !m->is_static()) &&
(m->name() != vmSymbols::object_initializer_name())) {
Symbol* name = m->name();
Symbol* signature = m->signature();
Klass* k = this_klass->super();
Method* super_m = NULL;
while (k != NULL) {
if (k->has_final_method()) {
super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
if (super_m == NULL) {
break; // didn't find any match; get out
}
if (super_m->is_final() && !super_m->is_static() &&
(Reflection::verify_field_access(this_klass(),
super_m->method_holder(),
super_m->method_holder(),
super_m->access_flags(), false))
) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_VerifyError(),
"class %s overrides final method %s.%s",
this_klass->external_name(),
name->as_C_string(),
signature->as_C_string()
);
return;
}
k = super_m->method_holder()->super();
continue;
}
k = k->super();
}
}
}
}
void ClassFileParser::check_illegal_static_method(instanceKlassHandle this_klass, TRAPS) {
assert(this_klass->is_interface(), "not an interface");
Array<Method*>* methods = this_klass->methods();
int num_methods = methods->length();
for (int index = 0; index < num_methods; index++) {
Method* m = methods->at(index);
if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_VerifyError(),
"Illegal static method %s in interface %s",
m->name()->as_C_string(),
this_klass->external_name()
);
return;
}
}
}
void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) {
if (!_need_verify) { return; }
const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;
const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
const bool is_final = (flags & JVM_ACC_FINAL) != 0;
const bool is_super = (flags & JVM_ACC_SUPER) != 0;
const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
if ((is_abstract && is_final) ||
(is_interface && !is_abstract) ||
(is_interface && major_gte_15 && (is_super || is_enum)) ||
(!is_interface && major_gte_15 && is_annotation)) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"Illegal class modifiers in class %s: 0x%X",
_class_name->as_C_string(), flags
);
return;
}
}
bool ClassFileParser::has_illegal_visibility(jint flags) {
const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
return ((is_public && is_protected) ||
(is_public && is_private) ||
(is_protected && is_private));
}
bool ClassFileParser::is_supported_version(u2 major, u2 minor) {
u2 max_version =
JDK_Version::is_gte_jdk17x_version() ? JAVA_MAX_SUPPORTED_VERSION :
(JDK_Version::is_gte_jdk16x_version() ? JAVA_6_VERSION : JAVA_1_5_VERSION);
return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
(major <= max_version) &&
((major != max_version) ||
(minor <= JAVA_MAX_SUPPORTED_MINOR_VERSION));
}
void ClassFileParser::verify_legal_field_modifiers(
jint flags, bool is_interface, TRAPS) {
if (!_need_verify) { return; }
const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
const bool is_static = (flags & JVM_ACC_STATIC) != 0;
const bool is_final = (flags & JVM_ACC_FINAL) != 0;
const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0;
const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
const bool is_enum = (flags & JVM_ACC_ENUM) != 0;
const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
bool is_illegal = false;
if (is_interface) {
if (!is_public || !is_static || !is_final || is_private ||
is_protected || is_volatile || is_transient ||
(major_gte_15 && is_enum)) {
is_illegal = true;
}
} else { // not interface
if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
is_illegal = true;
}
}
if (is_illegal) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"Illegal field modifiers in class %s: 0x%X",
_class_name->as_C_string(), flags);
return;
}
}
void ClassFileParser::verify_legal_method_modifiers(
jint flags, bool is_interface, Symbol* name, TRAPS) {
if (!_need_verify) { return; }
const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;
const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;
const bool is_static = (flags & JVM_ACC_STATIC) != 0;
const bool is_final = (flags & JVM_ACC_FINAL) != 0;
const bool is_native = (flags & JVM_ACC_NATIVE) != 0;
const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;
const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0;
const bool is_strict = (flags & JVM_ACC_STRICT) != 0;
const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
const bool major_gte_8 = _major_version >= JAVA_8_VERSION;
const bool is_initializer = (name == vmSymbols::object_initializer_name());
bool is_illegal = false;
if (is_interface) {
if (major_gte_8) {
if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
(is_native || is_protected || is_final || is_synchronized) ||
(is_abstract && (is_private || is_static || is_strict))) {
is_illegal = true;
}
} else if (major_gte_15) {
if (!is_public || is_static || is_final || is_synchronized ||
is_native || !is_abstract || is_strict) {
is_illegal = true;
}
} else {
if (!is_public || is_static || is_final || is_native || !is_abstract) {
is_illegal = true;
}
}
} else { // not interface
if (is_initializer) {
if (is_static || is_final || is_synchronized || is_native ||
is_abstract || (major_gte_15 && is_bridge)) {
is_illegal = true;
}
} else { // not initializer
if (is_abstract) {
if ((is_final || is_native || is_private || is_static ||
(major_gte_15 && (is_synchronized || is_strict)))) {
is_illegal = true;
}
}
if (has_illegal_visibility(flags)) {
is_illegal = true;
}
}
}
if (is_illegal) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"Method %s in class %s has illegal modifiers: 0x%X",
name->as_C_string(), _class_name->as_C_string(), flags);
return;
}
}
void ClassFileParser::verify_legal_utf8(const unsigned char* buffer, int length, TRAPS) {
assert(_need_verify, "only called when _need_verify is true");
int i = 0;
int count = length >> 2;
for (int k=0; k<count; k++) {
unsigned char b0 = buffer[i];
unsigned char b1 = buffer[i+1];
unsigned char b2 = buffer[i+2];
unsigned char b3 = buffer[i+3];
unsigned char res = b0 | b0 - 1 |
b1 | b1 - 1 |
b2 | b2 - 1 |
b3 | b3 - 1;
if (res >= 128) break;
i += 4;
}
for(; i < length; i++) {
unsigned short c;
guarantee_property((buffer[i] != 0), "Illegal UTF8 string in constant pool in class file %s", CHECK);
if(buffer[i] < 128) {
continue;
}
if ((i + 5) < length) { // see if it's legal supplementary character
if (UTF8::is_supplementary_character(&buffer[i])) {
c = UTF8::get_supplementary_character(&buffer[i]);
i += 5;
continue;
}
}
switch (buffer[i] >> 4) {
default: break;
case 0x8: case 0x9: case 0xA: case 0xB: case 0xF:
classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
case 0xC: case 0xD: // 110xxxxx 10xxxxxx
c = (buffer[i] & 0x1F) << 6;
i++;
if ((i < length) && ((buffer[i] & 0xC0) == 0x80)) {
c += buffer[i] & 0x3F;
if (_major_version <= 47 || c == 0 || c >= 0x80) {
break;
}
}
classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
case 0xE: // 1110xxxx 10xxxxxx 10xxxxxx
c = (buffer[i] & 0xF) << 12;
i += 2;
if ((i < length) && ((buffer[i-1] & 0xC0) == 0x80) && ((buffer[i] & 0xC0) == 0x80)) {
c += ((buffer[i-1] & 0x3F) << 6) + (buffer[i] & 0x3F);
if (_major_version <= 47 || c >= 0x800) {
break;
}
}
classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
} // end of switch
} // end of for
}
void ClassFileParser::verify_legal_class_name(Symbol* name, TRAPS) {
if (!_need_verify || _relax_verify) { return; }
char buf[fixed_buffer_size];
char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
unsigned int length = name->utf8_length();
bool legal = false;
if (length > 0) {
char* p;
if (bytes[0] == JVM_SIGNATURE_ARRAY) {
p = skip_over_field_signature(bytes, false, length, CHECK);
legal = (p != NULL) && ((p - bytes) == (int)length);
} else if (_major_version < JAVA_1_5_VERSION) {
if (bytes[0] != '<') {
p = skip_over_field_name(bytes, true, length);
legal = (p != NULL) && ((p - bytes) == (int)length);
}
} else {
legal = verify_unqualified_name(bytes, length, LegalClass);
}
}
if (!legal) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"Illegal class name \"%s\" in class file %s", bytes,
_class_name->as_C_string()
);
return;
}
}
void ClassFileParser::verify_legal_field_name(Symbol* name, TRAPS) {
if (!_need_verify || _relax_verify) { return; }
char buf[fixed_buffer_size];
char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
unsigned int length = name->utf8_length();
bool legal = false;
if (length > 0) {
if (_major_version < JAVA_1_5_VERSION) {
if (bytes[0] != '<') {
char* p = skip_over_field_name(bytes, false, length);
legal = (p != NULL) && ((p - bytes) == (int)length);
}
} else {
legal = verify_unqualified_name(bytes, length, LegalField);
}
}
if (!legal) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"Illegal field name \"%s\" in class %s", bytes,
_class_name->as_C_string()
);
return;
}
}
void ClassFileParser::verify_legal_method_name(Symbol* name, TRAPS) {
if (!_need_verify || _relax_verify) { return; }
assert(name != NULL, "method name is null");
char buf[fixed_buffer_size];
char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
unsigned int length = name->utf8_length();
bool legal = false;
if (length > 0) {
if (bytes[0] == '<') {
if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
legal = true;
}
} else if (_major_version < JAVA_1_5_VERSION) {
char* p;
p = skip_over_field_name(bytes, false, length);
legal = (p != NULL) && ((p - bytes) == (int)length);
} else {
legal = verify_unqualified_name(bytes, length, LegalMethod);
}
}
if (!legal) {
ResourceMark rm(THREAD);
Exceptions::fthrow(
THREAD_AND_LOCATION,
vmSymbols::java_lang_ClassFormatError(),
"Illegal method name \"%s\" in class %s", bytes,
_class_name->as_C_string()
);
return;
}
}
void ClassFileParser::verify_legal_field_signature(Symbol* name, Symbol* signature, TRAPS) {
if (!_need_verify) { return; }
char buf[fixed_buffer_size];
char* bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
unsigned int length = signature->utf8_length();
char* p = skip_over_field_signature(bytes, false, length, CHECK);
if (p == NULL || (p - bytes) != (int)length) {
throwIllegalSignature("Field", name, signature, CHECK);
}
}
int ClassFileParser::verify_legal_method_signature(Symbol* name, Symbol* signature, TRAPS) {
if (!_need_verify) {
return -2;
}
unsigned int args_size = 0;
char buf[fixed_buffer_size];
char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
unsigned int length = signature->utf8_length();
char* nextp;
if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
length--;
nextp = skip_over_field_signature(p, false, length, CHECK_0);
while ((length > 0) && (nextp != NULL)) {
args_size++;
if (p[0] == 'J' || p[0] == 'D') {
args_size++;
}
length -= nextp - p;
p = nextp;
nextp = skip_over_field_signature(p, false, length, CHECK_0);
}
if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
length--;
if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
return args_size;
}
} else {
nextp = skip_over_field_signature(p, true, length, CHECK_0);
if (nextp && ((int)length == (nextp - p))) {
return args_size;
}
}
}
}
throwIllegalSignature("Method", name, signature, CHECK_0);
return 0;
}
bool ClassFileParser::verify_unqualified_name(
char* name, unsigned int length, int type) {
jchar ch;
for (char* p = name; p != name + length; ) {
ch = *p;
if (ch < 128) {
p++;
if (ch == '.' || ch == ';' || ch == '[' ) {
return false; // do not permit '.', ';', or '['
}
if (type != LegalClass && ch == '/') {
return false; // do not permit '/' unless it's class name
}
if (type == LegalMethod && (ch == '<' || ch == '>')) {
return false; // do not permit '<' or '>' in method names
}
} else {
char* tmp_p = UTF8::next(p, &ch);
p = tmp_p;
}
}
return true;
}
char* ClassFileParser::skip_over_field_name(char* name, bool slash_ok, unsigned int length) {
char* p;
jchar ch;
jboolean last_is_slash = false;
jboolean not_first_ch = false;
for (p = name; p != name + length; not_first_ch = true) {
char* old_p = p;
ch = *p;
if (ch < 128) {
p++;
if ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch == '_' || ch == '$') ||
(not_first_ch && ch >= '0' && ch <= '9')) {
last_is_slash = false;
continue;
}
if (slash_ok && ch == '/') {
if (last_is_slash) {
return NULL; // Don't permit consecutive slashes
}
last_is_slash = true;
continue;
}
} else {
jint unicode_ch;
char* tmp_p = UTF8::next_character(p, &unicode_ch);
p = tmp_p;
last_is_slash = false;
EXCEPTION_MARK;
instanceKlassHandle klass (THREAD, SystemDictionary::Character_klass());
JavaValue result(T_BOOLEAN);
JavaCallArguments args;
args.push_int(unicode_ch);
JavaCalls::call_static(&result,
klass,
vmSymbols::isJavaIdentifierStart_name(),
vmSymbols::int_bool_signature(),
&args,
THREAD);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
return 0;
}
if (result.get_jboolean()) {
continue;
}
if (not_first_ch) {
JavaCalls::call_static(&result,
klass,
vmSymbols::isJavaIdentifierPart_name(),
vmSymbols::int_bool_signature(),
&args,
THREAD);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
return 0;
}
if (result.get_jboolean()) {
continue;
}
}
}
return (not_first_ch) ? old_p : NULL;
}
return (not_first_ch) ? p : NULL;
}
char* ClassFileParser::skip_over_field_signature(char* signature,
bool void_ok,
unsigned int length,
TRAPS) {
unsigned int array_dim = 0;
while (length > 0) {
switch (signature[0]) {
case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
case JVM_SIGNATURE_BOOLEAN:
case JVM_SIGNATURE_BYTE:
case JVM_SIGNATURE_CHAR:
case JVM_SIGNATURE_SHORT:
case JVM_SIGNATURE_INT:
case JVM_SIGNATURE_FLOAT:
case JVM_SIGNATURE_LONG:
case JVM_SIGNATURE_DOUBLE:
return signature + 1;
case JVM_SIGNATURE_CLASS: {
if (_major_version < JAVA_1_5_VERSION) {
char* p = skip_over_field_name(signature + 1, true, --length);
if (p && (p - signature) > 1 && p[0] == ';') {
return p + 1;
}
} else {
length--;
signature++;
while (length > 0 && signature[0] != ';') {
if (signature[0] == '.') {
classfile_parse_error("Class name contains illegal character '.' in descriptor in class file %s", CHECK_0);
}
length--;
signature++;
}
if (signature[0] == ';') { return signature + 1; }
}
return NULL;
}
case JVM_SIGNATURE_ARRAY:
array_dim++;
if (array_dim > 255) {
classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
}
signature++;
length--;
void_ok = false;
break;
default:
return NULL;
}
}
return NULL;
}
#if INCLUDE_JFR
ClassFileStream* ClassFileParser::clone_stream() const {
assert(_stream != NULL, "invariant");
return _stream->clone();
}
void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
#ifdef ASSERT
if (klass != NULL) {
assert(NULL == _klass, "leaking?");
}
#endif
_klass = klass;
}
#endif // INCLUDE_JFR
C:\hotspot-69087d08d473\src\share\vm/classfile/classFileParser.hpp
#ifndef SHARE_VM_CLASSFILE_CLASSFILEPARSER_HPP
#define SHARE_VM_CLASSFILE_CLASSFILEPARSER_HPP
#include "classfile/classFileStream.hpp"
#include "memory/resourceArea.hpp"
#include "oops/oop.inline.hpp"
#include "oops/typeArrayOop.hpp"
#include "runtime/handles.inline.hpp"
#include "utilities/accessFlags.hpp"
#include "classfile/symbolTable.hpp"
class FieldAllocationCount;
class FieldLayoutInfo;
sssssssss12
最新推荐文章于 2024-10-08 10:40:47 发布