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 references import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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 "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 loads import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 extended import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/instructions/loads" import "jvmgo/ch09/instructions/math" import "jvmgo/ch09/instructions/stores" import "jvmgo/ch09/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/ch09/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 extended import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 comparisons import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 comparisons import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 constants import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/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/ch09/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/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 reserved import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" import "jvmgo/ch09/native" import _ "jvmgo/ch09/native/java/lang" import _ "jvmgo/ch09/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/ch09/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 constants import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 stack import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 stack import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/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 conversions import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/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/ch09/instructions/conversions/d2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206
```go package stack import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" // Duplicate the top operand stack value type DUP struct{ base.NoOperandsInstruction } func (self *DUP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot := stack.PopSlot() stack.PushSlot(slot) stack.PushSlot(slot) } // Duplicate the top operand stack value and insert two values down type DUP_X1 struct{ base.NoOperandsInstruction } func (self *DUP_X1) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() stack.PushSlot(slot1) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top operand stack value and insert two or three values down type DUP_X2 struct{ base.NoOperandsInstruction } func (self *DUP_X2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() slot3 := stack.PopSlot() stack.PushSlot(slot1) stack.PushSlot(slot3) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top one or two operand stack values type DUP2 struct{ base.NoOperandsInstruction } func (self *DUP2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() stack.PushSlot(slot2) stack.PushSlot(slot1) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top one or two operand stack values and insert two or three values down type DUP2_X1 struct{ base.NoOperandsInstruction } func (self *DUP2_X1) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() slot3 := stack.PopSlot() stack.PushSlot(slot2) stack.PushSlot(slot1) stack.PushSlot(slot3) stack.PushSlot(slot2) stack.PushSlot(slot1) } // Duplicate the top one or two operand stack values and insert two, three, or four values down type DUP2_X2 struct{ base.NoOperandsInstruction } func (self *DUP2_X2) Execute(frame *rtda.Frame) { stack := frame.OperandStack() slot1 := stack.PopSlot() slot2 := stack.PopSlot() slot3 := stack.PopSlot() slot4 := stack.PopSlot() stack.PushSlot(slot2) stack.PushSlot(slot1) stack.PushSlot(slot4) stack.PushSlot(slot3) stack.PushSlot(slot2) stack.PushSlot(slot1) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/stack/dup.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
584
```go package conversions import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" // Convert int to byte type I2B struct{ base.NoOperandsInstruction } func (self *I2B) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() b := int32(int8(i)) stack.PushInt(b) } // Convert int to char type I2C struct{ base.NoOperandsInstruction } func (self *I2C) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() c := int32(uint16(i)) stack.PushInt(c) } // Convert int to short type I2S struct{ base.NoOperandsInstruction } func (self *I2S) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() s := int32(int16(i)) stack.PushInt(s) } // Convert int to long type I2L struct{ base.NoOperandsInstruction } func (self *I2L) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() l := int64(i) stack.PushLong(l) } // Convert int to float type I2F struct{ base.NoOperandsInstruction } func (self *I2F) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() f := float32(i) stack.PushFloat(f) } // Convert int to double type I2D struct{ base.NoOperandsInstruction } func (self *I2D) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() d := float64(i) stack.PushDouble(d) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/conversions/i2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
392
```go package conversions import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" // Convert float to double type F2D struct{ base.NoOperandsInstruction } func (self *F2D) Execute(frame *rtda.Frame) { stack := frame.OperandStack() f := stack.PopFloat() d := float64(f) stack.PushDouble(d) } // Convert float to int type F2I struct{ base.NoOperandsInstruction } func (self *F2I) Execute(frame *rtda.Frame) { stack := frame.OperandStack() f := stack.PopFloat() i := int32(f) stack.PushInt(i) } // Convert float to long type F2L struct{ base.NoOperandsInstruction } func (self *F2L) Execute(frame *rtda.Frame) { stack := frame.OperandStack() f := stack.PopFloat() l := int64(f) stack.PushLong(l) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/conversions/f2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206
```go package conversions import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" // Convert long to double type L2D struct{ base.NoOperandsInstruction } func (self *L2D) Execute(frame *rtda.Frame) { stack := frame.OperandStack() l := stack.PopLong() d := float64(l) stack.PushDouble(d) } // Convert long to float type L2F struct{ base.NoOperandsInstruction } func (self *L2F) Execute(frame *rtda.Frame) { stack := frame.OperandStack() l := stack.PopLong() f := float32(l) stack.PushFloat(f) } // Convert long to int type L2I struct{ base.NoOperandsInstruction } func (self *L2I) Execute(frame *rtda.Frame) { stack := frame.OperandStack() l := stack.PopLong() i := int32(l) stack.PushInt(i) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/conversions/l2x.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
206
```go package control import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" // Branch always type GOTO struct{ base.BranchInstruction } func (self *GOTO) Execute(frame *rtda.Frame) { base.Branch(frame, self.Offset) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/control/goto.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
63
```go package control import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" /* tableswitch <0-3 byte pad> defaultbyte1 defaultbyte2 defaultbyte3 defaultbyte4 lowbyte1 lowbyte2 lowbyte3 lowbyte4 highbyte1 highbyte2 highbyte3 highbyte4 jump offsets... */ // Access jump table by index and jump type TABLE_SWITCH struct { defaultOffset int32 low int32 high int32 jumpOffsets []int32 } func (self *TABLE_SWITCH) FetchOperands(reader *base.BytecodeReader) { reader.SkipPadding() self.defaultOffset = reader.ReadInt32() self.low = reader.ReadInt32() self.high = reader.ReadInt32() jumpOffsetsCount := self.high - self.low + 1 self.jumpOffsets = reader.ReadInt32s(jumpOffsetsCount) } func (self *TABLE_SWITCH) Execute(frame *rtda.Frame) { index := frame.OperandStack().PopInt() var offset int if index >= self.low && index <= self.high { offset = int(self.jumpOffsets[index-self.low]) } else { offset = int(self.defaultOffset) } base.Branch(frame, offset) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/control/tableswitch.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
274
```go package control import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" // Return void from method type RETURN struct{ base.NoOperandsInstruction } func (self *RETURN) Execute(frame *rtda.Frame) { frame.Thread().PopFrame() } // Return reference from method type ARETURN struct{ base.NoOperandsInstruction } func (self *ARETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() ref := currentFrame.OperandStack().PopRef() invokerFrame.OperandStack().PushRef(ref) } // Return double from method type DRETURN struct{ base.NoOperandsInstruction } func (self *DRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopDouble() invokerFrame.OperandStack().PushDouble(val) } // Return float from method type FRETURN struct{ base.NoOperandsInstruction } func (self *FRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopFloat() invokerFrame.OperandStack().PushFloat(val) } // Return int from method type IRETURN struct{ base.NoOperandsInstruction } func (self *IRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopInt() invokerFrame.OperandStack().PushInt(val) } // Return double from method type LRETURN struct{ base.NoOperandsInstruction } func (self *LRETURN) Execute(frame *rtda.Frame) { thread := frame.Thread() currentFrame := thread.PopFrame() invokerFrame := thread.TopFrame() val := currentFrame.OperandStack().PopLong() invokerFrame.OperandStack().PushLong(val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/control/return.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
454
```go package control import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/rtda" /* lookupswitch <0-3 byte pad> defaultbyte1 defaultbyte2 defaultbyte3 defaultbyte4 npairs1 npairs2 npairs3 npairs4 match-offset pairs... */ // Access jump table by key match and jump type LOOKUP_SWITCH struct { defaultOffset int32 npairs int32 matchOffsets []int32 } func (self *LOOKUP_SWITCH) FetchOperands(reader *base.BytecodeReader) { reader.SkipPadding() self.defaultOffset = reader.ReadInt32() self.npairs = reader.ReadInt32() self.matchOffsets = reader.ReadInt32s(self.npairs * 2) } func (self *LOOKUP_SWITCH) Execute(frame *rtda.Frame) { key := frame.OperandStack().PopInt() for i := int32(0); i < self.npairs*2; i += 2 { if self.matchOffsets[i] == key { offset := self.matchOffsets[i+1] base.Branch(frame, int(offset)) return } } base.Branch(frame, int(self.defaultOffset)) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/instructions/control/lookupswitch.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
259
```go package classfile /* field_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } method_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } */ type MemberInfo struct { cp ConstantPool accessFlags uint16 nameIndex uint16 descriptorIndex uint16 attributes []AttributeInfo } // read field or method table func readMembers(reader *ClassReader, cp ConstantPool) []*MemberInfo { memberCount := reader.readUint16() members := make([]*MemberInfo, memberCount) for i := range members { members[i] = readMember(reader, cp) } return members } func readMember(reader *ClassReader, cp ConstantPool) *MemberInfo { return &MemberInfo{ cp: cp, accessFlags: reader.readUint16(), nameIndex: reader.readUint16(), descriptorIndex: reader.readUint16(), attributes: readAttributes(reader, cp), } } func (self *MemberInfo) AccessFlags() uint16 { return self.accessFlags } func (self *MemberInfo) Name() string { return self.cp.getUtf8(self.nameIndex) } func (self *MemberInfo) Descriptor() string { return self.cp.getUtf8(self.descriptorIndex) } func (self *MemberInfo) CodeAttribute() *CodeAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *CodeAttribute: return attrInfo.(*CodeAttribute) } } return nil } func (self *MemberInfo) ConstantValueAttribute() *ConstantValueAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *ConstantValueAttribute: return attrInfo.(*ConstantValueAttribute) } } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/classfile/member_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
438
```go package classfile /* EnclosingMethod_attribute { u2 attribute_name_index; u4 attribute_length; u2 class_index; u2 method_index; } */ type EnclosingMethodAttribute struct { cp ConstantPool classIndex uint16 methodIndex uint16 } func (self *EnclosingMethodAttribute) readInfo(reader *ClassReader) { self.classIndex = reader.readUint16() self.methodIndex = reader.readUint16() } func (self *EnclosingMethodAttribute) ClassName() string { return self.cp.getClassName(self.classIndex) } func (self *EnclosingMethodAttribute) MethodNameAndDescriptor() (string, string) { if self.methodIndex > 0 { return self.cp.getNameAndType(self.methodIndex) } else { return "", "" } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/classfile/attr_enclosing_method.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
170
```go package classfile /* CONSTANT_MethodHandle_info { u1 tag; u1 reference_kind; u2 reference_index; } */ type ConstantMethodHandleInfo struct { referenceKind uint8 referenceIndex uint16 } func (self *ConstantMethodHandleInfo) readInfo(reader *ClassReader) { self.referenceKind = reader.readUint8() self.referenceIndex = reader.readUint16() } /* CONSTANT_MethodType_info { u1 tag; u2 descriptor_index; } */ type ConstantMethodTypeInfo struct { descriptorIndex uint16 } func (self *ConstantMethodTypeInfo) readInfo(reader *ClassReader) { self.descriptorIndex = reader.readUint16() } /* CONSTANT_InvokeDynamic_info { u1 tag; u2 bootstrap_method_attr_index; u2 name_and_type_index; } */ type ConstantInvokeDynamicInfo struct { bootstrapMethodAttrIndex uint16 nameAndTypeIndex uint16 } func (self *ConstantInvokeDynamicInfo) readInfo(reader *ClassReader) { self.bootstrapMethodAttrIndex = reader.readUint16() self.nameAndTypeIndex = reader.readUint16() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/classfile/cp_invoke_dynamic.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
241
```go package classfile /* BootstrapMethods_attribute { u2 attribute_name_index; u4 attribute_length; u2 num_bootstrap_methods; { u2 bootstrap_method_ref; u2 num_bootstrap_arguments; u2 bootstrap_arguments[num_bootstrap_arguments]; } bootstrap_methods[num_bootstrap_methods]; } */ type BootstrapMethodsAttribute struct { bootstrapMethods []*BootstrapMethod } func (self *BootstrapMethodsAttribute) readInfo(reader *ClassReader) { numBootstrapMethods := reader.readUint16() self.bootstrapMethods = make([]*BootstrapMethod, numBootstrapMethods) for i := range self.bootstrapMethods { self.bootstrapMethods[i] = &BootstrapMethod{ bootstrapMethodRef: reader.readUint16(), bootstrapArguments: reader.readUint16s(), } } } type BootstrapMethod struct { bootstrapMethodRef uint16 bootstrapArguments []uint16 } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/classfile/attr_bootstrap_methods.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
184
```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/ch09/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 /* 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/ch09/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 /* 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/ch09/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 /* 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/ch09/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 /* 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/ch09/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/ch09/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 /* 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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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/ch09/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 /* 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/ch09/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 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/ch09/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 native import "jvmgo/ch09/rtda" type NativeMethod func(frame *rtda.Frame) var registry = map[string]NativeMethod{} func emptyNativeMethod(frame *rtda.Frame) { // do nothing } func Register(className, methodName, methodDescriptor string, method NativeMethod) { key := className + "~" + methodName + "~" + methodDescriptor registry[key] = method } func FindNativeMethod(className, methodName, methodDescriptor string) NativeMethod { key := className + "~" + methodName + "~" + methodDescriptor if method, ok := registry[key]; ok { return method } if methodDescriptor == "()V" && methodName == "registerNatives" { return emptyNativeMethod } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/registry.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
165
```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/ch09/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 lang import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" import "jvmgo/ch09/rtda/heap" const jlString = "java/lang/String" func init() { native.Register(jlString, "intern", "()Ljava/lang/String;", intern) } // public native String intern(); // ()Ljava/lang/String; func intern(frame *rtda.Frame) { this := frame.LocalVars().GetThis() interned := heap.InternString(this) frame.OperandStack().PushRef(interned) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/java/lang/String.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
121
```go package lang import "unsafe" import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" const jlObject = "java/lang/Object" func init() { native.Register(jlObject, "getClass", "()Ljava/lang/Class;", getClass) native.Register(jlObject, "hashCode", "()I", hashCode) native.Register(jlObject, "clone", "()Ljava/lang/Object;", clone) } // public final native Class<?> getClass(); // ()Ljava/lang/Class; func getClass(frame *rtda.Frame) { this := frame.LocalVars().GetThis() class := this.Class().JClass() frame.OperandStack().PushRef(class) } // public native int hashCode(); // ()I func hashCode(frame *rtda.Frame) { this := frame.LocalVars().GetThis() hash := int32(uintptr(unsafe.Pointer(this))) frame.OperandStack().PushInt(hash) } // protected native Object clone() throws CloneNotSupportedException; // ()Ljava/lang/Object; func clone(frame *rtda.Frame) { this := frame.LocalVars().GetThis() cloneable := this.Class().Loader().LoadClass("java/lang/Cloneable") if !this.Class().IsImplements(cloneable) { panic("java.lang.CloneNotSupportedException") } frame.OperandStack().PushRef(this.Clone()) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/java/lang/Object.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
280
```go package lang import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" import "jvmgo/ch09/rtda/heap" const jlSystem = "java/lang/System" func init() { native.Register(jlSystem, "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", arraycopy) } // public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) // (Ljava/lang/Object;ILjava/lang/Object;II)V func arraycopy(frame *rtda.Frame) { vars := frame.LocalVars() src := vars.GetRef(0) srcPos := vars.GetInt(1) dest := vars.GetRef(2) destPos := vars.GetInt(3) length := vars.GetInt(4) if src == nil || dest == nil { panic("java.lang.NullPointerException") } if !checkArrayCopy(src, dest) { panic("java.lang.ArrayStoreException") } if srcPos < 0 || destPos < 0 || length < 0 || srcPos+length > src.ArrayLength() || destPos+length > dest.ArrayLength() { panic("java.lang.IndexOutOfBoundsException") } heap.ArrayCopy(src, dest, srcPos, destPos, length) } func checkArrayCopy(src, dest *heap.Object) bool { srcClass := src.Class() destClass := dest.Class() if !srcClass.IsArray() || !destClass.IsArray() { return false } if srcClass.ComponentClass().IsPrimitive() || destClass.ComponentClass().IsPrimitive() { return srcClass == destClass } return true } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/java/lang/System.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
360
```go package lang import "math" import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" const jlFloat = "java/lang/Float" func init() { native.Register(jlFloat, "floatToRawIntBits", "(F)I", floatToRawIntBits) native.Register(jlFloat, "intBitsToFloat", "(I)F", intBitsToFloat) } // public static native int floatToRawIntBits(float value); // (F)I func floatToRawIntBits(frame *rtda.Frame) { value := frame.LocalVars().GetFloat(0) bits := math.Float32bits(value) // todo frame.OperandStack().PushInt(int32(bits)) } // public static native float intBitsToFloat(int bits); // (I)F func intBitsToFloat(frame *rtda.Frame) { bits := frame.LocalVars().GetInt(0) value := math.Float32frombits(uint32(bits)) // todo frame.OperandStack().PushFloat(value) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/java/lang/Float.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
225
```go package lang import "math" import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" const jlDouble = "java/lang/Double" func init() { native.Register(jlDouble, "doubleToRawLongBits", "(D)J", doubleToRawLongBits) native.Register(jlDouble, "longBitsToDouble", "(J)D", longBitsToDouble) } // public static native long doubleToRawLongBits(double value); // (D)J func doubleToRawLongBits(frame *rtda.Frame) { value := frame.LocalVars().GetDouble(0) bits := math.Float64bits(value) // todo frame.OperandStack().PushLong(int64(bits)) } // public static native double longBitsToDouble(long bits); // (J)D func longBitsToDouble(frame *rtda.Frame) { bits := frame.LocalVars().GetLong(0) value := math.Float64frombits(uint64(bits)) // todo frame.OperandStack().PushDouble(value) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/java/lang/Double.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
226
```go package misc import "jvmgo/ch09/instructions/base" import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" import "jvmgo/ch09/rtda/heap" func init() { native.Register("sun/misc/VM", "initialize", "()V", initialize) } // private static native void initialize(); // ()V func initialize(frame *rtda.Frame) { // hack: just make VM.savedProps nonempty vmClass := frame.Method().Class() savedProps := vmClass.GetRefVar("savedProps", "Ljava/util/Properties;") key := heap.JString(vmClass.Loader(), "foo") val := heap.JString(vmClass.Loader(), "bar") frame.OperandStack().PushRef(savedProps) frame.OperandStack().PushRef(key) frame.OperandStack().PushRef(val) propsClass := vmClass.Loader().LoadClass("java/util/Properties") setPropMethod := propsClass.GetInstanceMethod("setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;") base.InvokeMethod(frame, setPropMethod) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/sun/misc/VM.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
232
```go package lang import "jvmgo/ch09/native" import "jvmgo/ch09/rtda" import "jvmgo/ch09/rtda/heap" const jlClass = "java/lang/Class" func init() { native.Register(jlClass, "getPrimitiveClass", "(Ljava/lang/String;)Ljava/lang/Class;", getPrimitiveClass) native.Register(jlClass, "getName0", "()Ljava/lang/String;", getName0) native.Register(jlClass, "desiredAssertionStatus0", "(Ljava/lang/Class;)Z", desiredAssertionStatus0) //native.Register(jlClass, "isInterface", "()Z", isInterface) //native.Register(jlClass, "isPrimitive", "()Z", isPrimitive) } // static native Class<?> getPrimitiveClass(String name); // (Ljava/lang/String;)Ljava/lang/Class; func getPrimitiveClass(frame *rtda.Frame) { nameObj := frame.LocalVars().GetRef(0) name := heap.GoString(nameObj) loader := frame.Method().Class().Loader() class := loader.LoadClass(name).JClass() frame.OperandStack().PushRef(class) } // private native String getName0(); // ()Ljava/lang/String; func getName0(frame *rtda.Frame) { this := frame.LocalVars().GetThis() class := this.Extra().(*heap.Class) name := class.JavaName() nameObj := heap.JString(class.Loader(), name) frame.OperandStack().PushRef(nameObj) } // private static native boolean desiredAssertionStatus0(Class<?> clazz); // (Ljava/lang/Class;)Z func desiredAssertionStatus0(frame *rtda.Frame) { // todo frame.OperandStack().PushBoolean(false) } // public native boolean isInterface(); // ()Z func isInterface(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) stack := frame.OperandStack() stack.PushBoolean(class.IsInterface()) } // public native boolean isPrimitive(); // ()Z func isPrimitive(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) stack := frame.OperandStack() stack.PushBoolean(class.IsPrimitive()) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/native/java/lang/Class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
483
```go package rtda import "jvmgo/ch09/rtda/heap" /* 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) TopFrame() *Frame { return self.stack.top() } func (self *Thread) IsStackEmpty() bool { return self.stack.isEmpty() } func (self *Thread) NewFrame(method *heap.Method) *Frame { return newFrame(self, method) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/thread.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
241
```go package rtda import "math" import "jvmgo/ch09/rtda/heap" 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 *heap.Object) { self.slots[self.size].ref = ref self.size++ } func (self *OperandStack) PopRef() *heap.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] } func (self *OperandStack) GetRefFromTop(n uint) *heap.Object { return self.slots[self.size-1-n].ref } func (self *OperandStack) PushBoolean(val bool) { if val { self.PushInt(1) } else { self.PushInt(0) } } func (self *OperandStack) PopBoolean() bool { return self.PopInt() == 1 } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/operand_stack.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
606
```go package rtda import "math" import "jvmgo/ch09/rtda/heap" 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 *heap.Object) { self[index].ref = ref } func (self LocalVars) GetRef(index uint) *heap.Object { return self[index].ref } func (self LocalVars) SetSlot(index uint, slot Slot) { self[index] = slot } func (self LocalVars) GetThis() *heap.Object { return self.GetRef(0) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/local_vars.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
436
```go package rtda import "jvmgo/ch09/rtda/heap" type Slot struct { num int32 ref *heap.Object } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/slot.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
33
```go package rtda import "jvmgo/ch09/rtda/heap" // stack frame type Frame struct { lower *Frame // stack is implemented as linked list localVars LocalVars operandStack *OperandStack thread *Thread method *heap.Method nextPC int // the next instruction after the call } func newFrame(thread *Thread, method *heap.Method) *Frame { return &Frame{ thread: thread, method: method, localVars: newLocalVars(method.MaxLocals()), operandStack: newOperandStack(method.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) Method() *heap.Method { return self.method } func (self *Frame) NextPC() int { return self.nextPC } func (self *Frame) SetNextPC(nextPC int) { self.nextPC = nextPC } func (self *Frame) RevertNextPC() { self.nextPC = self.thread.pc } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/frame.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
272
```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 } func (self *Stack) isEmpty() bool { return self._top == nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/jvm_stack.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
225
```go package heap // symbolic reference type SymRef struct { cp *ConstantPool className string class *Class } func (self *SymRef) ResolvedClass() *Class { if self.class == nil { self.resolveClassRef() } return self.class } // jvms8 5.4.3.1 func (self *SymRef) resolveClassRef() { d := self.cp.class c := d.loader.LoadClass(self.className) if !c.isAccessibleTo(d) { panic("java.lang.IllegalAccessError") } self.class = c } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/cp_symref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
129
```go package heap import "jvmgo/ch09/classfile" type MethodRef struct { MemberRef method *Method } func newMethodRef(cp *ConstantPool, refInfo *classfile.ConstantMethodrefInfo) *MethodRef { ref := &MethodRef{} ref.cp = cp ref.copyMemberRefInfo(&refInfo.ConstantMemberrefInfo) return ref } func (self *MethodRef) ResolvedMethod() *Method { if self.method == nil { self.resolveMethodRef() } return self.method } // jvms8 5.4.3.3 func (self *MethodRef) resolveMethodRef() { d := self.cp.class c := self.ResolvedClass() if c.IsInterface() { panic("java.lang.IncompatibleClassChangeError") } method := lookupMethod(c, self.name, self.descriptor) if method == nil { panic("java.lang.NoSuchMethodError") } if !method.isAccessibleTo(d) { panic("java.lang.IllegalAccessError") } self.method = method } func lookupMethod(class *Class, name, descriptor string) *Method { method := LookupMethodInClass(class, name, descriptor) if method == nil { method = lookupMethodInInterfaces(class.interfaces, name, descriptor) } return method } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/cp_methodref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
277
```go package heap import "fmt" import "jvmgo/ch09/classfile" type Constant interface{} type ConstantPool struct { class *Class consts []Constant } func newConstantPool(class *Class, cfCp classfile.ConstantPool) *ConstantPool { cpCount := len(cfCp) consts := make([]Constant, cpCount) rtCp := &ConstantPool{class, consts} for i := 1; i < cpCount; i++ { cpInfo := cfCp[i] switch cpInfo.(type) { case *classfile.ConstantIntegerInfo: intInfo := cpInfo.(*classfile.ConstantIntegerInfo) consts[i] = intInfo.Value() case *classfile.ConstantFloatInfo: floatInfo := cpInfo.(*classfile.ConstantFloatInfo) consts[i] = floatInfo.Value() case *classfile.ConstantLongInfo: longInfo := cpInfo.(*classfile.ConstantLongInfo) consts[i] = longInfo.Value() i++ case *classfile.ConstantDoubleInfo: doubleInfo := cpInfo.(*classfile.ConstantDoubleInfo) consts[i] = doubleInfo.Value() i++ case *classfile.ConstantStringInfo: stringInfo := cpInfo.(*classfile.ConstantStringInfo) consts[i] = stringInfo.String() case *classfile.ConstantClassInfo: classInfo := cpInfo.(*classfile.ConstantClassInfo) consts[i] = newClassRef(rtCp, classInfo) case *classfile.ConstantFieldrefInfo: fieldrefInfo := cpInfo.(*classfile.ConstantFieldrefInfo) consts[i] = newFieldRef(rtCp, fieldrefInfo) case *classfile.ConstantMethodrefInfo: methodrefInfo := cpInfo.(*classfile.ConstantMethodrefInfo) consts[i] = newMethodRef(rtCp, methodrefInfo) case *classfile.ConstantInterfaceMethodrefInfo: methodrefInfo := cpInfo.(*classfile.ConstantInterfaceMethodrefInfo) consts[i] = newInterfaceMethodRef(rtCp, methodrefInfo) default: // todo } } return rtCp } func (self *ConstantPool) GetConstant(index uint) Constant { if c := self.consts[index]; c != nil { return c } panic(fmt.Sprintf("No constants at index %d", index)) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/constant_pool.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
517
```go package heap import "strings" import "jvmgo/ch09/classfile" // name, superClassName and interfaceNames are all binary names(jvms8-4.2.1) type Class struct { accessFlags uint16 name string // thisClassName superClassName string interfaceNames []string constantPool *ConstantPool fields []*Field methods []*Method loader *ClassLoader superClass *Class interfaces []*Class instanceSlotCount uint staticSlotCount uint staticVars Slots initStarted bool jClass *Object } func newClass(cf *classfile.ClassFile) *Class { class := &Class{} class.accessFlags = cf.AccessFlags() class.name = cf.ClassName() class.superClassName = cf.SuperClassName() class.interfaceNames = cf.InterfaceNames() class.constantPool = newConstantPool(class, cf.ConstantPool()) class.fields = newFields(class, cf.Fields()) class.methods = newMethods(class, cf.Methods()) return class } func (self *Class) IsPublic() bool { return 0 != self.accessFlags&ACC_PUBLIC } func (self *Class) IsFinal() bool { return 0 != self.accessFlags&ACC_FINAL } func (self *Class) IsSuper() bool { return 0 != self.accessFlags&ACC_SUPER } func (self *Class) IsInterface() bool { return 0 != self.accessFlags&ACC_INTERFACE } func (self *Class) IsAbstract() bool { return 0 != self.accessFlags&ACC_ABSTRACT } func (self *Class) IsSynthetic() bool { return 0 != self.accessFlags&ACC_SYNTHETIC } func (self *Class) IsAnnotation() bool { return 0 != self.accessFlags&ACC_ANNOTATION } func (self *Class) IsEnum() bool { return 0 != self.accessFlags&ACC_ENUM } // getters func (self *Class) Name() string { return self.name } func (self *Class) ConstantPool() *ConstantPool { return self.constantPool } func (self *Class) Fields() []*Field { return self.fields } func (self *Class) Methods() []*Method { return self.methods } func (self *Class) Loader() *ClassLoader { return self.loader } func (self *Class) SuperClass() *Class { return self.superClass } func (self *Class) StaticVars() Slots { return self.staticVars } func (self *Class) InitStarted() bool { return self.initStarted } func (self *Class) JClass() *Object { return self.jClass } func (self *Class) StartInit() { self.initStarted = true } // jvms 5.4.4 func (self *Class) isAccessibleTo(other *Class) bool { return self.IsPublic() || self.GetPackageName() == other.GetPackageName() } func (self *Class) GetPackageName() string { if i := strings.LastIndex(self.name, "/"); i >= 0 { return self.name[:i] } return "" } func (self *Class) GetMainMethod() *Method { return self.getMethod("main", "([Ljava/lang/String;)V", true) } func (self *Class) GetClinitMethod() *Method { return self.getMethod("<clinit>", "()V", true) } func (self *Class) getMethod(name, descriptor string, isStatic bool) *Method { for c := self; c != nil; c = c.superClass { for _, method := range c.methods { if method.IsStatic() == isStatic && method.name == name && method.descriptor == descriptor { return method } } } return nil } func (self *Class) getField(name, descriptor string, isStatic bool) *Field { for c := self; c != nil; c = c.superClass { for _, field := range c.fields { if field.IsStatic() == isStatic && field.name == name && field.descriptor == descriptor { return field } } } return nil } func (self *Class) isJlObject() bool { return self.name == "java/lang/Object" } func (self *Class) isJlCloneable() bool { return self.name == "java/lang/Cloneable" } func (self *Class) isJioSerializable() bool { return self.name == "java/io/Serializable" } func (self *Class) NewObject() *Object { return newObject(self) } func (self *Class) ArrayClass() *Class { arrayClassName := getArrayClassName(self.name) return self.loader.LoadClass(arrayClassName) } func (self *Class) JavaName() string { return strings.Replace(self.name, "/", ".", -1) } func (self *Class) IsPrimitive() bool { _, ok := primitiveTypes[self.name] return ok } func (self *Class) GetInstanceMethod(name, descriptor string) *Method { return self.getMethod(name, descriptor, false) } func (self *Class) GetRefVar(fieldName, fieldDescriptor string) *Object { field := self.getField(fieldName, fieldDescriptor, true) return self.staticVars.GetRef(field.slotId) } func (self *Class) SetRefVar(fieldName, fieldDescriptor string, ref *Object) { field := self.getField(fieldName, fieldDescriptor, true) self.staticVars.SetRef(field.slotId, ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,167
```go package heap import "jvmgo/ch09/classfile" type FieldRef struct { MemberRef field *Field } func newFieldRef(cp *ConstantPool, refInfo *classfile.ConstantFieldrefInfo) *FieldRef { ref := &FieldRef{} ref.cp = cp ref.copyMemberRefInfo(&refInfo.ConstantMemberrefInfo) return ref } func (self *FieldRef) ResolvedField() *Field { if self.field == nil { self.resolveFieldRef() } return self.field } // jvms 5.4.3.2 func (self *FieldRef) resolveFieldRef() { d := self.cp.class c := self.ResolvedClass() field := lookupField(c, self.name, self.descriptor) if field == nil { panic("java.lang.NoSuchFieldError") } if !field.isAccessibleTo(d) { panic("java.lang.IllegalAccessError") } self.field = field } func lookupField(c *Class, name, descriptor string) *Field { for _, field := range c.fields { if field.name == name && field.descriptor == descriptor { return field } } for _, iface := range c.interfaces { if field := lookupField(iface, name, descriptor); field != nil { return field } } if c.superClass != nil { return lookupField(c.superClass, name, descriptor) } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/cp_fieldref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
308
```go package heap // jvms8 6.5.instanceof // jvms8 6.5.checkcast func (self *Class) isAssignableFrom(other *Class) bool { s, t := other, self if s == t { return true } if !s.IsArray() { if !s.IsInterface() { // s is class if !t.IsInterface() { // t is not interface return s.IsSubClassOf(t) } else { // t is interface return s.IsImplements(t) } } else { // s is interface if !t.IsInterface() { // t is not interface return t.isJlObject() } else { // t is interface return t.isSuperInterfaceOf(s) } } } else { // s is array if !t.IsArray() { if !t.IsInterface() { // t is class return t.isJlObject() } else { // t is interface return t.isJlCloneable() || t.isJioSerializable() } } else { // t is array sc := s.ComponentClass() tc := t.ComponentClass() return sc == tc || tc.isAssignableFrom(sc) } } return false } // self extends c func (self *Class) IsSubClassOf(other *Class) bool { for c := self.superClass; c != nil; c = c.superClass { if c == other { return true } } return false } // self implements iface func (self *Class) IsImplements(iface *Class) bool { for c := self; c != nil; c = c.superClass { for _, i := range c.interfaces { if i == iface || i.isSubInterfaceOf(iface) { return true } } } return false } // self extends iface func (self *Class) isSubInterfaceOf(iface *Class) bool { for _, superInterface := range self.interfaces { if superInterface == iface || superInterface.isSubInterfaceOf(iface) { return true } } return false } // c extends self func (self *Class) IsSuperClassOf(other *Class) bool { return other.IsSubClassOf(self) } // iface extends self func (self *Class) isSuperInterfaceOf(iface *Class) bool { return iface.isSubInterfaceOf(self) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/class_hierarchy.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
568
```go package heap import "jvmgo/ch09/classfile" type ClassRef struct { SymRef } func newClassRef(cp *ConstantPool, classInfo *classfile.ConstantClassInfo) *ClassRef { ref := &ClassRef{} ref.cp = cp ref.className = classInfo.Name() return ref } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/cp_classref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
68
```go package heap import "strings" type MethodDescriptorParser struct { raw string offset int parsed *MethodDescriptor } func parseMethodDescriptor(descriptor string) *MethodDescriptor { parser := &MethodDescriptorParser{} return parser.parse(descriptor) } func (self *MethodDescriptorParser) parse(descriptor string) *MethodDescriptor { self.raw = descriptor self.parsed = &MethodDescriptor{} self.startParams() self.parseParamTypes() self.endParams() self.parseReturnType() self.finish() return self.parsed } func (self *MethodDescriptorParser) startParams() { if self.readUint8() != '(' { self.causePanic() } } func (self *MethodDescriptorParser) endParams() { if self.readUint8() != ')' { self.causePanic() } } func (self *MethodDescriptorParser) finish() { if self.offset != len(self.raw) { self.causePanic() } } func (self *MethodDescriptorParser) causePanic() { panic("BAD descriptor: " + self.raw) } func (self *MethodDescriptorParser) readUint8() uint8 { b := self.raw[self.offset] self.offset++ return b } func (self *MethodDescriptorParser) unreadUint8() { self.offset-- } func (self *MethodDescriptorParser) parseParamTypes() { for { t := self.parseFieldType() if t != "" { self.parsed.addParameterType(t) } else { break } } } func (self *MethodDescriptorParser) parseReturnType() { if self.readUint8() == 'V' { self.parsed.returnType = "V" return } self.unreadUint8() t := self.parseFieldType() if t != "" { self.parsed.returnType = t return } self.causePanic() } func (self *MethodDescriptorParser) parseFieldType() string { switch self.readUint8() { case 'B': return "B" case 'C': return "C" case 'D': return "D" case 'F': return "F" case 'I': return "I" case 'J': return "J" case 'S': return "S" case 'Z': return "Z" case 'L': return self.parseObjectType() case '[': return self.parseArrayType() default: self.unreadUint8() return "" } } func (self *MethodDescriptorParser) parseObjectType() string { unread := self.raw[self.offset:] semicolonIndex := strings.IndexRune(unread, ';') if semicolonIndex == -1 { self.causePanic() return "" } else { objStart := self.offset - 1 objEnd := self.offset + semicolonIndex + 1 self.offset = objEnd descriptor := self.raw[objStart:objEnd] return descriptor } } func (self *MethodDescriptorParser) parseArrayType() string { arrStart := self.offset - 1 self.parseFieldType() arrEnd := self.offset descriptor := self.raw[arrStart:arrEnd] return descriptor } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/method_descriptor_parser.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
675
```go package heap import "jvmgo/ch09/classfile" type ClassMember struct { accessFlags uint16 name string descriptor string class *Class } func (self *ClassMember) copyMemberInfo(memberInfo *classfile.MemberInfo) { self.accessFlags = memberInfo.AccessFlags() self.name = memberInfo.Name() self.descriptor = memberInfo.Descriptor() } func (self *ClassMember) IsPublic() bool { return 0 != self.accessFlags&ACC_PUBLIC } func (self *ClassMember) IsPrivate() bool { return 0 != self.accessFlags&ACC_PRIVATE } func (self *ClassMember) IsProtected() bool { return 0 != self.accessFlags&ACC_PROTECTED } func (self *ClassMember) IsStatic() bool { return 0 != self.accessFlags&ACC_STATIC } func (self *ClassMember) IsFinal() bool { return 0 != self.accessFlags&ACC_FINAL } func (self *ClassMember) IsSynthetic() bool { return 0 != self.accessFlags&ACC_SYNTHETIC } // getters func (self *ClassMember) Name() string { return self.name } func (self *ClassMember) Descriptor() string { return self.descriptor } func (self *ClassMember) Class() *Class { return self.class } // jvms 5.4.4 func (self *ClassMember) isAccessibleTo(d *Class) bool { if self.IsPublic() { return true } c := self.class if self.IsProtected() { return d == c || d.IsSubClassOf(c) || c.GetPackageName() == d.GetPackageName() } if !self.IsPrivate() { return c.GetPackageName() == d.GetPackageName() } return d == c } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/class_member.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
387
```go package heap import "unicode/utf16" var internedStrings = map[string]*Object{} // todo // go string -> java.lang.String func JString(loader *ClassLoader, goStr string) *Object { if internedStr, ok := internedStrings[goStr]; ok { return internedStr } chars := stringToUtf16(goStr) jChars := &Object{loader.LoadClass("[C"), chars, nil} jStr := loader.LoadClass("java/lang/String").NewObject() jStr.SetRefVar("value", "[C", jChars) internedStrings[goStr] = jStr return jStr } // java.lang.String -> go string func GoString(jStr *Object) string { charArr := jStr.GetRefVar("value", "[C") return utf16ToString(charArr.Chars()) } // utf8 -> utf16 func stringToUtf16(s string) []uint16 { runes := []rune(s) // utf32 return utf16.Encode(runes) // func Encode(s []rune) []uint16 } // utf16 -> utf8 func utf16ToString(s []uint16) string { runes := utf16.Decode(s) // func Decode(s []uint16) []rune return string(runes) } // todo func InternString(jStr *Object) *Object { goStr := GoString(jStr) if internedStr, ok := internedStrings[goStr]; ok { return internedStr } internedStrings[goStr] = jStr return jStr } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/string_pool.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
342
```go package heap var primitiveTypes = map[string]string{ "void": "V", "boolean": "Z", "byte": "B", "short": "S", "int": "I", "long": "J", "char": "C", "float": "F", "double": "D", } // [XXX -> [[XXX // int -> [I // XXX -> [LXXX; func getArrayClassName(className string) string { return "[" + toDescriptor(className) } // [[XXX -> [XXX // [LXXX; -> XXX // [I -> int func getComponentClassName(className string) string { if className[0] == '[' { componentTypeDescriptor := className[1:] return toClassName(componentTypeDescriptor) } panic("Not array: " + className) } // [XXX => [XXX // int => I // XXX => LXXX; func toDescriptor(className string) string { if className[0] == '[' { // array return className } if d, ok := primitiveTypes[className]; ok { // primitive return d } // object return "L" + className + ";" } // [XXX => [XXX // LXXX; => XXX // I => int func toClassName(descriptor string) string { if descriptor[0] == '[' { // array return descriptor } if descriptor[0] == 'L' { // object return descriptor[1 : len(descriptor)-1] } for className, d := range primitiveTypes { if d == descriptor { // primitive return className } } panic("Invalid descriptor: " + descriptor) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/class_name_helper.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
387
```go package heap type Object struct { class *Class data interface{} // Slots for Object, []int32 for int[] ... extra interface{} } // create normal (non-array) object func newObject(class *Class) *Object { return &Object{ class: class, data: newSlots(class.instanceSlotCount), } } // getters & setters func (self *Object) Class() *Class { return self.class } func (self *Object) Fields() Slots { return self.data.(Slots) } func (self *Object) Extra() interface{} { return self.extra } func (self *Object) SetExtra(extra interface{}) { self.extra = extra } func (self *Object) IsInstanceOf(class *Class) bool { return class.isAssignableFrom(self.class) } // reflection func (self *Object) GetRefVar(name, descriptor string) *Object { field := self.class.getField(name, descriptor, false) slots := self.data.(Slots) return slots.GetRef(field.slotId) } func (self *Object) SetRefVar(name, descriptor string, ref *Object) { field := self.class.getField(name, descriptor, false) slots := self.data.(Slots) slots.SetRef(field.slotId, ref) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/object.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
266
```go package heap import "jvmgo/ch09/classfile" type MemberRef struct { SymRef name string descriptor string } func (self *MemberRef) copyMemberRefInfo(refInfo *classfile.ConstantMemberrefInfo) { self.className = refInfo.ClassName() self.name, self.descriptor = refInfo.NameAndDescriptor() } func (self *MemberRef) Name() string { return self.name } func (self *MemberRef) Descriptor() string { return self.descriptor } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/cp_memberref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
107
```go package heap type MethodDescriptor struct { parameterTypes []string returnType string } func (self *MethodDescriptor) addParameterType(t string) { pLen := len(self.parameterTypes) if pLen == cap(self.parameterTypes) { s := make([]string, pLen, pLen+4) copy(s, self.parameterTypes) self.parameterTypes = s } self.parameterTypes = append(self.parameterTypes, t) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/method_descriptor.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
97
```go package heap import "jvmgo/ch09/classfile" type Method struct { ClassMember maxStack uint maxLocals uint code []byte argSlotCount uint } func newMethods(class *Class, cfMethods []*classfile.MemberInfo) []*Method { methods := make([]*Method, len(cfMethods)) for i, cfMethod := range cfMethods { methods[i] = newMethod(class, cfMethod) } return methods } func newMethod(class *Class, cfMethod *classfile.MemberInfo) *Method { method := &Method{} method.class = class method.copyMemberInfo(cfMethod) method.copyAttributes(cfMethod) md := parseMethodDescriptor(method.descriptor) method.calcArgSlotCount(md.parameterTypes) if method.IsNative() { method.injectCodeAttribute(md.returnType) } return method } func (self *Method) copyAttributes(cfMethod *classfile.MemberInfo) { if codeAttr := cfMethod.CodeAttribute(); codeAttr != nil { self.maxStack = codeAttr.MaxStack() self.maxLocals = codeAttr.MaxLocals() self.code = codeAttr.Code() } } func (self *Method) calcArgSlotCount(paramTypes []string) { for _, paramType := range paramTypes { self.argSlotCount++ if paramType == "J" || paramType == "D" { self.argSlotCount++ } } if !self.IsStatic() { self.argSlotCount++ // `this` reference } } func (self *Method) injectCodeAttribute(returnType string) { self.maxStack = 4 // todo self.maxLocals = self.argSlotCount switch returnType[0] { case 'V': self.code = []byte{0xfe, 0xb1} // return case 'L', '[': self.code = []byte{0xfe, 0xb0} // areturn case 'D': self.code = []byte{0xfe, 0xaf} // dreturn case 'F': self.code = []byte{0xfe, 0xae} // freturn case 'J': self.code = []byte{0xfe, 0xad} // lreturn default: self.code = []byte{0xfe, 0xac} // ireturn } } func (self *Method) IsSynchronized() bool { return 0 != self.accessFlags&ACC_SYNCHRONIZED } func (self *Method) IsBridge() bool { return 0 != self.accessFlags&ACC_BRIDGE } func (self *Method) IsVarargs() bool { return 0 != self.accessFlags&ACC_VARARGS } func (self *Method) IsNative() bool { return 0 != self.accessFlags&ACC_NATIVE } func (self *Method) IsAbstract() bool { return 0 != self.accessFlags&ACC_ABSTRACT } func (self *Method) IsStrict() bool { return 0 != self.accessFlags&ACC_STRICT } // getters func (self *Method) MaxStack() uint { return self.maxStack } func (self *Method) MaxLocals() uint { return self.maxLocals } func (self *Method) Code() []byte { return self.code } func (self *Method) ArgSlotCount() uint { return self.argSlotCount } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/method.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
720
```go package heap const ( ACC_PUBLIC = 0x0001 // class field method ACC_PRIVATE = 0x0002 // field method ACC_PROTECTED = 0x0004 // field method ACC_STATIC = 0x0008 // field method ACC_FINAL = 0x0010 // class field method ACC_SUPER = 0x0020 // class ACC_SYNCHRONIZED = 0x0020 // method ACC_VOLATILE = 0x0040 // field ACC_BRIDGE = 0x0040 // method ACC_TRANSIENT = 0x0080 // field ACC_VARARGS = 0x0080 // method ACC_NATIVE = 0x0100 // method ACC_INTERFACE = 0x0200 // class ACC_ABSTRACT = 0x0400 // class method ACC_STRICT = 0x0800 // method ACC_SYNTHETIC = 0x1000 // class field method ACC_ANNOTATION = 0x2000 // class ACC_ENUM = 0x4000 // class field ) ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/access_flags.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
278
```go package heap func LookupMethodInClass(class *Class, name, descriptor string) *Method { for c := class; c != nil; c = c.superClass { for _, method := range c.methods { if method.name == name && method.descriptor == descriptor { return method } } } return nil } func lookupMethodInInterfaces(ifaces []*Class, name, descriptor string) *Method { for _, iface := range ifaces { for _, method := range iface.methods { if method.name == name && method.descriptor == descriptor { return method } } method := lookupMethodInInterfaces(iface.interfaces, name, descriptor) if method != nil { return method } } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch09/rtda/heap/method_lookup.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
164