Welyab Paula
Welyab Paula

Reputation: 269

Java class file spec - double and long representation

In Java class file specification, at section about long and double representation, the document says:

The CONSTANT_Long_info and CONSTANT_Double_info represent 8-byte numeric (long and double) constants:

CONSTANT_Long_info {
    u1 tag;
    u4 high_bytes;
    u4 low_bytes;
}

CONSTANT_Double_info {
    u1 tag;
    u4 high_bytes;
    u4 low_bytes;
}

All 8-byte constants take up two entries in the constant_pool table of the class file. If a CONSTANT_Long_info or CONSTANT_Double_info structure is the item in the constant_pool table at index n, then the next usable item in the pool is located at index n+2. The constant_pool index n+1 must be valid but is considered unusable.

My doubt is what the tag of entry in constant_pool in index n+1.

Upvotes: 1

Views: 168

Answers (2)

Antimony
Antimony

Reputation: 39451

There is no tag at index n+1 because there is no constant pool entry at index n+1. It's just like index 0. There's no data for it and it skips straight to the next entry.

Upvotes: 1

Welyab Paula
Welyab Paula

Reputation: 269

By trial and error, and with help comment of tassos-bassoukos, I reach a solution. When found a constant long or double at index n, the index at n+1 is not usd, only that.

I will show with code:

List<Constant> constants = new ArrayList<>();
byte[] bytecode = ... // reads the class byte code
int constantPoolCount = getConstantPoolCount(bytecode);
int offset = getConstantPoolStartOffset(bytecode);

for(int i = 1; i < constantPoolCount; i++){
  int tag = bytecode[offset];
  offset++;

  if(tag == LONG_CONSTANT_TAG) {
    byte[] highBytes = Arrays.copyOfRange(bytecode, offset, offset+4);
    offset += 4;
    byte[] lowBytes = Arrays.copyOfRange(bytecode, offset, offset+4);
    offset += 4;

    ConstantLong c = new ConstantLong(highBytes, lowBytes);
    constants.add(c);

    // because we are at CONSTANT LONG, the entry at n+1 is not used
    constants.add(null);
    i++;

  } else if(tag == DOUBLE_CONSTANT_TAG) {
    ... // performs the same, like LONG_CONSTANT_TAG
  }

  // read more entries without skip indexes.

}

Note that constants list is indexed starting in zero, and entries in constant_pool bytecode is indexed starting in 1.

Upvotes: 0

Related Questions