text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```go package classfile /* Exceptions_attribute { u2 attribute_name_index; u4 attribute_length; u2 number_of_exceptions; u2 exception_index_table[number_of_exceptions]; } */ type ExceptionsAttribute struct { exceptionIndexTable []uint16 } func (self *ExceptionsAttribute) readInfo(reader *ClassReader) { self.exceptionIndexTable = reader.readUint16s() } func (self *ExceptionsAttribute) ExceptionIndexTable() []uint16 { return self.exceptionIndexTable } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_exceptions.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
104
```go package classfile import "fmt" type ConstantPool []ConstantInfo func readConstantPool(reader *ClassReader) ConstantPool { cpCount := int(reader.readUint16()) cp := make([]ConstantInfo, cpCount) // The constant_pool table is indexed from 1 to constant_pool_count - 1. for i := 1; i < cpCount; i++ { cp[i] = readConstantInfo(reader, cp) // path_to_url#jvms-4.4.5 // 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. switch cp[i].(type) { case *ConstantLongInfo, *ConstantDoubleInfo: i++ } } return cp } func (self ConstantPool) getConstantInfo(index uint16) ConstantInfo { if cpInfo := self[index]; cpInfo != nil { return cpInfo } panic(fmt.Errorf("Invalid constant pool index: %v!", index)) } func (self ConstantPool) getNameAndType(index uint16) (string, string) { ntInfo := self.getConstantInfo(index).(*ConstantNameAndTypeInfo) name := self.getUtf8(ntInfo.nameIndex) _type := self.getUtf8(ntInfo.descriptorIndex) return name, _type } func (self ConstantPool) getClassName(index uint16) string { classInfo := self.getConstantInfo(index).(*ConstantClassInfo) return self.getUtf8(classInfo.nameIndex) } func (self ConstantPool) getUtf8(index uint16) string { utf8Info := self.getConstantInfo(index).(*ConstantUtf8Info) return utf8Info.str } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/constant_pool.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
421
```go package classfile /* CONSTANT_NameAndType_info { u1 tag; u2 name_index; u2 descriptor_index; } */ type ConstantNameAndTypeInfo struct { nameIndex uint16 descriptorIndex uint16 } func (self *ConstantNameAndTypeInfo) readInfo(reader *ClassReader) { self.nameIndex = reader.readUint16() self.descriptorIndex = reader.readUint16() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/cp_name_and_type.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
88
```go package classfile /* Deprecated_attribute { u2 attribute_name_index; u4 attribute_length; } */ type DeprecatedAttribute struct { MarkerAttribute } /* Synthetic_attribute { u2 attribute_name_index; u4 attribute_length; } */ type SyntheticAttribute struct { MarkerAttribute } type MarkerAttribute struct{} func (self *MarkerAttribute) readInfo(reader *ClassReader) { // read nothing } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_markers.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
90
```go package classfile /* attribute_info { u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; } */ type UnparsedAttribute struct { name string length uint32 info []byte } func (self *UnparsedAttribute) readInfo(reader *ClassReader) { self.info = reader.readBytes(self.length) } func (self *UnparsedAttribute) Info() []byte { return self.info } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_unparsed.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
96
```go package classfile /* LineNumberTable_attribute { u2 attribute_name_index; u4 attribute_length; u2 line_number_table_length; { u2 start_pc; u2 line_number; } line_number_table[line_number_table_length]; } */ type LineNumberTableAttribute struct { lineNumberTable []*LineNumberTableEntry } type LineNumberTableEntry struct { startPc uint16 lineNumber uint16 } func (self *LineNumberTableAttribute) readInfo(reader *ClassReader) { lineNumberTableLength := reader.readUint16() self.lineNumberTable = make([]*LineNumberTableEntry, lineNumberTableLength) for i := range self.lineNumberTable { self.lineNumberTable[i] = &LineNumberTableEntry{ startPc: reader.readUint16(), lineNumber: reader.readUint16(), } } } func (self *LineNumberTableAttribute) GetLineNumber(pc int) int { for i := len(self.lineNumberTable) - 1; i >= 0; i-- { entry := self.lineNumberTable[i] if pc >= int(entry.startPc) { return int(entry.lineNumber) } } return -1 } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_line_number_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
255
```go package classfile /* CONSTANT_Class_info { u1 tag; u2 name_index; } */ type ConstantClassInfo struct { cp ConstantPool nameIndex uint16 } func (self *ConstantClassInfo) readInfo(reader *ClassReader) { self.nameIndex = reader.readUint16() } func (self *ConstantClassInfo) Name() string { return self.cp.getUtf8(self.nameIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/cp_class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
90
```go package classfile // Constant pool tags const ( CONSTANT_Class = 7 CONSTANT_Fieldref = 9 CONSTANT_Methodref = 10 CONSTANT_InterfaceMethodref = 11 CONSTANT_String = 8 CONSTANT_Integer = 3 CONSTANT_Float = 4 CONSTANT_Long = 5 CONSTANT_Double = 6 CONSTANT_NameAndType = 12 CONSTANT_Utf8 = 1 CONSTANT_MethodHandle = 15 CONSTANT_MethodType = 16 CONSTANT_InvokeDynamic = 18 ) /* cp_info { u1 tag; u1 info[]; } */ type ConstantInfo interface { readInfo(reader *ClassReader) } func readConstantInfo(reader *ClassReader, cp ConstantPool) ConstantInfo { tag := reader.readUint8() c := newConstantInfo(tag, cp) c.readInfo(reader) return c } // todo ugly code func newConstantInfo(tag uint8, cp ConstantPool) ConstantInfo { switch tag { case CONSTANT_Integer: return &ConstantIntegerInfo{} case CONSTANT_Float: return &ConstantFloatInfo{} case CONSTANT_Long: return &ConstantLongInfo{} case CONSTANT_Double: return &ConstantDoubleInfo{} case CONSTANT_Utf8: return &ConstantUtf8Info{} case CONSTANT_String: return &ConstantStringInfo{cp: cp} case CONSTANT_Class: return &ConstantClassInfo{cp: cp} case CONSTANT_Fieldref: return &ConstantFieldrefInfo{ConstantMemberrefInfo{cp: cp}} case CONSTANT_Methodref: return &ConstantMethodrefInfo{ConstantMemberrefInfo{cp: cp}} case CONSTANT_InterfaceMethodref: return &ConstantInterfaceMethodrefInfo{ConstantMemberrefInfo{cp: cp}} case CONSTANT_NameAndType: return &ConstantNameAndTypeInfo{} case CONSTANT_MethodType: return &ConstantMethodTypeInfo{} case CONSTANT_MethodHandle: return &ConstantMethodHandleInfo{} case CONSTANT_InvokeDynamic: return &ConstantInvokeDynamicInfo{} default: panic("java.lang.ClassFormatError: constant pool tag!") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/constant_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
468
```go package classfile import "math" /* CONSTANT_Integer_info { u1 tag; u4 bytes; } */ type ConstantIntegerInfo struct { val int32 } func (self *ConstantIntegerInfo) readInfo(reader *ClassReader) { bytes := reader.readUint32() self.val = int32(bytes) } func (self *ConstantIntegerInfo) Value() int32 { return self.val } /* CONSTANT_Float_info { u1 tag; u4 bytes; } */ type ConstantFloatInfo struct { val float32 } func (self *ConstantFloatInfo) readInfo(reader *ClassReader) { bytes := reader.readUint32() self.val = math.Float32frombits(bytes) } func (self *ConstantFloatInfo) Value() float32 { return self.val } /* CONSTANT_Long_info { u1 tag; u4 high_bytes; u4 low_bytes; } */ type ConstantLongInfo struct { val int64 } func (self *ConstantLongInfo) readInfo(reader *ClassReader) { bytes := reader.readUint64() self.val = int64(bytes) } func (self *ConstantLongInfo) Value() int64 { return self.val } /* CONSTANT_Double_info { u1 tag; u4 high_bytes; u4 low_bytes; } */ type ConstantDoubleInfo struct { val float64 } func (self *ConstantDoubleInfo) readInfo(reader *ClassReader) { bytes := reader.readUint64() self.val = math.Float64frombits(bytes) } func (self *ConstantDoubleInfo) Value() float64 { return self.val } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/cp_numeric.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
341
```go package classfile /* SourceFile_attribute { u2 attribute_name_index; u4 attribute_length; u2 sourcefile_index; } */ type SourceFileAttribute struct { cp ConstantPool sourceFileIndex uint16 } func (self *SourceFileAttribute) readInfo(reader *ClassReader) { self.sourceFileIndex = reader.readUint16() } func (self *SourceFileAttribute) FileName() string { return self.cp.getUtf8(self.sourceFileIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_source_file.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
101
```go package classfile import "fmt" /* ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_info constant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_info fields[fields_count]; u2 methods_count; method_info methods[methods_count]; u2 attributes_count; attribute_info attributes[attributes_count]; } */ type ClassFile struct { //magic uint32 minorVersion uint16 majorVersion uint16 constantPool ConstantPool accessFlags uint16 thisClass uint16 superClass uint16 interfaces []uint16 fields []*MemberInfo methods []*MemberInfo attributes []AttributeInfo } func Parse(classData []byte) (cf *ClassFile, err error) { defer func() { if r := recover(); r != nil { var ok bool err, ok = r.(error) if !ok { err = fmt.Errorf("%v", r) } } }() cr := &ClassReader{classData} cf = &ClassFile{} cf.read(cr) return } func (self *ClassFile) read(reader *ClassReader) { self.readAndCheckMagic(reader) self.readAndCheckVersion(reader) self.constantPool = readConstantPool(reader) self.accessFlags = reader.readUint16() self.thisClass = reader.readUint16() self.superClass = reader.readUint16() self.interfaces = reader.readUint16s() self.fields = readMembers(reader, self.constantPool) self.methods = readMembers(reader, self.constantPool) self.attributes = readAttributes(reader, self.constantPool) } func (self *ClassFile) readAndCheckMagic(reader *ClassReader) { magic := reader.readUint32() if magic != 0xCAFEBABE { panic("java.lang.ClassFormatError: magic!") } } func (self *ClassFile) readAndCheckVersion(reader *ClassReader) { self.minorVersion = reader.readUint16() self.majorVersion = reader.readUint16() switch self.majorVersion { case 45: return case 46, 47, 48, 49, 50, 51, 52: if self.minorVersion == 0 { return } } panic("java.lang.UnsupportedClassVersionError!") } func (self *ClassFile) MinorVersion() uint16 { return self.minorVersion } func (self *ClassFile) MajorVersion() uint16 { return self.majorVersion } func (self *ClassFile) ConstantPool() ConstantPool { return self.constantPool } func (self *ClassFile) AccessFlags() uint16 { return self.accessFlags } func (self *ClassFile) Fields() []*MemberInfo { return self.fields } func (self *ClassFile) Methods() []*MemberInfo { return self.methods } func (self *ClassFile) ClassName() string { return self.constantPool.getClassName(self.thisClass) } func (self *ClassFile) SuperClassName() string { if self.superClass > 0 { return self.constantPool.getClassName(self.superClass) } return "" } func (self *ClassFile) InterfaceNames() []string { interfaceNames := make([]string, len(self.interfaces)) for i, cpIndex := range self.interfaces { interfaceNames[i] = self.constantPool.getClassName(cpIndex) } return interfaceNames } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/class_file.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
787
```go package classfile /* ConstantValue_attribute { u2 attribute_name_index; u4 attribute_length; u2 constantvalue_index; } */ type ConstantValueAttribute struct { constantValueIndex uint16 } func (self *ConstantValueAttribute) readInfo(reader *ClassReader) { self.constantValueIndex = reader.readUint16() } func (self *ConstantValueAttribute) ConstantValueIndex() uint16 { return self.constantValueIndex } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_constant_value.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
95
```go package classfile /* LocalVariableTable_attribute { u2 attribute_name_index; u4 attribute_length; u2 local_variable_table_length; { u2 start_pc; u2 length; u2 name_index; u2 descriptor_index; u2 index; } local_variable_table[local_variable_table_length]; } */ type LocalVariableTableAttribute struct { localVariableTable []*LocalVariableTableEntry } type LocalVariableTableEntry struct { startPc uint16 length uint16 nameIndex uint16 descriptorIndex uint16 index uint16 } func (self *LocalVariableTableAttribute) readInfo(reader *ClassReader) { localVariableTableLength := reader.readUint16() self.localVariableTable = make([]*LocalVariableTableEntry, localVariableTableLength) for i := range self.localVariableTable { self.localVariableTable[i] = &LocalVariableTableEntry{ startPc: reader.readUint16(), length: reader.readUint16(), nameIndex: reader.readUint16(), descriptorIndex: reader.readUint16(), index: reader.readUint16(), } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_local_variable_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
251
```go package classfile import "encoding/binary" type ClassReader struct { data []byte } // u1 func (self *ClassReader) readUint8() uint8 { val := self.data[0] self.data = self.data[1:] return val } // u2 func (self *ClassReader) readUint16() uint16 { val := binary.BigEndian.Uint16(self.data) self.data = self.data[2:] return val } // u4 func (self *ClassReader) readUint32() uint32 { val := binary.BigEndian.Uint32(self.data) self.data = self.data[4:] return val } func (self *ClassReader) readUint64() uint64 { val := binary.BigEndian.Uint64(self.data) self.data = self.data[8:] return val } func (self *ClassReader) readUint16s() []uint16 { n := self.readUint16() s := make([]uint16, n) for i := range s { s[i] = self.readUint16() } return s } func (self *ClassReader) readBytes(n uint32) []byte { bytes := self.data[:n] self.data = self.data[n:] return bytes } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/class_reader.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
262
```go package classfile /* InnerClasses_attribute { u2 attribute_name_index; u4 attribute_length; u2 number_of_classes; { u2 inner_class_info_index; u2 outer_class_info_index; u2 inner_name_index; u2 inner_class_access_flags; } classes[number_of_classes]; } */ type InnerClassesAttribute struct { classes []*InnerClassInfo } type InnerClassInfo struct { innerClassInfoIndex uint16 outerClassInfoIndex uint16 innerNameIndex uint16 innerClassAccessFlags uint16 } func (self *InnerClassesAttribute) readInfo(reader *ClassReader) { numberOfClasses := reader.readUint16() self.classes = make([]*InnerClassInfo, numberOfClasses) for i := range self.classes { self.classes[i] = &InnerClassInfo{ innerClassInfoIndex: reader.readUint16(), outerClassInfoIndex: reader.readUint16(), innerNameIndex: reader.readUint16(), innerClassAccessFlags: reader.readUint16(), } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_inner_classes.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
238
```go package classfile /* Signature_attribute { u2 attribute_name_index; u4 attribute_length; u2 signature_index; } */ type SignatureAttribute struct { cp ConstantPool signatureIndex uint16 } func (self *SignatureAttribute) readInfo(reader *ClassReader) { self.signatureIndex = reader.readUint16() } func (self *SignatureAttribute) Signature() string { return self.cp.getUtf8(self.signatureIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_signature.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
94
```go package classfile import "fmt" import "unicode/utf16" /* CONSTANT_Utf8_info { u1 tag; u2 length; u1 bytes[length]; } */ type ConstantUtf8Info struct { str string } func (self *ConstantUtf8Info) readInfo(reader *ClassReader) { length := uint32(reader.readUint16()) bytes := reader.readBytes(length) self.str = decodeMUTF8(bytes) } func (self *ConstantUtf8Info) Str() string { return self.str } /* func decodeMUTF8(bytes []byte) string { return string(bytes) // not correct! } */ // mutf8 -> utf16 -> utf32 -> string // see java.io.DataInputStream.readUTF(DataInput) func decodeMUTF8(bytearr []byte) string { utflen := len(bytearr) chararr := make([]uint16, utflen) var c, char2, char3 uint16 count := 0 chararr_count := 0 for count < utflen { c = uint16(bytearr[count]) if c > 127 { break } count++ chararr[chararr_count] = c chararr_count++ } for count < utflen { c = uint16(bytearr[count]) switch c >> 4 { case 0, 1, 2, 3, 4, 5, 6, 7: /* 0xxxxxxx*/ count++ chararr[chararr_count] = c chararr_count++ case 12, 13: /* 110x xxxx 10xx xxxx*/ count += 2 if count > utflen { panic("malformed input: partial character at end") } char2 = uint16(bytearr[count-1]) if char2&0xC0 != 0x80 { panic(fmt.Errorf("malformed input around byte %v", count)) } chararr[chararr_count] = c&0x1F<<6 | char2&0x3F chararr_count++ case 14: /* 1110 xxxx 10xx xxxx 10xx xxxx*/ count += 3 if count > utflen { panic("malformed input: partial character at end") } char2 = uint16(bytearr[count-2]) char3 = uint16(bytearr[count-1]) if char2&0xC0 != 0x80 || char3&0xC0 != 0x80 { panic(fmt.Errorf("malformed input around byte %v", (count - 1))) } chararr[chararr_count] = c&0x0F<<12 | char2&0x3F<<6 | char3&0x3F<<0 chararr_count++ default: /* 10xx xxxx, 1111 xxxx */ panic(fmt.Errorf("malformed input around byte %v", count)) } } // The number of chars produced may be less than utflen chararr = chararr[0:chararr_count] runes := utf16.Decode(chararr) return string(runes) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/cp_utf8.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
702
```go package classfile /* Code_attribute { u2 attribute_name_index; u4 attribute_length; u2 max_stack; u2 max_locals; u4 code_length; u1 code[code_length]; u2 exception_table_length; { u2 start_pc; u2 end_pc; u2 handler_pc; u2 catch_type; } exception_table[exception_table_length]; u2 attributes_count; attribute_info attributes[attributes_count]; } */ type CodeAttribute struct { cp ConstantPool maxStack uint16 maxLocals uint16 code []byte exceptionTable []*ExceptionTableEntry attributes []AttributeInfo } func (self *CodeAttribute) readInfo(reader *ClassReader) { self.maxStack = reader.readUint16() self.maxLocals = reader.readUint16() codeLength := reader.readUint32() self.code = reader.readBytes(codeLength) self.exceptionTable = readExceptionTable(reader) self.attributes = readAttributes(reader, self.cp) } func (self *CodeAttribute) MaxStack() uint { return uint(self.maxStack) } func (self *CodeAttribute) MaxLocals() uint { return uint(self.maxLocals) } func (self *CodeAttribute) Code() []byte { return self.code } func (self *CodeAttribute) ExceptionTable() []*ExceptionTableEntry { return self.exceptionTable } type ExceptionTableEntry struct { startPc uint16 endPc uint16 handlerPc uint16 catchType uint16 } func readExceptionTable(reader *ClassReader) []*ExceptionTableEntry { exceptionTableLength := reader.readUint16() exceptionTable := make([]*ExceptionTableEntry, exceptionTableLength) for i := range exceptionTable { exceptionTable[i] = &ExceptionTableEntry{ startPc: reader.readUint16(), endPc: reader.readUint16(), handlerPc: reader.readUint16(), catchType: reader.readUint16(), } } return exceptionTable } func (self *ExceptionTableEntry) StartPc() uint16 { return self.startPc } func (self *ExceptionTableEntry) EndPc() uint16 { return self.endPc } func (self *ExceptionTableEntry) HandlerPc() uint16 { return self.handlerPc } func (self *ExceptionTableEntry) CatchType() uint16 { return self.catchType } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_code.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
524
```go package classfile /* CONSTANT_Fieldref_info { u1 tag; u2 class_index; u2 name_and_type_index; } CONSTANT_Methodref_info { u1 tag; u2 class_index; u2 name_and_type_index; } CONSTANT_InterfaceMethodref_info { u1 tag; u2 class_index; u2 name_and_type_index; } */ type ConstantFieldrefInfo struct{ ConstantMemberrefInfo } type ConstantMethodrefInfo struct{ ConstantMemberrefInfo } type ConstantInterfaceMethodrefInfo struct{ ConstantMemberrefInfo } type ConstantMemberrefInfo struct { cp ConstantPool classIndex uint16 nameAndTypeIndex uint16 } func (self *ConstantMemberrefInfo) readInfo(reader *ClassReader) { self.classIndex = reader.readUint16() self.nameAndTypeIndex = reader.readUint16() } func (self *ConstantMemberrefInfo) ClassName() string { return self.cp.getClassName(self.classIndex) } func (self *ConstantMemberrefInfo) NameAndDescriptor() (string, string) { return self.cp.getNameAndType(self.nameAndTypeIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/cp_member_ref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
241
```go package classfile var ( _attrDeprecated = &DeprecatedAttribute{} _attrSynthetic = &SyntheticAttribute{} ) /* attribute_info { u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; } */ type AttributeInfo interface { readInfo(reader *ClassReader) } func readAttributes(reader *ClassReader, cp ConstantPool) []AttributeInfo { attributesCount := reader.readUint16() attributes := make([]AttributeInfo, attributesCount) for i := range attributes { attributes[i] = readAttribute(reader, cp) } return attributes } func readAttribute(reader *ClassReader, cp ConstantPool) AttributeInfo { attrNameIndex := reader.readUint16() attrName := cp.getUtf8(attrNameIndex) attrLen := reader.readUint32() attrInfo := newAttributeInfo(attrName, attrLen, cp) attrInfo.readInfo(reader) return attrInfo } func newAttributeInfo(attrName string, attrLen uint32, cp ConstantPool) AttributeInfo { switch attrName { // case "AnnotationDefault": case "BootstrapMethods": return &BootstrapMethodsAttribute{} case "Code": return &CodeAttribute{cp: cp} case "ConstantValue": return &ConstantValueAttribute{} case "Deprecated": return _attrDeprecated case "EnclosingMethod": return &EnclosingMethodAttribute{cp: cp} case "Exceptions": return &ExceptionsAttribute{} case "InnerClasses": return &InnerClassesAttribute{} case "LineNumberTable": return &LineNumberTableAttribute{} case "LocalVariableTable": return &LocalVariableTableAttribute{} case "LocalVariableTypeTable": return &LocalVariableTypeTableAttribute{} // case "MethodParameters": // case "RuntimeInvisibleAnnotations": // case "RuntimeInvisibleParameterAnnotations": // case "RuntimeInvisibleTypeAnnotations": // case "RuntimeVisibleAnnotations": // case "RuntimeVisibleParameterAnnotations": // case "RuntimeVisibleTypeAnnotations": case "Signature": return &SignatureAttribute{cp: cp} case "SourceFile": return &SourceFileAttribute{cp: cp} // case "SourceDebugExtension": // case "StackMapTable": case "Synthetic": return _attrSynthetic default: return &UnparsedAttribute{attrName, attrLen, nil} } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attribute_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
496
```go package classfile /* CONSTANT_String_info { u1 tag; u2 string_index; } */ type ConstantStringInfo struct { cp ConstantPool stringIndex uint16 } func (self *ConstantStringInfo) readInfo(reader *ClassReader) { self.stringIndex = reader.readUint16() } func (self *ConstantStringInfo) String() string { return self.cp.getUtf8(self.stringIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/cp_string.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
90
```go package rtda /* JVM Thread pc Stack Frame LocalVars OperandStack */ type Thread struct { pc int // the address of the instruction currently being executed stack *Stack // todo } func NewThread() *Thread { return &Thread{ stack: newStack(1024), } } func (self *Thread) PC() int { return self.pc } func (self *Thread) SetPC(pc int) { self.pc = pc } func (self *Thread) PushFrame(frame *Frame) { self.stack.push(frame) } func (self *Thread) PopFrame() *Frame { return self.stack.pop() } func (self *Thread) CurrentFrame() *Frame { return self.stack.top() } func (self *Thread) NewFrame(maxLocals, maxStack uint) *Frame { return newFrame(self, maxLocals, maxStack) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/thread.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
200
```go package rtda import "math" type OperandStack struct { size uint slots []Slot } func newOperandStack(maxStack uint) *OperandStack { if maxStack > 0 { return &OperandStack{ slots: make([]Slot, maxStack), } } return nil } func (self *OperandStack) PushInt(val int32) { self.slots[self.size].num = val self.size++ } func (self *OperandStack) PopInt() int32 { self.size-- return self.slots[self.size].num } func (self *OperandStack) PushFloat(val float32) { bits := math.Float32bits(val) self.slots[self.size].num = int32(bits) self.size++ } func (self *OperandStack) PopFloat() float32 { self.size-- bits := uint32(self.slots[self.size].num) return math.Float32frombits(bits) } // long consumes two slots func (self *OperandStack) PushLong(val int64) { self.slots[self.size].num = int32(val) self.slots[self.size+1].num = int32(val >> 32) self.size += 2 } func (self *OperandStack) PopLong() int64 { self.size -= 2 low := uint32(self.slots[self.size].num) high := uint32(self.slots[self.size+1].num) return int64(high)<<32 | int64(low) } // double consumes two slots func (self *OperandStack) PushDouble(val float64) { bits := math.Float64bits(val) self.PushLong(int64(bits)) } func (self *OperandStack) PopDouble() float64 { bits := uint64(self.PopLong()) return math.Float64frombits(bits) } func (self *OperandStack) PushRef(ref *Object) { self.slots[self.size].ref = ref self.size++ } func (self *OperandStack) PopRef() *Object { self.size-- ref := self.slots[self.size].ref self.slots[self.size].ref = nil return ref } func (self *OperandStack) PushSlot(slot Slot) { self.slots[self.size] = slot self.size++ } func (self *OperandStack) PopSlot() Slot { self.size-- return self.slots[self.size] } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/operand_stack.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
501
```go package classfile /* LocalVariableTypeTable_attribute { u2 attribute_name_index; u4 attribute_length; u2 local_variable_type_table_length; { u2 start_pc; u2 length; u2 name_index; u2 signature_index; u2 index; } local_variable_type_table[local_variable_type_table_length]; } */ type LocalVariableTypeTableAttribute struct { localVariableTypeTable []*LocalVariableTypeTableEntry } type LocalVariableTypeTableEntry struct { startPc uint16 length uint16 nameIndex uint16 signatureIndex uint16 index uint16 } func (self *LocalVariableTypeTableAttribute) readInfo(reader *ClassReader) { localVariableTypeTableLength := reader.readUint16() self.localVariableTypeTable = make([]*LocalVariableTypeTableEntry, localVariableTypeTableLength) for i := range self.localVariableTypeTable { self.localVariableTypeTable[i] = &LocalVariableTypeTableEntry{ startPc: reader.readUint16(), length: reader.readUint16(), nameIndex: reader.readUint16(), signatureIndex: reader.readUint16(), index: reader.readUint16(), } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classfile/attr_local_variable_type_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
267
```go package rtda import "math" type LocalVars []Slot func newLocalVars(maxLocals uint) LocalVars { if maxLocals > 0 { return make([]Slot, maxLocals) } return nil } func (self LocalVars) SetInt(index uint, val int32) { self[index].num = val } func (self LocalVars) GetInt(index uint) int32 { return self[index].num } func (self LocalVars) SetFloat(index uint, val float32) { bits := math.Float32bits(val) self[index].num = int32(bits) } func (self LocalVars) GetFloat(index uint) float32 { bits := uint32(self[index].num) return math.Float32frombits(bits) } // long consumes two slots func (self LocalVars) SetLong(index uint, val int64) { self[index].num = int32(val) self[index+1].num = int32(val >> 32) } func (self LocalVars) GetLong(index uint) int64 { low := uint32(self[index].num) high := uint32(self[index+1].num) return int64(high)<<32 | int64(low) } // double consumes two slots func (self LocalVars) SetDouble(index uint, val float64) { bits := math.Float64bits(val) self.SetLong(index, int64(bits)) } func (self LocalVars) GetDouble(index uint) float64 { bits := uint64(self.GetLong(index)) return math.Float64frombits(bits) } func (self LocalVars) SetRef(index uint, ref *Object) { self[index].ref = ref } func (self LocalVars) GetRef(index uint) *Object { return self[index].ref } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/local_vars.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
378
```go package rtda // stack frame type Frame struct { lower *Frame // stack is implemented as linked list localVars LocalVars operandStack *OperandStack thread *Thread nextPC int // the next instruction after the call } func newFrame(thread *Thread, maxLocals, maxStack uint) *Frame { return &Frame{ thread: thread, localVars: newLocalVars(maxLocals), operandStack: newOperandStack(maxStack), } } // getters & setters func (self *Frame) LocalVars() LocalVars { return self.localVars } func (self *Frame) OperandStack() *OperandStack { return self.operandStack } func (self *Frame) Thread() *Thread { return self.thread } func (self *Frame) NextPC() int { return self.nextPC } func (self *Frame) SetNextPC(nextPC int) { self.nextPC = nextPC } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/frame.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
210
```go package rtda type Object struct { // todo } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/object.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
15
```go package rtda type Slot struct { num int32 ref *Object } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/slot.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
19
```go package classpath import "os" import "strings" // :(linux/unix) or ;(windows) const pathListSeparator = string(os.PathListSeparator) type Entry interface { // className: fully/qualified/ClassName.class readClass(className string) ([]byte, Entry, error) String() string } func newEntry(path string) Entry { if strings.Contains(path, pathListSeparator) { return newCompositeEntry(path) } if strings.HasSuffix(path, "*") { return newWildcardEntry(path) } if strings.HasSuffix(path, ".jar") || strings.HasSuffix(path, ".JAR") || strings.HasSuffix(path, ".zip") || strings.HasSuffix(path, ".ZIP") { return newZipEntry(path) } return newDirEntry(path) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classpath/entry.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
168
```go package rtda // jvm stack type Stack struct { maxSize uint size uint _top *Frame // stack is implemented as linked list } func newStack(maxSize uint) *Stack { return &Stack{ maxSize: maxSize, } } func (self *Stack) push(frame *Frame) { if self.size >= self.maxSize { panic("java.lang.StackOverflowError") } if self._top != nil { frame.lower = self._top } self._top = frame self.size++ } func (self *Stack) pop() *Frame { if self._top == nil { panic("jvm stack is empty!") } top := self._top self._top = top.lower top.lower = nil self.size-- return top } func (self *Stack) top() *Frame { if self._top == nil { panic("jvm stack is empty!") } return self._top } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/rtda/jvm_stack.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
207
```go package classpath import "errors" import "strings" type CompositeEntry []Entry func newCompositeEntry(pathList string) CompositeEntry { compositeEntry := []Entry{} for _, path := range strings.Split(pathList, pathListSeparator) { entry := newEntry(path) compositeEntry = append(compositeEntry, entry) } return compositeEntry } func (self CompositeEntry) readClass(className string) ([]byte, Entry, error) { for _, entry := range self { data, from, err := entry.readClass(className) if err == nil { return data, from, nil } } return nil, nil, errors.New("class not found: " + className) } func (self CompositeEntry) String() string { strs := make([]string, len(self)) for i, entry := range self { strs[i] = entry.String() } return strings.Join(strs, pathListSeparator) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classpath/entry_composite.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
202
```go package classpath import "os" import "path/filepath" type Classpath struct { bootClasspath Entry extClasspath Entry userClasspath Entry } func Parse(jreOption, cpOption string) *Classpath { cp := &Classpath{} cp.parseBootAndExtClasspath(jreOption) cp.parseUserClasspath(cpOption) return cp } func (self *Classpath) parseBootAndExtClasspath(jreOption string) { jreDir := getJreDir(jreOption) // jre/lib/* jreLibPath := filepath.Join(jreDir, "lib", "*") self.bootClasspath = newWildcardEntry(jreLibPath) // jre/lib/ext/* jreExtPath := filepath.Join(jreDir, "lib", "ext", "*") self.extClasspath = newWildcardEntry(jreExtPath) } func getJreDir(jreOption string) string { if jreOption != "" && exists(jreOption) { return jreOption } if exists("./jre") { return "./jre" } if jh := os.Getenv("JAVA_HOME"); jh != "" { return filepath.Join(jh, "jre") } panic("Can not find jre folder!") } func exists(path string) bool { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { return false } } return true } func (self *Classpath) parseUserClasspath(cpOption string) { if cpOption == "" { cpOption = "." } self.userClasspath = newEntry(cpOption) } // className: fully/qualified/ClassName func (self *Classpath) ReadClass(className string) ([]byte, Entry, error) { className = className + ".class" if data, entry, err := self.bootClasspath.readClass(className); err == nil { return data, entry, err } if data, entry, err := self.extClasspath.readClass(className); err == nil { return data, entry, err } return self.userClasspath.readClass(className) } func (self *Classpath) String() string { return self.userClasspath.String() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classpath/classpath.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
476
```go package classpath import "os" import "path/filepath" import "strings" func newWildcardEntry(path string) CompositeEntry { baseDir := path[:len(path)-1] // remove * compositeEntry := []Entry{} walkFn := func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() && path != baseDir { return filepath.SkipDir } if strings.HasSuffix(path, ".jar") || strings.HasSuffix(path, ".JAR") { jarEntry := newZipEntry(path) compositeEntry = append(compositeEntry, jarEntry) } return nil } filepath.Walk(baseDir, walkFn) return compositeEntry } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classpath/entry_wildcard.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
168
```go package classpath import "archive/zip" import "errors" import "io/ioutil" import "path/filepath" type ZipEntry struct { absPath string zipRC *zip.ReadCloser } func newZipEntry(path string) *ZipEntry { absPath, err := filepath.Abs(path) if err != nil { panic(err) } return &ZipEntry{absPath, nil} } func (self *ZipEntry) readClass(className string) ([]byte, Entry, error) { if self.zipRC == nil { err := self.openJar() if err != nil { return nil, nil, err } } classFile := self.findClass(className) if classFile == nil { return nil, nil, errors.New("class not found: " + className) } data, err := readClass(classFile) return data, self, err } // todo: close zip func (self *ZipEntry) openJar() error { r, err := zip.OpenReader(self.absPath) if err == nil { self.zipRC = r } return err } func (self *ZipEntry) findClass(className string) *zip.File { for _, f := range self.zipRC.File { if f.Name == className { return f } } return nil } func readClass(classFile *zip.File) ([]byte, error) { rc, err := classFile.Open() if err != nil { return nil, err } // read class data data, err := ioutil.ReadAll(rc) rc.Close() if err != nil { return nil, err } return data, nil } func (self *ZipEntry) String() string { return self.absPath } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classpath/entry_zip.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
374
```go package classpath import "io/ioutil" import "path/filepath" type DirEntry struct { absDir string } func newDirEntry(path string) *DirEntry { absDir, err := filepath.Abs(path) if err != nil { panic(err) } return &DirEntry{absDir} } func (self *DirEntry) readClass(className string) ([]byte, Entry, error) { fileName := filepath.Join(self.absDir, className) data, err := ioutil.ReadFile(fileName) return data, self, err } func (self *DirEntry) String() string { return self.absDir } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch05/classpath/entry_dir.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
131
```go package main import "flag" import "fmt" import "os" // java [-options] class [args...] type Cmd struct { helpFlag bool versionFlag bool verboseClassFlag bool verboseInstFlag bool cpOption string XjreOption string class string args []string } func parseCmd() *Cmd { cmd := &Cmd{} flag.Usage = printUsage flag.BoolVar(&cmd.helpFlag, "help", false, "print help message") flag.BoolVar(&cmd.helpFlag, "?", false, "print help message") flag.BoolVar(&cmd.versionFlag, "version", false, "print version and exit") flag.BoolVar(&cmd.verboseClassFlag, "verbose", false, "enable verbose output") flag.BoolVar(&cmd.verboseClassFlag, "verbose:class", false, "enable verbose output") flag.BoolVar(&cmd.verboseInstFlag, "verbose:inst", false, "enable verbose output") flag.StringVar(&cmd.cpOption, "classpath", "", "classpath") flag.StringVar(&cmd.cpOption, "cp", "", "classpath") flag.StringVar(&cmd.XjreOption, "Xjre", "", "path to jre") flag.Parse() args := flag.Args() if len(args) > 0 { cmd.class = args[0] cmd.args = args[1:] } return cmd } func printUsage() { fmt.Printf("Usage: %s [-options] class [args...]\n", os.Args[0]) //flag.PrintDefaults() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/cmd.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
328
```go package main import "fmt" import "strings" import "jvmgo/ch10/classpath" import "jvmgo/ch10/rtda/heap" func main() { cmd := parseCmd() if cmd.versionFlag { fmt.Println("version 0.0.1") } else if cmd.helpFlag || cmd.class == "" { printUsage() } else { startJVM(cmd) } } func startJVM(cmd *Cmd) { cp := classpath.Parse(cmd.XjreOption, cmd.cpOption) classLoader := heap.NewClassLoader(cp, cmd.verboseClassFlag) className := strings.Replace(cmd.class, ".", "/", -1) mainClass := classLoader.LoadClass(className) mainMethod := mainClass.GetMainMethod() if mainMethod != nil { interpret(mainMethod, cmd.verboseInstFlag, cmd.args) } else { fmt.Printf("Main method not found in class %s\n", cmd.class) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/main.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
202
```go package main import "fmt" import "jvmgo/ch10/instructions" import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" func interpret(method *heap.Method, logInst bool, args []string) { thread := rtda.NewThread() frame := thread.NewFrame(method) thread.PushFrame(frame) jArgs := createArgsArray(method.Class().Loader(), args) frame.LocalVars().SetRef(0, jArgs) defer catchErr(thread) loop(thread, logInst) } func createArgsArray(loader *heap.ClassLoader, args []string) *heap.Object { stringClass := loader.LoadClass("java/lang/String") argsArr := stringClass.ArrayClass().NewArray(uint(len(args))) jArgs := argsArr.Refs() for i, arg := range args { jArgs[i] = heap.JString(loader, arg) } return argsArr } func catchErr(thread *rtda.Thread) { if r := recover(); r != nil { logFrames(thread) panic(r) } } func loop(thread *rtda.Thread, logInst bool) { reader := &base.BytecodeReader{} for { frame := thread.CurrentFrame() pc := frame.NextPC() thread.SetPC(pc) // decode reader.Reset(frame.Method().Code(), pc) opcode := reader.ReadUint8() inst := instructions.NewInstruction(opcode) inst.FetchOperands(reader) frame.SetNextPC(reader.PC()) if logInst { logInstruction(frame, inst) } // execute inst.Execute(frame) if thread.IsStackEmpty() { break } } } func logInstruction(frame *rtda.Frame, inst base.Instruction) { method := frame.Method() className := method.Class().Name() methodName := method.Name() pc := frame.Thread().PC() fmt.Printf("%v.%v() #%2d %T %v\n", className, methodName, pc, inst, inst) } func logFrames(thread *rtda.Thread) { for !thread.IsStackEmpty() { frame := thread.PopFrame() method := frame.Method() className := method.Class().Name() lineNum := method.GetLineNumber(frame.NextPC()) fmt.Printf(">> line:%4d pc:%4d %v.%v%v \n", lineNum, frame.NextPC(), className, method.Name(), method.Descriptor()) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/interpreter.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
532
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Boolean AND int type IAND struct{ base.NoOperandsInstruction } func (self *IAND) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 & v2 stack.PushInt(result) } // Boolean AND long type LAND struct{ base.NoOperandsInstruction } func (self *LAND) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 & v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/and.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
158
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Add double type DADD struct{ base.NoOperandsInstruction } func (self *DADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v1 := stack.PopDouble() v2 := stack.PopDouble() result := v1 + v2 stack.PushDouble(result) } // Add float type FADD struct{ base.NoOperandsInstruction } func (self *FADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 + v2 stack.PushFloat(result) } // Add int type IADD struct{ base.NoOperandsInstruction } func (self *IADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 + v2 stack.PushInt(result) } // Add long type LADD struct{ base.NoOperandsInstruction } func (self *LADD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 + v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/add.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package math import "math" import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Remainder double type DREM struct{ base.NoOperandsInstruction } func (self *DREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := math.Mod(v1, v2) // todo stack.PushDouble(result) } // Remainder float type FREM struct{ base.NoOperandsInstruction } func (self *FREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := float32(math.Mod(float64(v1), float64(v2))) // todo stack.PushFloat(result) } // Remainder int type IREM struct{ base.NoOperandsInstruction } func (self *IREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 % v2 stack.PushInt(result) } // Remainder long type LREM struct{ base.NoOperandsInstruction } func (self *LREM) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 % v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/rem.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
358
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Shift left int type ISHL struct{ base.NoOperandsInstruction } func (self *ISHL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() s := uint32(v2) & 0x1f result := v1 << s stack.PushInt(result) } // Arithmetic shift right int type ISHR struct{ base.NoOperandsInstruction } func (self *ISHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() s := uint32(v2) & 0x1f result := v1 >> s stack.PushInt(result) } // Logical shift right int type IUSHR struct{ base.NoOperandsInstruction } func (self *IUSHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() s := uint32(v2) & 0x1f result := int32(uint32(v1) >> s) stack.PushInt(result) } // Shift left long type LSHL struct{ base.NoOperandsInstruction } func (self *LSHL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopLong() s := uint32(v2) & 0x3f result := v1 << s stack.PushLong(result) } // Arithmetic shift right long type LSHR struct{ base.NoOperandsInstruction } func (self *LSHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopLong() s := uint32(v2) & 0x3f result := v1 >> s stack.PushLong(result) } // Logical shift right long type LUSHR struct{ base.NoOperandsInstruction } func (self *LUSHR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopLong() s := uint32(v2) & 0x3f result := int64(uint64(v1) >> s) stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/sh.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
526
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Boolean OR int type IOR struct{ base.NoOperandsInstruction } func (self *IOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 | v2 stack.PushInt(result) } // Boolean OR long type LOR struct{ base.NoOperandsInstruction } func (self *LOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 | v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/or.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
159
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Divide double type DDIV struct{ base.NoOperandsInstruction } func (self *DDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := v1 / v2 stack.PushDouble(result) } // Divide float type FDIV struct{ base.NoOperandsInstruction } func (self *FDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 / v2 stack.PushFloat(result) } // Divide int type IDIV struct{ base.NoOperandsInstruction } func (self *IDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 / v2 stack.PushInt(result) } // Divide long type LDIV struct{ base.NoOperandsInstruction } func (self *LDIV) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() if v2 == 0 { panic("java.lang.ArithmeticException: / by zero") } result := v1 / v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/div.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
334
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Subtract double type DSUB struct{ base.NoOperandsInstruction } func (self *DSUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := v1 - v2 stack.PushDouble(result) } // Subtract float type FSUB struct{ base.NoOperandsInstruction } func (self *FSUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 - v2 stack.PushFloat(result) } // Subtract int type ISUB struct{ base.NoOperandsInstruction } func (self *ISUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 - v2 stack.PushInt(result) } // Subtract long type LSUB struct{ base.NoOperandsInstruction } func (self *LSUB) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 - v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/sub.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Negate double type DNEG struct{ base.NoOperandsInstruction } func (self *DNEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopDouble() stack.PushDouble(-val) } // Negate float type FNEG struct{ base.NoOperandsInstruction } func (self *FNEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopFloat() stack.PushFloat(-val) } // Negate int type INEG struct{ base.NoOperandsInstruction } func (self *INEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() stack.PushInt(-val) } // Negate long type LNEG struct{ base.NoOperandsInstruction } func (self *LNEG) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopLong() stack.PushLong(-val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/neg.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
234
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Boolean XOR int type IXOR struct{ base.NoOperandsInstruction } func (self *IXOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v1 := stack.PopInt() v2 := stack.PopInt() result := v1 ^ v2 stack.PushInt(result) } // Boolean XOR long type LXOR struct{ base.NoOperandsInstruction } func (self *LXOR) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v1 := stack.PopLong() v2 := stack.PopLong() result := v1 ^ v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/xor.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
161
```go package instructions import "fmt" import "jvmgo/ch10/instructions/base" import . "jvmgo/ch10/instructions/comparisons" import . "jvmgo/ch10/instructions/constants" import . "jvmgo/ch10/instructions/control" import . "jvmgo/ch10/instructions/conversions" import . "jvmgo/ch10/instructions/extended" import . "jvmgo/ch10/instructions/loads" import . "jvmgo/ch10/instructions/math" import . "jvmgo/ch10/instructions/references" import . "jvmgo/ch10/instructions/reserved" import . "jvmgo/ch10/instructions/stack" import . "jvmgo/ch10/instructions/stores" // NoOperandsInstruction singletons var ( nop = &NOP{} aconst_null = &ACONST_NULL{} iconst_m1 = &ICONST_M1{} iconst_0 = &ICONST_0{} iconst_1 = &ICONST_1{} iconst_2 = &ICONST_2{} iconst_3 = &ICONST_3{} iconst_4 = &ICONST_4{} iconst_5 = &ICONST_5{} lconst_0 = &LCONST_0{} lconst_1 = &LCONST_1{} fconst_0 = &FCONST_0{} fconst_1 = &FCONST_1{} fconst_2 = &FCONST_2{} dconst_0 = &DCONST_0{} dconst_1 = &DCONST_1{} iload_0 = &ILOAD_0{} iload_1 = &ILOAD_1{} iload_2 = &ILOAD_2{} iload_3 = &ILOAD_3{} lload_0 = &LLOAD_0{} lload_1 = &LLOAD_1{} lload_2 = &LLOAD_2{} lload_3 = &LLOAD_3{} fload_0 = &FLOAD_0{} fload_1 = &FLOAD_1{} fload_2 = &FLOAD_2{} fload_3 = &FLOAD_3{} dload_0 = &DLOAD_0{} dload_1 = &DLOAD_1{} dload_2 = &DLOAD_2{} dload_3 = &DLOAD_3{} aload_0 = &ALOAD_0{} aload_1 = &ALOAD_1{} aload_2 = &ALOAD_2{} aload_3 = &ALOAD_3{} iaload = &IALOAD{} laload = &LALOAD{} faload = &FALOAD{} daload = &DALOAD{} aaload = &AALOAD{} baload = &BALOAD{} caload = &CALOAD{} saload = &SALOAD{} istore_0 = &ISTORE_0{} istore_1 = &ISTORE_1{} istore_2 = &ISTORE_2{} istore_3 = &ISTORE_3{} lstore_0 = &LSTORE_0{} lstore_1 = &LSTORE_1{} lstore_2 = &LSTORE_2{} lstore_3 = &LSTORE_3{} fstore_0 = &FSTORE_0{} fstore_1 = &FSTORE_1{} fstore_2 = &FSTORE_2{} fstore_3 = &FSTORE_3{} dstore_0 = &DSTORE_0{} dstore_1 = &DSTORE_1{} dstore_2 = &DSTORE_2{} dstore_3 = &DSTORE_3{} astore_0 = &ASTORE_0{} astore_1 = &ASTORE_1{} astore_2 = &ASTORE_2{} astore_3 = &ASTORE_3{} iastore = &IASTORE{} lastore = &LASTORE{} fastore = &FASTORE{} dastore = &DASTORE{} aastore = &AASTORE{} bastore = &BASTORE{} castore = &CASTORE{} sastore = &SASTORE{} pop = &POP{} pop2 = &POP2{} dup = &DUP{} dup_x1 = &DUP_X1{} dup_x2 = &DUP_X2{} dup2 = &DUP2{} dup2_x1 = &DUP2_X1{} dup2_x2 = &DUP2_X2{} swap = &SWAP{} iadd = &IADD{} ladd = &LADD{} fadd = &FADD{} dadd = &DADD{} isub = &ISUB{} lsub = &LSUB{} fsub = &FSUB{} dsub = &DSUB{} imul = &IMUL{} lmul = &LMUL{} fmul = &FMUL{} dmul = &DMUL{} idiv = &IDIV{} ldiv = &LDIV{} fdiv = &FDIV{} ddiv = &DDIV{} irem = &IREM{} lrem = &LREM{} frem = &FREM{} drem = &DREM{} ineg = &INEG{} lneg = &LNEG{} fneg = &FNEG{} dneg = &DNEG{} ishl = &ISHL{} lshl = &LSHL{} ishr = &ISHR{} lshr = &LSHR{} iushr = &IUSHR{} lushr = &LUSHR{} iand = &IAND{} land = &LAND{} ior = &IOR{} lor = &LOR{} ixor = &IXOR{} lxor = &LXOR{} i2l = &I2L{} i2f = &I2F{} i2d = &I2D{} l2i = &L2I{} l2f = &L2F{} l2d = &L2D{} f2i = &F2I{} f2l = &F2L{} f2d = &F2D{} d2i = &D2I{} d2l = &D2L{} d2f = &D2F{} i2b = &I2B{} i2c = &I2C{} i2s = &I2S{} lcmp = &LCMP{} fcmpl = &FCMPL{} fcmpg = &FCMPG{} dcmpl = &DCMPL{} dcmpg = &DCMPG{} ireturn = &IRETURN{} lreturn = &LRETURN{} freturn = &FRETURN{} dreturn = &DRETURN{} areturn = &ARETURN{} _return = &RETURN{} arraylength = &ARRAY_LENGTH{} athrow = &ATHROW{} // monitorenter = &MONITOR_ENTER{} // monitorexit = &MONITOR_EXIT{} invoke_native = &INVOKE_NATIVE{} ) func NewInstruction(opcode byte) base.Instruction { switch opcode { case 0x00: return nop case 0x01: return aconst_null case 0x02: return iconst_m1 case 0x03: return iconst_0 case 0x04: return iconst_1 case 0x05: return iconst_2 case 0x06: return iconst_3 case 0x07: return iconst_4 case 0x08: return iconst_5 case 0x09: return lconst_0 case 0x0a: return lconst_1 case 0x0b: return fconst_0 case 0x0c: return fconst_1 case 0x0d: return fconst_2 case 0x0e: return dconst_0 case 0x0f: return dconst_1 case 0x10: return &BIPUSH{} case 0x11: return &SIPUSH{} case 0x12: return &LDC{} case 0x13: return &LDC_W{} case 0x14: return &LDC2_W{} case 0x15: return &ILOAD{} case 0x16: return &LLOAD{} case 0x17: return &FLOAD{} case 0x18: return &DLOAD{} case 0x19: return &ALOAD{} case 0x1a: return iload_0 case 0x1b: return iload_1 case 0x1c: return iload_2 case 0x1d: return iload_3 case 0x1e: return lload_0 case 0x1f: return lload_1 case 0x20: return lload_2 case 0x21: return lload_3 case 0x22: return fload_0 case 0x23: return fload_1 case 0x24: return fload_2 case 0x25: return fload_3 case 0x26: return dload_0 case 0x27: return dload_1 case 0x28: return dload_2 case 0x29: return dload_3 case 0x2a: return aload_0 case 0x2b: return aload_1 case 0x2c: return aload_2 case 0x2d: return aload_3 case 0x2e: return iaload case 0x2f: return laload case 0x30: return faload case 0x31: return daload case 0x32: return aaload case 0x33: return baload case 0x34: return caload case 0x35: return saload case 0x36: return &ISTORE{} case 0x37: return &LSTORE{} case 0x38: return &FSTORE{} case 0x39: return &DSTORE{} case 0x3a: return &ASTORE{} case 0x3b: return istore_0 case 0x3c: return istore_1 case 0x3d: return istore_2 case 0x3e: return istore_3 case 0x3f: return lstore_0 case 0x40: return lstore_1 case 0x41: return lstore_2 case 0x42: return lstore_3 case 0x43: return fstore_0 case 0x44: return fstore_1 case 0x45: return fstore_2 case 0x46: return fstore_3 case 0x47: return dstore_0 case 0x48: return dstore_1 case 0x49: return dstore_2 case 0x4a: return dstore_3 case 0x4b: return astore_0 case 0x4c: return astore_1 case 0x4d: return astore_2 case 0x4e: return astore_3 case 0x4f: return iastore case 0x50: return lastore case 0x51: return fastore case 0x52: return dastore case 0x53: return aastore case 0x54: return bastore case 0x55: return castore case 0x56: return sastore case 0x57: return pop case 0x58: return pop2 case 0x59: return dup case 0x5a: return dup_x1 case 0x5b: return dup_x2 case 0x5c: return dup2 case 0x5d: return dup2_x1 case 0x5e: return dup2_x2 case 0x5f: return swap case 0x60: return iadd case 0x61: return ladd case 0x62: return fadd case 0x63: return dadd case 0x64: return isub case 0x65: return lsub case 0x66: return fsub case 0x67: return dsub case 0x68: return imul case 0x69: return lmul case 0x6a: return fmul case 0x6b: return dmul case 0x6c: return idiv case 0x6d: return ldiv case 0x6e: return fdiv case 0x6f: return ddiv case 0x70: return irem case 0x71: return lrem case 0x72: return frem case 0x73: return drem case 0x74: return ineg case 0x75: return lneg case 0x76: return fneg case 0x77: return dneg case 0x78: return ishl case 0x79: return lshl case 0x7a: return ishr case 0x7b: return lshr case 0x7c: return iushr case 0x7d: return lushr case 0x7e: return iand case 0x7f: return land case 0x80: return ior case 0x81: return lor case 0x82: return ixor case 0x83: return lxor case 0x84: return &IINC{} case 0x85: return i2l case 0x86: return i2f case 0x87: return i2d case 0x88: return l2i case 0x89: return l2f case 0x8a: return l2d case 0x8b: return f2i case 0x8c: return f2l case 0x8d: return f2d case 0x8e: return d2i case 0x8f: return d2l case 0x90: return d2f case 0x91: return i2b case 0x92: return i2c case 0x93: return i2s case 0x94: return lcmp case 0x95: return fcmpl case 0x96: return fcmpg case 0x97: return dcmpl case 0x98: return dcmpg case 0x99: return &IFEQ{} case 0x9a: return &IFNE{} case 0x9b: return &IFLT{} case 0x9c: return &IFGE{} case 0x9d: return &IFGT{} case 0x9e: return &IFLE{} case 0x9f: return &IF_ICMPEQ{} case 0xa0: return &IF_ICMPNE{} case 0xa1: return &IF_ICMPLT{} case 0xa2: return &IF_ICMPGE{} case 0xa3: return &IF_ICMPGT{} case 0xa4: return &IF_ICMPLE{} case 0xa5: return &IF_ACMPEQ{} case 0xa6: return &IF_ACMPNE{} case 0xa7: return &GOTO{} // case 0xa8: // return &JSR{} // case 0xa9: // return &RET{} case 0xaa: return &TABLE_SWITCH{} case 0xab: return &LOOKUP_SWITCH{} case 0xac: return ireturn case 0xad: return lreturn case 0xae: return freturn case 0xaf: return dreturn case 0xb0: return areturn case 0xb1: return _return case 0xb2: return &GET_STATIC{} case 0xb3: return &PUT_STATIC{} case 0xb4: return &GET_FIELD{} case 0xb5: return &PUT_FIELD{} case 0xb6: return &INVOKE_VIRTUAL{} case 0xb7: return &INVOKE_SPECIAL{} case 0xb8: return &INVOKE_STATIC{} case 0xb9: return &INVOKE_INTERFACE{} // case 0xba: // return &INVOKE_DYNAMIC{} case 0xbb: return &NEW{} case 0xbc: return &NEW_ARRAY{} case 0xbd: return &ANEW_ARRAY{} case 0xbe: return arraylength case 0xbf: return athrow case 0xc0: return &CHECK_CAST{} case 0xc1: return &INSTANCE_OF{} // case 0xc2: // return monitorenter // case 0xc3: // return monitorexit case 0xc4: return &WIDE{} case 0xc5: return &MULTI_ANEW_ARRAY{} case 0xc6: return &IFNULL{} case 0xc7: return &IFNONNULL{} case 0xc8: return &GOTO_W{} // case 0xc9: // return &JSR_W{} // case 0xca: breakpoint case 0xfe: return invoke_native // case 0xff: impdep2 default: panic(fmt.Errorf("Unsupported opcode: 0x%x!", opcode)) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/factory.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
4,248
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Increment local variable by constant type IINC struct { Index uint Const int32 } func (self *IINC) FetchOperands(reader *base.BytecodeReader) { self.Index = uint(reader.ReadUint8()) self.Const = int32(reader.ReadInt8()) } func (self *IINC) Execute(frame *rtda.Frame) { localVars := frame.LocalVars() val := localVars.GetInt(self.Index) val += self.Const localVars.SetInt(self.Index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/iinc.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
132
```go package math import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Multiply double type DMUL struct{ base.NoOperandsInstruction } func (self *DMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() result := v1 * v2 stack.PushDouble(result) } // Multiply float type FMUL struct{ base.NoOperandsInstruction } func (self *FMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() result := v1 * v2 stack.PushFloat(result) } // Multiply int type IMUL struct{ base.NoOperandsInstruction } func (self *IMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopInt() v1 := stack.PopInt() result := v1 * v2 stack.PushInt(result) } // Multiply long type LMUL struct{ base.NoOperandsInstruction } func (self *LMUL) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() result := v1 * v2 stack.PushLong(result) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/math/mul.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package stores import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Store float into local variable type FSTORE struct{ base.Index8Instruction } func (self *FSTORE) Execute(frame *rtda.Frame) { _fstore(frame, uint(self.Index)) } type FSTORE_0 struct{ base.NoOperandsInstruction } func (self *FSTORE_0) Execute(frame *rtda.Frame) { _fstore(frame, 0) } type FSTORE_1 struct{ base.NoOperandsInstruction } func (self *FSTORE_1) Execute(frame *rtda.Frame) { _fstore(frame, 1) } type FSTORE_2 struct{ base.NoOperandsInstruction } func (self *FSTORE_2) Execute(frame *rtda.Frame) { _fstore(frame, 2) } type FSTORE_3 struct{ base.NoOperandsInstruction } func (self *FSTORE_3) Execute(frame *rtda.Frame) { _fstore(frame, 3) } func _fstore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopFloat() frame.LocalVars().SetFloat(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stores/fstore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package stores import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Store into reference array type AASTORE struct{ base.NoOperandsInstruction } func (self *AASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() ref := stack.PopRef() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) refs := arrRef.Refs() checkIndex(len(refs), index) refs[index] = ref } // Store into byte or boolean array type BASTORE struct{ base.NoOperandsInstruction } func (self *BASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) bytes := arrRef.Bytes() checkIndex(len(bytes), index) bytes[index] = int8(val) } // Store into char array type CASTORE struct{ base.NoOperandsInstruction } func (self *CASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) chars := arrRef.Chars() checkIndex(len(chars), index) chars[index] = uint16(val) } // Store into double array type DASTORE struct{ base.NoOperandsInstruction } func (self *DASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopDouble() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) doubles := arrRef.Doubles() checkIndex(len(doubles), index) doubles[index] = float64(val) } // Store into float array type FASTORE struct{ base.NoOperandsInstruction } func (self *FASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopFloat() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) floats := arrRef.Floats() checkIndex(len(floats), index) floats[index] = float32(val) } // Store into int array type IASTORE struct{ base.NoOperandsInstruction } func (self *IASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) ints := arrRef.Ints() checkIndex(len(ints), index) ints[index] = int32(val) } // Store into long array type LASTORE struct{ base.NoOperandsInstruction } func (self *LASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopLong() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) longs := arrRef.Longs() checkIndex(len(longs), index) longs[index] = int64(val) } // Store into short array type SASTORE struct{ base.NoOperandsInstruction } func (self *SASTORE) Execute(frame *rtda.Frame) { stack := frame.OperandStack() val := stack.PopInt() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) shorts := arrRef.Shorts() checkIndex(len(shorts), index) shorts[index] = int16(val) } func checkNotNil(ref *heap.Object) { if ref == nil { panic("java.lang.NullPointerException") } } func checkIndex(arrLen int, index int32) { if index < 0 || index >= int32(arrLen) { panic("ArrayIndexOutOfBoundsException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stores/xastore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
823
```go package stores import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Store double into local variable type DSTORE struct{ base.Index8Instruction } func (self *DSTORE) Execute(frame *rtda.Frame) { _dstore(frame, uint(self.Index)) } type DSTORE_0 struct{ base.NoOperandsInstruction } func (self *DSTORE_0) Execute(frame *rtda.Frame) { _dstore(frame, 0) } type DSTORE_1 struct{ base.NoOperandsInstruction } func (self *DSTORE_1) Execute(frame *rtda.Frame) { _dstore(frame, 1) } type DSTORE_2 struct{ base.NoOperandsInstruction } func (self *DSTORE_2) Execute(frame *rtda.Frame) { _dstore(frame, 2) } type DSTORE_3 struct{ base.NoOperandsInstruction } func (self *DSTORE_3) Execute(frame *rtda.Frame) { _dstore(frame, 3) } func _dstore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopDouble() frame.LocalVars().SetDouble(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stores/dstore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package stores import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Store reference into local variable type ASTORE struct{ base.Index8Instruction } func (self *ASTORE) Execute(frame *rtda.Frame) { _astore(frame, uint(self.Index)) } type ASTORE_0 struct{ base.NoOperandsInstruction } func (self *ASTORE_0) Execute(frame *rtda.Frame) { _astore(frame, 0) } type ASTORE_1 struct{ base.NoOperandsInstruction } func (self *ASTORE_1) Execute(frame *rtda.Frame) { _astore(frame, 1) } type ASTORE_2 struct{ base.NoOperandsInstruction } func (self *ASTORE_2) Execute(frame *rtda.Frame) { _astore(frame, 2) } type ASTORE_3 struct{ base.NoOperandsInstruction } func (self *ASTORE_3) Execute(frame *rtda.Frame) { _astore(frame, 3) } func _astore(frame *rtda.Frame, index uint) { ref := frame.OperandStack().PopRef() frame.LocalVars().SetRef(index, ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stores/astore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package stores import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Store int into local variable type ISTORE struct{ base.Index8Instruction } func (self *ISTORE) Execute(frame *rtda.Frame) { _istore(frame, uint(self.Index)) } type ISTORE_0 struct{ base.NoOperandsInstruction } func (self *ISTORE_0) Execute(frame *rtda.Frame) { _istore(frame, 0) } type ISTORE_1 struct{ base.NoOperandsInstruction } func (self *ISTORE_1) Execute(frame *rtda.Frame) { _istore(frame, 1) } type ISTORE_2 struct{ base.NoOperandsInstruction } func (self *ISTORE_2) Execute(frame *rtda.Frame) { _istore(frame, 2) } type ISTORE_3 struct{ base.NoOperandsInstruction } func (self *ISTORE_3) Execute(frame *rtda.Frame) { _istore(frame, 3) } func _istore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopInt() frame.LocalVars().SetInt(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stores/istore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
270
```go package stores import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Store long into local variable type LSTORE struct{ base.Index8Instruction } func (self *LSTORE) Execute(frame *rtda.Frame) { _lstore(frame, uint(self.Index)) } type LSTORE_0 struct{ base.NoOperandsInstruction } func (self *LSTORE_0) Execute(frame *rtda.Frame) { _lstore(frame, 0) } type LSTORE_1 struct{ base.NoOperandsInstruction } func (self *LSTORE_1) Execute(frame *rtda.Frame) { _lstore(frame, 1) } type LSTORE_2 struct{ base.NoOperandsInstruction } func (self *LSTORE_2) Execute(frame *rtda.Frame) { _lstore(frame, 2) } type LSTORE_3 struct{ base.NoOperandsInstruction } func (self *LSTORE_3) Execute(frame *rtda.Frame) { _lstore(frame, 3) } func _lstore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopLong() frame.LocalVars().SetLong(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stores/lstore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package base import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // jvms 5.5 func InitClass(thread *rtda.Thread, class *heap.Class) { class.StartInit() scheduleClinit(thread, class) initSuperClass(thread, class) } func scheduleClinit(thread *rtda.Thread, class *heap.Class) { clinit := class.GetClinitMethod() if clinit != nil && clinit.Class() == class { // exec <clinit> newFrame := thread.NewFrame(clinit) thread.PushFrame(newFrame) } } func initSuperClass(thread *rtda.Thread, class *heap.Class) { if !class.IsInterface() { superClass := class.SuperClass() if superClass != nil && !superClass.InitStarted() { InitClass(thread, superClass) } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/base/class_init_logic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
199
```go package base import "jvmgo/ch10/rtda" func Branch(frame *rtda.Frame, offset int) { pc := frame.Thread().PC() nextPC := pc + offset frame.SetNextPC(nextPC) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/base/branch_logic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
50
```go package base import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" func InvokeMethod(invokerFrame *rtda.Frame, method *heap.Method) { thread := invokerFrame.Thread() newFrame := thread.NewFrame(method) thread.PushFrame(newFrame) argSlotCount := int(method.ArgSlotCount()) if argSlotCount > 0 { for i := argSlotCount - 1; i >= 0; i-- { slot := invokerFrame.OperandStack().PopSlot() newFrame.LocalVars().SetSlot(uint(i), slot) } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/base/method_invoke_logic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
136
```go package base import "jvmgo/ch10/rtda" type Instruction interface { FetchOperands(reader *BytecodeReader) Execute(frame *rtda.Frame) } type NoOperandsInstruction struct { // empty } func (self *NoOperandsInstruction) FetchOperands(reader *BytecodeReader) { // nothing to do } type BranchInstruction struct { Offset int } func (self *BranchInstruction) FetchOperands(reader *BytecodeReader) { self.Offset = int(reader.ReadInt16()) } type Index8Instruction struct { Index uint } func (self *Index8Instruction) FetchOperands(reader *BytecodeReader) { self.Index = uint(reader.ReadUint8()) } type Index16Instruction struct { Index uint } func (self *Index16Instruction) FetchOperands(reader *BytecodeReader) { self.Index = uint(reader.ReadUint16()) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/base/instruction.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
191
```go package base type BytecodeReader struct { code []byte // bytecodes pc int } func (self *BytecodeReader) Reset(code []byte, pc int) { self.code = code self.pc = pc } func (self *BytecodeReader) PC() int { return self.pc } func (self *BytecodeReader) ReadInt8() int8 { return int8(self.ReadUint8()) } func (self *BytecodeReader) ReadUint8() uint8 { i := self.code[self.pc] self.pc++ return i } func (self *BytecodeReader) ReadInt16() int16 { return int16(self.ReadUint16()) } func (self *BytecodeReader) ReadUint16() uint16 { byte1 := uint16(self.ReadUint8()) byte2 := uint16(self.ReadUint8()) return (byte1 << 8) | byte2 } func (self *BytecodeReader) ReadInt32() int32 { byte1 := int32(self.ReadUint8()) byte2 := int32(self.ReadUint8()) byte3 := int32(self.ReadUint8()) byte4 := int32(self.ReadUint8()) return (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4 } // used by lookupswitch and tableswitch func (self *BytecodeReader) ReadInt32s(n int32) []int32 { ints := make([]int32, n) for i := range ints { ints[i] = self.ReadInt32() } return ints } // used by lookupswitch and tableswitch func (self *BytecodeReader) SkipPadding() { for self.pc%4 != 0 { self.ReadUint8() } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/base/bytecode_reader.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
376
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Invoke a class (static) method type INVOKE_STATIC struct{ base.Index16Instruction } func (self *INVOKE_STATIC) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() methodRef := cp.GetConstant(self.Index).(*heap.MethodRef) resolvedMethod := methodRef.ResolvedMethod() if !resolvedMethod.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } class := resolvedMethod.Class() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } base.InvokeMethod(frame, resolvedMethod) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/invokestatic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
174
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Get static field from class type GET_STATIC struct{ base.Index16Instruction } func (self *GET_STATIC) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() class := field.Class() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } if !field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } descriptor := field.Descriptor() slotId := field.SlotId() slots := class.StaticVars() stack := frame.OperandStack() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': stack.PushInt(slots.GetInt(slotId)) case 'F': stack.PushFloat(slots.GetFloat(slotId)) case 'J': stack.PushLong(slots.GetLong(slotId)) case 'D': stack.PushDouble(slots.GetDouble(slotId)) case 'L', '[': stack.PushRef(slots.GetRef(slotId)) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/getstatic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Check whether object is of given type type CHECK_CAST struct{ base.Index16Instruction } func (self *CHECK_CAST) Execute(frame *rtda.Frame) { stack := frame.OperandStack() ref := stack.PopRef() stack.PushRef(ref) if ref == nil { return } cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) class := classRef.ResolvedClass() if !ref.IsInstanceOf(class) { panic("java.lang.ClassCastException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/checkcast.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
153
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Invoke interface method type INVOKE_INTERFACE struct { index uint // count uint8 // zero uint8 } func (self *INVOKE_INTERFACE) FetchOperands(reader *base.BytecodeReader) { self.index = uint(reader.ReadUint16()) reader.ReadUint8() // count reader.ReadUint8() // must be 0 } func (self *INVOKE_INTERFACE) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() methodRef := cp.GetConstant(self.index).(*heap.InterfaceMethodRef) resolvedMethod := methodRef.ResolvedInterfaceMethod() if resolvedMethod.IsStatic() || resolvedMethod.IsPrivate() { panic("java.lang.IncompatibleClassChangeError") } ref := frame.OperandStack().GetRefFromTop(resolvedMethod.ArgSlotCount() - 1) if ref == nil { panic("java.lang.NullPointerException") // todo } if !ref.Class().IsImplements(methodRef.ResolvedClass()) { panic("java.lang.IncompatibleClassChangeError") } methodToBeInvoked := heap.LookupMethodInClass(ref.Class(), methodRef.Name(), methodRef.Descriptor()) if methodToBeInvoked == nil || methodToBeInvoked.IsAbstract() { panic("java.lang.AbstractMethodError") } if !methodToBeInvoked.IsPublic() { panic("java.lang.IllegalAccessError") } base.InvokeMethod(frame, methodToBeInvoked) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/invokeinterface.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
349
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Get length of array type ARRAY_LENGTH struct{ base.NoOperandsInstruction } func (self *ARRAY_LENGTH) Execute(frame *rtda.Frame) { stack := frame.OperandStack() arrRef := stack.PopRef() if arrRef == nil { panic("java.lang.NullPointerException") } arrLen := arrRef.ArrayLength() stack.PushInt(arrLen) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/arraylength.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
104
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Determine if object is of given type type INSTANCE_OF struct{ base.Index16Instruction } func (self *INSTANCE_OF) Execute(frame *rtda.Frame) { stack := frame.OperandStack() ref := stack.PopRef() if ref == nil { stack.PushInt(0) return } cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) class := classRef.ResolvedClass() if ref.IsInstanceOf(class) { stack.PushInt(1) } else { stack.PushInt(0) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/instanceof.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
164
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Fetch field from object type GET_FIELD struct{ base.Index16Instruction } func (self *GET_FIELD) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() if field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } stack := frame.OperandStack() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } descriptor := field.Descriptor() slotId := field.SlotId() slots := ref.Fields() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': stack.PushInt(slots.GetInt(slotId)) case 'F': stack.PushFloat(slots.GetFloat(slotId)) case 'J': stack.PushLong(slots.GetLong(slotId)) case 'D': stack.PushDouble(slots.GetDouble(slotId)) case 'L', '[': stack.PushRef(slots.GetRef(slotId)) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/getfield.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
275
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Create new object type NEW struct{ base.Index16Instruction } func (self *NEW) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) class := classRef.ResolvedClass() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } if class.IsInterface() || class.IsAbstract() { panic("java.lang.InstantiationError") } ref := class.NewObject() frame.OperandStack().PushRef(ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/new.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
167
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Set static field in class type PUT_STATIC struct{ base.Index16Instruction } func (self *PUT_STATIC) Execute(frame *rtda.Frame) { currentMethod := frame.Method() currentClass := currentMethod.Class() cp := currentClass.ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() class := field.Class() if !class.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), class) return } if !field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } if field.IsFinal() { if currentClass != class || currentMethod.Name() != "<clinit>" { panic("java.lang.IllegalAccessError") } } descriptor := field.Descriptor() slotId := field.SlotId() slots := class.StaticVars() stack := frame.OperandStack() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': slots.SetInt(slotId, stack.PopInt()) case 'F': slots.SetFloat(slotId, stack.PopFloat()) case 'J': slots.SetLong(slotId, stack.PopLong()) case 'D': slots.SetDouble(slotId, stack.PopDouble()) case 'L', '[': slots.SetRef(slotId, stack.PopRef()) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/putstatic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
342
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" const ( //Array Type atype AT_BOOLEAN = 4 AT_CHAR = 5 AT_FLOAT = 6 AT_DOUBLE = 7 AT_BYTE = 8 AT_SHORT = 9 AT_INT = 10 AT_LONG = 11 ) // Create new array type NEW_ARRAY struct { atype uint8 } func (self *NEW_ARRAY) FetchOperands(reader *base.BytecodeReader) { self.atype = reader.ReadUint8() } func (self *NEW_ARRAY) Execute(frame *rtda.Frame) { stack := frame.OperandStack() count := stack.PopInt() if count < 0 { panic("java.lang.NegativeArraySizeException") } classLoader := frame.Method().Class().Loader() arrClass := getPrimitiveArrayClass(classLoader, self.atype) arr := arrClass.NewArray(uint(count)) stack.PushRef(arr) } func getPrimitiveArrayClass(loader *heap.ClassLoader, atype uint8) *heap.Class { switch atype { case AT_BOOLEAN: return loader.LoadClass("[Z") case AT_BYTE: return loader.LoadClass("[B") case AT_CHAR: return loader.LoadClass("[C") case AT_SHORT: return loader.LoadClass("[S") case AT_INT: return loader.LoadClass("[I") case AT_LONG: return loader.LoadClass("[J") case AT_FLOAT: return loader.LoadClass("[F") case AT_DOUBLE: return loader.LoadClass("[D") default: panic("Invalid atype!") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/newarray.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
368
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Invoke instance method; // special handling for superclass, private, and instance initialization method invocations type INVOKE_SPECIAL struct{ base.Index16Instruction } func (self *INVOKE_SPECIAL) Execute(frame *rtda.Frame) { currentClass := frame.Method().Class() cp := currentClass.ConstantPool() methodRef := cp.GetConstant(self.Index).(*heap.MethodRef) resolvedClass := methodRef.ResolvedClass() resolvedMethod := methodRef.ResolvedMethod() if resolvedMethod.Name() == "<init>" && resolvedMethod.Class() != resolvedClass { panic("java.lang.NoSuchMethodError") } if resolvedMethod.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } ref := frame.OperandStack().GetRefFromTop(resolvedMethod.ArgSlotCount() - 1) if ref == nil { panic("java.lang.NullPointerException") } if resolvedMethod.IsProtected() && resolvedMethod.Class().IsSuperClassOf(currentClass) && resolvedMethod.Class().GetPackageName() != currentClass.GetPackageName() && ref.Class() != currentClass && !ref.Class().IsSubClassOf(currentClass) { panic("java.lang.IllegalAccessError") } methodToBeInvoked := resolvedMethod if currentClass.IsSuper() && resolvedClass.IsSuperClassOf(currentClass) && resolvedMethod.Name() != "<init>" { methodToBeInvoked = heap.LookupMethodInClass(currentClass.SuperClass(), methodRef.Name(), methodRef.Descriptor()) } if methodToBeInvoked == nil || methodToBeInvoked.IsAbstract() { panic("java.lang.AbstractMethodError") } base.InvokeMethod(frame, methodToBeInvoked) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/invokespecial.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
403
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Create new array of reference type ANEW_ARRAY struct{ base.Index16Instruction } func (self *ANEW_ARRAY) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(self.Index).(*heap.ClassRef) componentClass := classRef.ResolvedClass() // if componentClass.InitializationNotStarted() { // thread := frame.Thread() // frame.SetNextPC(thread.PC()) // undo anewarray // thread.InitClass(componentClass) // return // } stack := frame.OperandStack() count := stack.PopInt() if count < 0 { panic("java.lang.NegativeArraySizeException") } arrClass := componentClass.ArrayClass() arr := arrClass.NewArray(uint(count)) stack.PushRef(arr) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/anewarray.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
214
```go package references import "reflect" import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Throw exception or error type ATHROW struct{ base.NoOperandsInstruction } func (self *ATHROW) Execute(frame *rtda.Frame) { ex := frame.OperandStack().PopRef() if ex == nil { panic("java.lang.NullPointerException") } thread := frame.Thread() if !findAndGotoExceptionHandler(thread, ex) { handleUncaughtException(thread, ex) } } func findAndGotoExceptionHandler(thread *rtda.Thread, ex *heap.Object) bool { for { frame := thread.CurrentFrame() pc := frame.NextPC() - 1 handlerPC := frame.Method().FindExceptionHandler(ex.Class(), pc) if handlerPC > 0 { stack := frame.OperandStack() stack.Clear() stack.PushRef(ex) frame.SetNextPC(handlerPC) return true } thread.PopFrame() if thread.IsStackEmpty() { break } } return false } // todo func handleUncaughtException(thread *rtda.Thread, ex *heap.Object) { thread.ClearStack() jMsg := ex.GetRefVar("detailMessage", "Ljava/lang/String;") goMsg := heap.GoString(jMsg) println(ex.Class().JavaName() + ": " + goMsg) stes := reflect.ValueOf(ex.Extra()) for i := 0; i < stes.Len(); i++ { ste := stes.Index(i).Interface().(interface { String() string }) println("\tat " + ste.String()) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/athrow.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
373
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Set field in object type PUT_FIELD struct{ base.Index16Instruction } func (self *PUT_FIELD) Execute(frame *rtda.Frame) { currentMethod := frame.Method() currentClass := currentMethod.Class() cp := currentClass.ConstantPool() fieldRef := cp.GetConstant(self.Index).(*heap.FieldRef) field := fieldRef.ResolvedField() if field.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } if field.IsFinal() { if currentClass != field.Class() || currentMethod.Name() != "<init>" { panic("java.lang.IllegalAccessError") } } descriptor := field.Descriptor() slotId := field.SlotId() stack := frame.OperandStack() switch descriptor[0] { case 'Z', 'B', 'C', 'S', 'I': val := stack.PopInt() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } ref.Fields().SetInt(slotId, val) case 'F': val := stack.PopFloat() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } ref.Fields().SetFloat(slotId, val) case 'J': val := stack.PopLong() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } ref.Fields().SetLong(slotId, val) case 'D': val := stack.PopDouble() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } ref.Fields().SetDouble(slotId, val) case 'L', '[': val := stack.PopRef() ref := stack.PopRef() if ref == nil { panic("java.lang.NullPointerException") } ref.Fields().SetRef(slotId, val) default: // todo } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/putfield.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
453
```go package references import "fmt" import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Invoke instance method; dispatch based on class type INVOKE_VIRTUAL struct{ base.Index16Instruction } func (self *INVOKE_VIRTUAL) Execute(frame *rtda.Frame) { currentClass := frame.Method().Class() cp := currentClass.ConstantPool() methodRef := cp.GetConstant(self.Index).(*heap.MethodRef) resolvedMethod := methodRef.ResolvedMethod() if resolvedMethod.IsStatic() { panic("java.lang.IncompatibleClassChangeError") } ref := frame.OperandStack().GetRefFromTop(resolvedMethod.ArgSlotCount() - 1) if ref == nil { // hack! if methodRef.Name() == "println" { _println(frame.OperandStack(), methodRef.Descriptor()) return } panic("java.lang.NullPointerException") } if resolvedMethod.IsProtected() && resolvedMethod.Class().IsSuperClassOf(currentClass) && resolvedMethod.Class().GetPackageName() != currentClass.GetPackageName() && ref.Class() != currentClass && !ref.Class().IsSubClassOf(currentClass) { if !(ref.Class().IsArray() && resolvedMethod.Name() == "clone") { panic("java.lang.IllegalAccessError") } } methodToBeInvoked := heap.LookupMethodInClass(ref.Class(), methodRef.Name(), methodRef.Descriptor()) if methodToBeInvoked == nil || methodToBeInvoked.IsAbstract() { panic("java.lang.AbstractMethodError") } base.InvokeMethod(frame, methodToBeInvoked) } // hack! func _println(stack *rtda.OperandStack, descriptor string) { switch descriptor { case "(Z)V": fmt.Printf("%v\n", stack.PopInt() != 0) case "(C)V": fmt.Printf("%c\n", stack.PopInt()) case "(I)V", "(B)V", "(S)V": fmt.Printf("%v\n", stack.PopInt()) case "(F)V": fmt.Printf("%v\n", stack.PopFloat()) case "(J)V": fmt.Printf("%v\n", stack.PopLong()) case "(D)V": fmt.Printf("%v\n", stack.PopDouble()) case "(Ljava/lang/String;)V": jStr := stack.PopRef() goStr := heap.GoString(jStr) fmt.Println(goStr) default: panic("println: " + descriptor) } stack.PopRef() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/invokevirtual.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
551
```go package references import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Create new multidimensional array type MULTI_ANEW_ARRAY struct { index uint16 dimensions uint8 } func (self *MULTI_ANEW_ARRAY) FetchOperands(reader *base.BytecodeReader) { self.index = reader.ReadUint16() self.dimensions = reader.ReadUint8() } func (self *MULTI_ANEW_ARRAY) Execute(frame *rtda.Frame) { cp := frame.Method().Class().ConstantPool() classRef := cp.GetConstant(uint(self.index)).(*heap.ClassRef) arrClass := classRef.ResolvedClass() stack := frame.OperandStack() counts := popAndCheckCounts(stack, int(self.dimensions)) arr := newMultiDimensionalArray(counts, arrClass) stack.PushRef(arr) } func popAndCheckCounts(stack *rtda.OperandStack, dimensions int) []int32 { counts := make([]int32, dimensions) for i := dimensions - 1; i >= 0; i-- { counts[i] = stack.PopInt() if counts[i] < 0 { panic("java.lang.NegativeArraySizeException") } } return counts } func newMultiDimensionalArray(counts []int32, arrClass *heap.Class) *heap.Object { count := uint(counts[0]) arr := arrClass.NewArray(count) if len(counts) > 1 { refs := arr.Refs() for i := range refs { refs[i] = newMultiDimensionalArray(counts[1:], arrClass.ComponentClass()) } } return arr } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/references/multianewarray.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
373
```go package loads import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Load reference from local variable type ALOAD struct{ base.Index8Instruction } func (self *ALOAD) Execute(frame *rtda.Frame) { _aload(frame, self.Index) } type ALOAD_0 struct{ base.NoOperandsInstruction } func (self *ALOAD_0) Execute(frame *rtda.Frame) { _aload(frame, 0) } type ALOAD_1 struct{ base.NoOperandsInstruction } func (self *ALOAD_1) Execute(frame *rtda.Frame) { _aload(frame, 1) } type ALOAD_2 struct{ base.NoOperandsInstruction } func (self *ALOAD_2) Execute(frame *rtda.Frame) { _aload(frame, 2) } type ALOAD_3 struct{ base.NoOperandsInstruction } func (self *ALOAD_3) Execute(frame *rtda.Frame) { _aload(frame, 3) } func _aload(frame *rtda.Frame, index uint) { ref := frame.LocalVars().GetRef(index) frame.OperandStack().PushRef(ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/loads/aload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
262
```go package loads import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Load double from local variable type DLOAD struct{ base.Index8Instruction } func (self *DLOAD) Execute(frame *rtda.Frame) { _dload(frame, self.Index) } type DLOAD_0 struct{ base.NoOperandsInstruction } func (self *DLOAD_0) Execute(frame *rtda.Frame) { _dload(frame, 0) } type DLOAD_1 struct{ base.NoOperandsInstruction } func (self *DLOAD_1) Execute(frame *rtda.Frame) { _dload(frame, 1) } type DLOAD_2 struct{ base.NoOperandsInstruction } func (self *DLOAD_2) Execute(frame *rtda.Frame) { _dload(frame, 2) } type DLOAD_3 struct{ base.NoOperandsInstruction } func (self *DLOAD_3) Execute(frame *rtda.Frame) { _dload(frame, 3) } func _dload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetDouble(index) frame.OperandStack().PushDouble(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/loads/dload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
263
```go package loads import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Load reference from array type AALOAD struct{ base.NoOperandsInstruction } func (self *AALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) refs := arrRef.Refs() checkIndex(len(refs), index) stack.PushRef(refs[index]) } // Load byte or boolean from array type BALOAD struct{ base.NoOperandsInstruction } func (self *BALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) bytes := arrRef.Bytes() checkIndex(len(bytes), index) stack.PushInt(int32(bytes[index])) } // Load char from array type CALOAD struct{ base.NoOperandsInstruction } func (self *CALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) chars := arrRef.Chars() checkIndex(len(chars), index) stack.PushInt(int32(chars[index])) } // Load double from array type DALOAD struct{ base.NoOperandsInstruction } func (self *DALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) doubles := arrRef.Doubles() checkIndex(len(doubles), index) stack.PushDouble(doubles[index]) } // Load float from array type FALOAD struct{ base.NoOperandsInstruction } func (self *FALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) floats := arrRef.Floats() checkIndex(len(floats), index) stack.PushFloat(floats[index]) } // Load int from array type IALOAD struct{ base.NoOperandsInstruction } func (self *IALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) ints := arrRef.Ints() checkIndex(len(ints), index) stack.PushInt(ints[index]) } // Load long from array type LALOAD struct{ base.NoOperandsInstruction } func (self *LALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) longs := arrRef.Longs() checkIndex(len(longs), index) stack.PushLong(longs[index]) } // Load short from array type SALOAD struct{ base.NoOperandsInstruction } func (self *SALOAD) Execute(frame *rtda.Frame) { stack := frame.OperandStack() index := stack.PopInt() arrRef := stack.PopRef() checkNotNil(arrRef) shorts := arrRef.Shorts() checkIndex(len(shorts), index) stack.PushInt(int32(shorts[index])) } func checkNotNil(ref *heap.Object) { if ref == nil { panic("java.lang.NullPointerException") } } func checkIndex(arrLen int, index int32) { if index < 0 || index >= int32(arrLen) { panic("ArrayIndexOutOfBoundsException") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/loads/xaload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
766
```go package loads import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Load float from local variable type FLOAD struct{ base.Index8Instruction } func (self *FLOAD) Execute(frame *rtda.Frame) { _fload(frame, self.Index) } type FLOAD_0 struct{ base.NoOperandsInstruction } func (self *FLOAD_0) Execute(frame *rtda.Frame) { _fload(frame, 0) } type FLOAD_1 struct{ base.NoOperandsInstruction } func (self *FLOAD_1) Execute(frame *rtda.Frame) { _fload(frame, 1) } type FLOAD_2 struct{ base.NoOperandsInstruction } func (self *FLOAD_2) Execute(frame *rtda.Frame) { _fload(frame, 2) } type FLOAD_3 struct{ base.NoOperandsInstruction } func (self *FLOAD_3) Execute(frame *rtda.Frame) { _fload(frame, 3) } func _fload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetFloat(index) frame.OperandStack().PushFloat(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/loads/fload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
263
```go package loads import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Load long from local variable type LLOAD struct{ base.Index8Instruction } func (self *LLOAD) Execute(frame *rtda.Frame) { _lload(frame, self.Index) } type LLOAD_0 struct{ base.NoOperandsInstruction } func (self *LLOAD_0) Execute(frame *rtda.Frame) { _lload(frame, 0) } type LLOAD_1 struct{ base.NoOperandsInstruction } func (self *LLOAD_1) Execute(frame *rtda.Frame) { _lload(frame, 1) } type LLOAD_2 struct{ base.NoOperandsInstruction } func (self *LLOAD_2) Execute(frame *rtda.Frame) { _lload(frame, 2) } type LLOAD_3 struct{ base.NoOperandsInstruction } func (self *LLOAD_3) Execute(frame *rtda.Frame) { _lload(frame, 3) } func _lload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetLong(index) frame.OperandStack().PushLong(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/loads/lload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
263
```go package loads import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Load int from local variable type ILOAD struct{ base.Index8Instruction } func (self *ILOAD) Execute(frame *rtda.Frame) { _iload(frame, self.Index) } type ILOAD_0 struct{ base.NoOperandsInstruction } func (self *ILOAD_0) Execute(frame *rtda.Frame) { _iload(frame, 0) } type ILOAD_1 struct{ base.NoOperandsInstruction } func (self *ILOAD_1) Execute(frame *rtda.Frame) { _iload(frame, 1) } type ILOAD_2 struct{ base.NoOperandsInstruction } func (self *ILOAD_2) Execute(frame *rtda.Frame) { _iload(frame, 2) } type ILOAD_3 struct{ base.NoOperandsInstruction } func (self *ILOAD_3) Execute(frame *rtda.Frame) { _iload(frame, 3) } func _iload(frame *rtda.Frame, index uint) { val := frame.LocalVars().GetInt(index) frame.OperandStack().PushInt(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/loads/iload.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
262
```go package extended import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Branch if reference is null type IFNULL struct{ base.BranchInstruction } func (self *IFNULL) Execute(frame *rtda.Frame) { ref := frame.OperandStack().PopRef() if ref == nil { base.Branch(frame, self.Offset) } } // Branch if reference not null type IFNONNULL struct{ base.BranchInstruction } func (self *IFNONNULL) Execute(frame *rtda.Frame) { ref := frame.OperandStack().PopRef() if ref != nil { base.Branch(frame, self.Offset) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/extended/ifnull.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
144
```go package extended import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Branch always (wide index) type GOTO_W struct { offset int } func (self *GOTO_W) FetchOperands(reader *base.BytecodeReader) { self.offset = int(reader.ReadInt32()) } func (self *GOTO_W) Execute(frame *rtda.Frame) { base.Branch(frame, self.offset) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/extended/goto_w.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
96
```go package extended import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/instructions/loads" import "jvmgo/ch10/instructions/math" import "jvmgo/ch10/instructions/stores" import "jvmgo/ch10/rtda" // Extend local variable index by additional bytes type WIDE struct { modifiedInstruction base.Instruction } func (self *WIDE) FetchOperands(reader *base.BytecodeReader) { opcode := reader.ReadUint8() switch opcode { case 0x15: inst := &loads.ILOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x16: inst := &loads.LLOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x17: inst := &loads.FLOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x18: inst := &loads.DLOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x19: inst := &loads.ALOAD{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x36: inst := &stores.ISTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x37: inst := &stores.LSTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x38: inst := &stores.FSTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x39: inst := &stores.DSTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x3a: inst := &stores.ASTORE{} inst.Index = uint(reader.ReadUint16()) self.modifiedInstruction = inst case 0x84: inst := &math.IINC{} inst.Index = uint(reader.ReadUint16()) inst.Const = int32(reader.ReadInt16()) self.modifiedInstruction = inst case 0xa9: // ret panic("Unsupported opcode: 0xa9!") } } func (self *WIDE) Execute(frame *rtda.Frame) { self.modifiedInstruction.Execute(frame) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/extended/wide.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
511
```go package comparisons import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Compare long type LCMP struct{ base.NoOperandsInstruction } func (self *LCMP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := stack.PopLong() if v1 > v2 { stack.PushInt(1) } else if v1 == v2 { stack.PushInt(0) } else { stack.PushInt(-1) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/comparisons/lcmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
123
```go package comparisons import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Compare float type FCMPG struct{ base.NoOperandsInstruction } func (self *FCMPG) Execute(frame *rtda.Frame) { _fcmp(frame, true) } type FCMPL struct{ base.NoOperandsInstruction } func (self *FCMPL) Execute(frame *rtda.Frame) { _fcmp(frame, false) } func _fcmp(frame *rtda.Frame, gFlag bool) { stack := frame.OperandStack() v2 := stack.PopFloat() v1 := stack.PopFloat() if v1 > v2 { stack.PushInt(1) } else if v1 == v2 { stack.PushInt(0) } else if v1 < v2 { stack.PushInt(-1) } else if gFlag { stack.PushInt(1) } else { stack.PushInt(-1) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/comparisons/fcmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
217
```go package comparisons import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Branch if int comparison with zero succeeds type IFEQ struct{ base.BranchInstruction } func (self *IFEQ) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val == 0 { base.Branch(frame, self.Offset) } } type IFNE struct{ base.BranchInstruction } func (self *IFNE) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val != 0 { base.Branch(frame, self.Offset) } } type IFLT struct{ base.BranchInstruction } func (self *IFLT) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val < 0 { base.Branch(frame, self.Offset) } } type IFLE struct{ base.BranchInstruction } func (self *IFLE) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val <= 0 { base.Branch(frame, self.Offset) } } type IFGT struct{ base.BranchInstruction } func (self *IFGT) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val > 0 { base.Branch(frame, self.Offset) } } type IFGE struct{ base.BranchInstruction } func (self *IFGE) Execute(frame *rtda.Frame) { val := frame.OperandStack().PopInt() if val >= 0 { base.Branch(frame, self.Offset) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/comparisons/ifcond.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
348
```go package comparisons import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Branch if reference comparison succeeds type IF_ACMPEQ struct{ base.BranchInstruction } func (self *IF_ACMPEQ) Execute(frame *rtda.Frame) { if _acmp(frame) { base.Branch(frame, self.Offset) } } type IF_ACMPNE struct{ base.BranchInstruction } func (self *IF_ACMPNE) Execute(frame *rtda.Frame) { if !_acmp(frame) { base.Branch(frame, self.Offset) } } func _acmp(frame *rtda.Frame) bool { stack := frame.OperandStack() ref2 := stack.PopRef() ref1 := stack.PopRef() return ref1 == ref2 // todo } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/comparisons/if_acmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
173
```go package comparisons import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Branch if int comparison succeeds type IF_ICMPEQ struct{ base.BranchInstruction } func (self *IF_ICMPEQ) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 == val2 { base.Branch(frame, self.Offset) } } type IF_ICMPNE struct{ base.BranchInstruction } func (self *IF_ICMPNE) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 != val2 { base.Branch(frame, self.Offset) } } type IF_ICMPLT struct{ base.BranchInstruction } func (self *IF_ICMPLT) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 < val2 { base.Branch(frame, self.Offset) } } type IF_ICMPLE struct{ base.BranchInstruction } func (self *IF_ICMPLE) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 <= val2 { base.Branch(frame, self.Offset) } } type IF_ICMPGT struct{ base.BranchInstruction } func (self *IF_ICMPGT) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 > val2 { base.Branch(frame, self.Offset) } } type IF_ICMPGE struct{ base.BranchInstruction } func (self *IF_ICMPGE) Execute(frame *rtda.Frame) { if val1, val2 := _icmpPop(frame); val1 >= val2 { base.Branch(frame, self.Offset) } } func _icmpPop(frame *rtda.Frame) (val1, val2 int32) { stack := frame.OperandStack() val2 = stack.PopInt() val1 = stack.PopInt() return } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/comparisons/if_icmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
430
```go package comparisons import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Compare double type DCMPG struct{ base.NoOperandsInstruction } func (self *DCMPG) Execute(frame *rtda.Frame) { _dcmp(frame, true) } type DCMPL struct{ base.NoOperandsInstruction } func (self *DCMPL) Execute(frame *rtda.Frame) { _dcmp(frame, false) } func _dcmp(frame *rtda.Frame, gFlag bool) { stack := frame.OperandStack() v2 := stack.PopDouble() v1 := stack.PopDouble() if v1 > v2 { stack.PushInt(1) } else if v1 == v2 { stack.PushInt(0) } else if v1 < v2 { stack.PushInt(-1) } else if gFlag { stack.PushInt(1) } else { stack.PushInt(-1) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/comparisons/dcmp.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
217
```go package constants import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Do nothing type NOP struct{ base.NoOperandsInstruction } func (self *NOP) Execute(frame *rtda.Frame) { // really do nothing } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/constants/nop.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
62
```go package constants import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/rtda/heap" // Push item from run-time constant pool type LDC struct{ base.Index8Instruction } func (self *LDC) Execute(frame *rtda.Frame) { _ldc(frame, self.Index) } // Push item from run-time constant pool (wide index) type LDC_W struct{ base.Index16Instruction } func (self *LDC_W) Execute(frame *rtda.Frame) { _ldc(frame, self.Index) } func _ldc(frame *rtda.Frame, index uint) { stack := frame.OperandStack() class := frame.Method().Class() c := class.ConstantPool().GetConstant(index) switch c.(type) { case int32: stack.PushInt(c.(int32)) case float32: stack.PushFloat(c.(float32)) case string: internedStr := heap.JString(class.Loader(), c.(string)) stack.PushRef(internedStr) case *heap.ClassRef: classRef := c.(*heap.ClassRef) classObj := classRef.ResolvedClass().JClass() stack.PushRef(classObj) // case MethodType, MethodHandle default: panic("todo: ldc!") } } // Push long or double from run-time constant pool (wide index) type LDC2_W struct{ base.Index16Instruction } func (self *LDC2_W) Execute(frame *rtda.Frame) { stack := frame.OperandStack() cp := frame.Method().Class().ConstantPool() c := cp.GetConstant(self.Index) switch c.(type) { case int64: stack.PushLong(c.(int64)) case float64: stack.PushDouble(c.(float64)) default: panic("java.lang.ClassFormatError") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/constants/ldc.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
403
```go package constants import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Push null type ACONST_NULL struct{ base.NoOperandsInstruction } func (self *ACONST_NULL) Execute(frame *rtda.Frame) { frame.OperandStack().PushRef(nil) } // Push double type DCONST_0 struct{ base.NoOperandsInstruction } func (self *DCONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushDouble(0.0) } type DCONST_1 struct{ base.NoOperandsInstruction } func (self *DCONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushDouble(1.0) } // Push float type FCONST_0 struct{ base.NoOperandsInstruction } func (self *FCONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushFloat(0.0) } type FCONST_1 struct{ base.NoOperandsInstruction } func (self *FCONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushFloat(1.0) } type FCONST_2 struct{ base.NoOperandsInstruction } func (self *FCONST_2) Execute(frame *rtda.Frame) { frame.OperandStack().PushFloat(2.0) } // Push int constant type ICONST_M1 struct{ base.NoOperandsInstruction } func (self *ICONST_M1) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(-1) } type ICONST_0 struct{ base.NoOperandsInstruction } func (self *ICONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(0) } type ICONST_1 struct{ base.NoOperandsInstruction } func (self *ICONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(1) } type ICONST_2 struct{ base.NoOperandsInstruction } func (self *ICONST_2) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(2) } type ICONST_3 struct{ base.NoOperandsInstruction } func (self *ICONST_3) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(3) } type ICONST_4 struct{ base.NoOperandsInstruction } func (self *ICONST_4) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(4) } type ICONST_5 struct{ base.NoOperandsInstruction } func (self *ICONST_5) Execute(frame *rtda.Frame) { frame.OperandStack().PushInt(5) } // Push long constant type LCONST_0 struct{ base.NoOperandsInstruction } func (self *LCONST_0) Execute(frame *rtda.Frame) { frame.OperandStack().PushLong(0) } type LCONST_1 struct{ base.NoOperandsInstruction } func (self *LCONST_1) Execute(frame *rtda.Frame) { frame.OperandStack().PushLong(1) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/constants/const.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
688
```go package constants import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Push byte type BIPUSH struct { val int8 } func (self *BIPUSH) FetchOperands(reader *base.BytecodeReader) { self.val = reader.ReadInt8() } func (self *BIPUSH) Execute(frame *rtda.Frame) { i := int32(self.val) frame.OperandStack().PushInt(i) } // Push short type SIPUSH struct { val int16 } func (self *SIPUSH) FetchOperands(reader *base.BytecodeReader) { self.val = reader.ReadInt16() } func (self *SIPUSH) Execute(frame *rtda.Frame) { i := int32(self.val) frame.OperandStack().PushInt(i) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/constants/ipush.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
177
```go package stack import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Swap the top two operand stack values type SWAP struct{ base.NoOperandsInstruction } func (self *SWAP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() stack.PushSlot(slot1) stack.PushSlot(slot2) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stack/swap.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
96
```go package reserved import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" import "jvmgo/ch10/native" import _ "jvmgo/ch10/native/java/lang" import _ "jvmgo/ch10/native/sun/misc" // Invoke native method type INVOKE_NATIVE struct{ base.NoOperandsInstruction } func (self *INVOKE_NATIVE) Execute(frame *rtda.Frame) { method := frame.Method() className := method.Class().Name() methodName := method.Name() methodDescriptor := method.Descriptor() nativeMethod := native.FindNativeMethod(className, methodName, methodDescriptor) if nativeMethod == nil { methodInfo := className + "." + methodName + methodDescriptor panic("java.lang.UnsatisfiedLinkError: " + methodInfo) } nativeMethod(frame) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/reserved/invokenative.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
177
```go package stack import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Pop the top operand stack value type POP struct{ base.NoOperandsInstruction } func (self *POP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() stack.PopSlot() } // Pop the top one or two operand stack values type POP2 struct{ base.NoOperandsInstruction } func (self *POP2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() stack.PopSlot() stack.PopSlot() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/stack/pop.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
125
```go package conversions import "jvmgo/ch10/instructions/base" import "jvmgo/ch10/rtda" // Convert double to float type D2F struct{ base.NoOperandsInstruction } func (self *D2F) Execute(frame *rtda.Frame) { stack := frame.OperandStack() d := stack.PopDouble() f := float32(d) stack.PushFloat(f) } // Convert double to int type D2I struct{ base.NoOperandsInstruction } func (self *D2I) Execute(frame *rtda.Frame) { stack := frame.OperandStack() d := stack.PopDouble() i := int32(d) stack.PushInt(i) } // Convert double to long type D2L struct{ base.NoOperandsInstruction } func (self *D2L) Execute(frame *rtda.Frame) { stack := frame.OperandStack() d := stack.PopDouble() l := int64(d) stack.PushLong(l) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch10/instructions/conversions/d2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206