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 loads import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/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/ch11/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 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/ch11/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 references import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/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/ch11/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 "reflect" import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" // Throw exception or error type ATHROW struct{ base.NoOperandsInstruction } func (self *ATHROW) Execute(frame *rtda.Frame) { ex := frame.OperandStack().PopRef() if ex == nil { panic("java.lang.NullPointerException") } thread := frame.Thread() if !findAndGotoExceptionHandler(thread, ex) { handleUncaughtException(thread, ex) } } func findAndGotoExceptionHandler(thread *rtda.Thread, ex *heap.Object) bool { for { frame := thread.CurrentFrame() pc := frame.NextPC() - 1 handlerPC := frame.Method().FindExceptionHandler(ex.Class(), pc) if handlerPC > 0 { stack := frame.OperandStack() stack.Clear() stack.PushRef(ex) frame.SetNextPC(handlerPC) return true } thread.PopFrame() if thread.IsStackEmpty() { break } } return false } // todo func handleUncaughtException(thread *rtda.Thread, ex *heap.Object) { thread.ClearStack() jMsg := ex.GetRefVar("detailMessage", "Ljava/lang/String;") goMsg := heap.GoString(jMsg) println(ex.Class().JavaName() + ": " + goMsg) stes := reflect.ValueOf(ex.Extra()) for i := 0; i < stes.Len(); i++ { ste := stes.Index(i).Interface().(interface { String() string }) println("\tat " + ste.String()) } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/references/athrow.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
373
```go package comparisons import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/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/ch11/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 main func main() { cmd := parseCmd() if cmd.versionFlag { println("version 0.0.1") } else if cmd.helpFlag || cmd.class == "" { printUsage() } else { newJVM(cmd).start() } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/main.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
61
```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/ch11/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 conversions import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/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/ch11/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 stores import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" // Store long into local variable type LSTORE struct{ base.Index8Instruction } func (self *LSTORE) Execute(frame *rtda.Frame) { _lstore(frame, uint(self.Index)) } type LSTORE_0 struct{ base.NoOperandsInstruction } func (self *LSTORE_0) Execute(frame *rtda.Frame) { _lstore(frame, 0) } type LSTORE_1 struct{ base.NoOperandsInstruction } func (self *LSTORE_1) Execute(frame *rtda.Frame) { _lstore(frame, 1) } type LSTORE_2 struct{ base.NoOperandsInstruction } func (self *LSTORE_2) Execute(frame *rtda.Frame) { _lstore(frame, 2) } type LSTORE_3 struct{ base.NoOperandsInstruction } func (self *LSTORE_3) Execute(frame *rtda.Frame) { _lstore(frame, 3) } func _lstore(frame *rtda.Frame, index uint) { val := frame.OperandStack().PopLong() frame.LocalVars().SetLong(index, val) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/instructions/stores/lstore.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
265
```go package 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 } func (self *CodeAttribute) LineNumberTableAttribute() *LineNumberTableAttribute { for _, attrInfo := range self.attributes { switch attrInfo.(type) { case *LineNumberTableAttribute: return attrInfo.(*LineNumberTableAttribute) } } return nil } 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/ch11/classfile/attr_code.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
583
```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/ch11/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 /* 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/ch11/classfile/cp_member_ref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
241
```go package classfile var ( _attrDeprecated = &DeprecatedAttribute{} _attrSynthetic = &SyntheticAttribute{} ) /* attribute_info { u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; } */ type AttributeInfo interface { readInfo(reader *ClassReader) } func readAttributes(reader *ClassReader, cp ConstantPool) []AttributeInfo { attributesCount := reader.readUint16() attributes := make([]AttributeInfo, attributesCount) for i := range attributes { attributes[i] = readAttribute(reader, cp) } return attributes } func readAttribute(reader *ClassReader, cp ConstantPool) AttributeInfo { attrNameIndex := reader.readUint16() attrName := cp.getUtf8(attrNameIndex) attrLen := reader.readUint32() attrInfo := newAttributeInfo(attrName, attrLen, cp) attrInfo.readInfo(reader) return attrInfo } func newAttributeInfo(attrName string, attrLen uint32, cp ConstantPool) AttributeInfo { switch attrName { // case "AnnotationDefault": case "BootstrapMethods": return &BootstrapMethodsAttribute{} case "Code": return &CodeAttribute{cp: cp} case "ConstantValue": return &ConstantValueAttribute{} case "Deprecated": return _attrDeprecated case "EnclosingMethod": return &EnclosingMethodAttribute{cp: cp} case "Exceptions": return &ExceptionsAttribute{} case "InnerClasses": return &InnerClassesAttribute{} case "LineNumberTable": return &LineNumberTableAttribute{} case "LocalVariableTable": return &LocalVariableTableAttribute{} case "LocalVariableTypeTable": return &LocalVariableTypeTableAttribute{} // case "MethodParameters": // case "RuntimeInvisibleAnnotations": // case "RuntimeInvisibleParameterAnnotations": // case "RuntimeInvisibleTypeAnnotations": // case "RuntimeVisibleAnnotations": // case "RuntimeVisibleParameterAnnotations": // case "RuntimeVisibleTypeAnnotations": case "Signature": return &SignatureAttribute{cp: cp} case "SourceFile": return &SourceFileAttribute{cp: cp} // case "SourceDebugExtension": // case "StackMapTable": case "Synthetic": return _attrSynthetic default: return &UnparsedAttribute{attrName, attrLen, nil} } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classfile/attribute_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
496
```go package classfile /* CONSTANT_String_info { u1 tag; u2 string_index; } */ type ConstantStringInfo struct { cp ConstantPool stringIndex uint16 } func (self *ConstantStringInfo) readInfo(reader *ClassReader) { self.stringIndex = reader.readUint16() } func (self *ConstantStringInfo) String() string { return self.cp.getUtf8(self.stringIndex) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/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 native import "jvmgo/ch11/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" { if methodName == "registerNatives" || methodName == "initIDs" { return emptyNativeMethod } } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/registry.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
177
```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/ch11/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 "fmt" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" const jlThrowable = "java/lang/Throwable" type StackTraceElement struct { fileName string className string methodName string lineNumber int } func (self *StackTraceElement) String() string { return fmt.Sprintf("%s.%s(%s:%d)", self.className, self.methodName, self.fileName, self.lineNumber) } func init() { native.Register(jlThrowable, "fillInStackTrace", "(I)Ljava/lang/Throwable;", fillInStackTrace) } // private native Throwable fillInStackTrace(int dummy); // (I)Ljava/lang/Throwable; func fillInStackTrace(frame *rtda.Frame) { this := frame.LocalVars().GetThis() frame.OperandStack().PushRef(this) stes := createStackTraceElements(this, frame.Thread()) this.SetExtra(stes) } func createStackTraceElements(tObj *heap.Object, thread *rtda.Thread) []*StackTraceElement { skip := distanceToObject(tObj.Class()) + 2 frames := thread.GetFrames()[skip:] stes := make([]*StackTraceElement, len(frames)) for i, frame := range frames { stes[i] = createStackTraceElement(frame) } return stes } func distanceToObject(class *heap.Class) int { distance := 0 for c := class.SuperClass(); c != nil; c = c.SuperClass() { distance++ } return distance } func createStackTraceElement(frame *rtda.Frame) *StackTraceElement { method := frame.Method() class := method.Class() return &StackTraceElement{ fileName: class.SourceFile(), className: class.JavaName(), methodName: method.Name(), lineNumber: method.GetLineNumber(frame.NextPC() - 1), } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Throwable.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
406
```go package lang import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" /* Constructor(Class<T> declaringClass, Class<?>[] parameterTypes, Class<?>[] checkedExceptions, int modifiers, int slot, String signature, byte[] annotations, byte[] parameterAnnotations) } */ const _constructorConstructorDescriptor = "" + "(Ljava/lang/Class;" + "[Ljava/lang/Class;" + "[Ljava/lang/Class;" + "II" + "Ljava/lang/String;" + "[B[B)V" // private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly); // (Z)[Ljava/lang/reflect/Constructor; func getDeclaredConstructors0(frame *rtda.Frame) { vars := frame.LocalVars() classObj := vars.GetThis() publicOnly := vars.GetBoolean(1) class := classObj.Extra().(*heap.Class) constructors := class.GetConstructors(publicOnly) constructorCount := uint(len(constructors)) classLoader := frame.Method().Class().Loader() constructorClass := classLoader.LoadClass("java/lang/reflect/Constructor") constructorArr := constructorClass.ArrayClass().NewArray(constructorCount) stack := frame.OperandStack() stack.PushRef(constructorArr) if constructorCount > 0 { thread := frame.Thread() constructorObjs := constructorArr.Refs() constructorInitMethod := constructorClass.GetConstructor(_constructorConstructorDescriptor) for i, constructor := range constructors { constructorObj := constructorClass.NewObject() constructorObj.SetExtra(constructor) constructorObjs[i] = constructorObj ops := rtda.NewOperandStack(9) ops.PushRef(constructorObj) // this ops.PushRef(classObj) // declaringClass ops.PushRef(toClassArr(classLoader, constructor.ParameterTypes())) // parameterTypes ops.PushRef(toClassArr(classLoader, constructor.ExceptionTypes())) // checkedExceptions ops.PushInt(int32(constructor.AccessFlags())) // modifiers ops.PushInt(int32(0)) // todo slot ops.PushRef(getSignatureStr(classLoader, constructor.Signature())) // signature ops.PushRef(toByteArr(classLoader, constructor.AnnotationData())) // annotations ops.PushRef(toByteArr(classLoader, constructor.ParameterAnnotationData())) // parameterAnnotations shimFrame := rtda.NewShimFrame(thread, ops) thread.PushFrame(shimFrame) // init constructorObj base.InvokeMethod(shimFrame, constructorInitMethod) } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Class_getDeclaredConstructors0.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
573
```go package lang import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/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/ch11/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 "runtime" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" const jlRuntime = "java/lang/Runtime" func init() { native.Register(jlRuntime, "availableProcessors", "()I", availableProcessors) } // public native int availableProcessors(); // ()I func availableProcessors(frame *rtda.Frame) { numCPU := runtime.NumCPU() stack := frame.OperandStack() stack.PushInt(int32(numCPU)) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Runtime.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
108
```go package lang import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { native.Register("java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", currentThread) native.Register("java/lang/Thread", "setPriority0", "(I)V", setPriority0) native.Register("java/lang/Thread", "isAlive", "()Z", isAlive) native.Register("java/lang/Thread", "start0", "()V", start0) } // public static native Thread currentThread(); // ()Ljava/lang/Thread; func currentThread(frame *rtda.Frame) { //jThread := frame.Thread().JThread() classLoader := frame.Method().Class().Loader() threadClass := classLoader.LoadClass("java/lang/Thread") jThread := threadClass.NewObject() threadGroupClass := classLoader.LoadClass("java/lang/ThreadGroup") jGroup := threadGroupClass.NewObject() jThread.SetRefVar("group", "Ljava/lang/ThreadGroup;", jGroup) jThread.SetIntVar("priority", "I", 1) frame.OperandStack().PushRef(jThread) } // private native void setPriority0(int newPriority); // (I)V func setPriority0(frame *rtda.Frame) { // vars := frame.LocalVars() // this := vars.GetThis() // newPriority := vars.GetInt(1)) // todo } // public final native boolean isAlive(); // ()Z func isAlive(frame *rtda.Frame) { //vars := frame.LocalVars() //this := vars.GetThis() stack := frame.OperandStack() stack.PushBoolean(false) } // private native void start0(); // ()V func start0(frame *rtda.Frame) { // todo } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Thread.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
383
```go package lang import "runtime" import "time" import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" const jlSystem = "java/lang/System" func init() { native.Register(jlSystem, "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", arraycopy) native.Register(jlSystem, "initProperties", "(Ljava/util/Properties;)Ljava/util/Properties;", initProperties) native.Register(jlSystem, "setIn0", "(Ljava/io/InputStream;)V", setIn0) native.Register(jlSystem, "setOut0", "(Ljava/io/PrintStream;)V", setOut0) native.Register(jlSystem, "setErr0", "(Ljava/io/PrintStream;)V", setErr0) native.Register(jlSystem, "currentTimeMillis", "()J", currentTimeMillis) } // 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 } // private static native Properties initProperties(Properties props); // (Ljava/util/Properties;)Ljava/util/Properties; func initProperties(frame *rtda.Frame) { vars := frame.LocalVars() props := vars.GetRef(0) stack := frame.OperandStack() stack.PushRef(props) // public synchronized Object setProperty(String key, String value) setPropMethod := props.Class().GetInstanceMethod("setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;") thread := frame.Thread() for key, val := range _sysProps() { jKey := heap.JString(frame.Method().Class().Loader(), key) jVal := heap.JString(frame.Method().Class().Loader(), val) ops := rtda.NewOperandStack(3) ops.PushRef(props) ops.PushRef(jKey) ops.PushRef(jVal) shimFrame := rtda.NewShimFrame(thread, ops) thread.PushFrame(shimFrame) base.InvokeMethod(shimFrame, setPropMethod) } } func _sysProps() map[string]string { return map[string]string{ "java.version": "1.8.0", "java.vendor": "jvm.go", "java.vendor.url": "path_to_url", "java.home": "todo", "java.class.version": "52.0", "java.class.path": "todo", "java.awt.graphicsenv": "sun.awt.CGraphicsEnvironment", "os.name": runtime.GOOS, // todo "os.arch": runtime.GOARCH, // todo "os.version": "", // todo "file.separator": "/", // todo os.PathSeparator "path.separator": ":", // todo os.PathListSeparator "line.separator": "\n", // todo "user.name": "", // todo "user.home": "", // todo "user.dir": ".", // todo "user.country": "CN", // todo "file.encoding": "UTF-8", "sun.stdout.encoding": "UTF-8", "sun.stderr.encoding": "UTF-8", } } // private static native void setIn0(InputStream in); // (Ljava/io/InputStream;)V func setIn0(frame *rtda.Frame) { vars := frame.LocalVars() in := vars.GetRef(0) sysClass := frame.Method().Class() sysClass.SetRefVar("in", "Ljava/io/InputStream;", in) } // private static native void setOut0(PrintStream out); // (Ljava/io/PrintStream;)V func setOut0(frame *rtda.Frame) { vars := frame.LocalVars() out := vars.GetRef(0) sysClass := frame.Method().Class() sysClass.SetRefVar("out", "Ljava/io/PrintStream;", out) } // private static native void setErr0(PrintStream err); // (Ljava/io/PrintStream;)V func setErr0(frame *rtda.Frame) { vars := frame.LocalVars() err := vars.GetRef(0) sysClass := frame.Method().Class() sysClass.SetRefVar("err", "Ljava/io/PrintStream;", err) } // public static native long currentTimeMillis(); // ()J func currentTimeMillis(frame *rtda.Frame) { millis := time.Now().UnixNano() / int64(time.Millisecond) stack := frame.OperandStack() stack.PushLong(millis) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/System.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,262
```go package lang import "unsafe" import "jvmgo/ch11/native" import "jvmgo/ch11/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) native.Register(jlObject, "notifyAll", "()V", notifyAll) } // 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()) } // public final native void notifyAll(); // ()V func notifyAll(frame *rtda.Frame) { // todo } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Object.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
325
```go package lang import "math" import "jvmgo/ch11/native" import "jvmgo/ch11/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/ch11/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 lang import "math" import "jvmgo/ch11/native" import "jvmgo/ch11/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/ch11/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 "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" /* Method(Class<?> declaringClass, String name, Class<?>[] parameterTypes, Class<?> returnType, Class<?>[] checkedExceptions, int modifiers, int slot, String signature, byte[] annotations, byte[] parameterAnnotations, byte[] annotationDefault) */ const _methodConstructorDescriptor = "" + "(Ljava/lang/Class;" + "Ljava/lang/String;" + "[Ljava/lang/Class;" + "Ljava/lang/Class;" + "[Ljava/lang/Class;" + "II" + "Ljava/lang/String;" + "[B[B[B)V" // private native Method[] getDeclaredMethods0(boolean publicOnly); // (Z)[Ljava/lang/reflect/Method; func getDeclaredMethods0(frame *rtda.Frame) { vars := frame.LocalVars() classObj := vars.GetThis() publicOnly := vars.GetBoolean(1) class := classObj.Extra().(*heap.Class) methods := class.GetMethods(publicOnly) methodCount := uint(len(methods)) classLoader := class.Loader() methodClass := classLoader.LoadClass("java/lang/reflect/Method") methodArr := methodClass.ArrayClass().NewArray(methodCount) stack := frame.OperandStack() stack.PushRef(methodArr) // create method objs if methodCount > 0 { thread := frame.Thread() methodObjs := methodArr.Refs() methodConstructor := methodClass.GetConstructor(_methodConstructorDescriptor) for i, method := range methods { methodObj := methodClass.NewObject() methodObj.SetExtra(method) methodObjs[i] = methodObj ops := rtda.NewOperandStack(12) ops.PushRef(methodObj) // this ops.PushRef(classObj) // declaringClass ops.PushRef(heap.JString(classLoader, method.Name())) // name ops.PushRef(toClassArr(classLoader, method.ParameterTypes())) // parameterTypes ops.PushRef(method.ReturnType().JClass()) // returnType ops.PushRef(toClassArr(classLoader, method.ExceptionTypes())) // checkedExceptions ops.PushInt(int32(method.AccessFlags())) // modifiers ops.PushInt(int32(0)) // todo: slot ops.PushRef(getSignatureStr(classLoader, method.Signature())) // signature ops.PushRef(toByteArr(classLoader, method.AnnotationData())) // annotations ops.PushRef(toByteArr(classLoader, method.ParameterAnnotationData())) // parameterAnnotations ops.PushRef(toByteArr(classLoader, method.AnnotationDefaultData())) // annotationDefault shimFrame := rtda.NewShimFrame(thread, ops) thread.PushFrame(shimFrame) // init methodObj base.InvokeMethod(shimFrame, methodConstructor) } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Class_getDeclaredMethods0.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
647
```go package lang import "unsafe" import "jvmgo/ch11/rtda/heap" // []*Class => Class[] func toClassArr(loader *heap.ClassLoader, classes []*heap.Class) *heap.Object { arrLen := len(classes) classArrClass := loader.LoadClass("java/lang/Class").ArrayClass() classArr := classArrClass.NewArray(uint(arrLen)) if arrLen > 0 { classObjs := classArr.Refs() for i, class := range classes { classObjs[i] = class.JClass() } } return classArr } // []byte => byte[] func toByteArr(loader *heap.ClassLoader, goBytes []byte) *heap.Object { if goBytes != nil { jBytes := castUint8sToInt8s(goBytes) return heap.NewByteArray(loader, jBytes) } return nil } func castUint8sToInt8s(goBytes []byte) (jBytes []int8) { ptr := unsafe.Pointer(&goBytes) jBytes = *((*[]int8)(ptr)) return } func getSignatureStr(loader *heap.ClassLoader, signature string) *heap.Object { if signature != "" { return heap.JString(loader, signature) } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Class_helper.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
268
```go package lang import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" /* Field(Class<?> declaringClass, String name, Class<?> type, int modifiers, int slot, String signature, byte[] annotations) */ const _fieldConstructorDescriptor = "" + "(Ljava/lang/Class;" + "Ljava/lang/String;" + "Ljava/lang/Class;" + "II" + "Ljava/lang/String;" + "[B)V" // private native Field[] getDeclaredFields0(boolean publicOnly); // (Z)[Ljava/lang/reflect/Field; func getDeclaredFields0(frame *rtda.Frame) { vars := frame.LocalVars() classObj := vars.GetThis() publicOnly := vars.GetBoolean(1) class := classObj.Extra().(*heap.Class) fields := class.GetFields(publicOnly) fieldCount := uint(len(fields)) classLoader := frame.Method().Class().Loader() fieldClass := classLoader.LoadClass("java/lang/reflect/Field") fieldArr := fieldClass.ArrayClass().NewArray(fieldCount) stack := frame.OperandStack() stack.PushRef(fieldArr) if fieldCount > 0 { thread := frame.Thread() fieldObjs := fieldArr.Refs() fieldConstructor := fieldClass.GetConstructor(_fieldConstructorDescriptor) for i, goField := range fields { fieldObj := fieldClass.NewObject() fieldObj.SetExtra(goField) fieldObjs[i] = fieldObj ops := rtda.NewOperandStack(8) ops.PushRef(fieldObj) // this ops.PushRef(classObj) // declaringClass ops.PushRef(heap.JString(classLoader, goField.Name())) // name ops.PushRef(goField.Type().JClass()) // type ops.PushInt(int32(goField.AccessFlags())) // modifiers ops.PushInt(int32(goField.SlotId())) // slot ops.PushRef(getSignatureStr(classLoader, goField.Signature())) // signature ops.PushRef(toByteArr(classLoader, goField.AnnotationData())) // annotations shimFrame := rtda.NewShimFrame(thread, ops) thread.PushFrame(shimFrame) // init fieldObj base.InvokeMethod(shimFrame, fieldConstructor) } } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Class_getDeclaredFields0.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
524
```go package security import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { native.Register("java/security/AccessController", "doPrivileged", "(Ljava/security/PrivilegedAction;)Ljava/lang/Object;", doPrivileged) native.Register("java/security/AccessController", "doPrivileged", "(Ljava/security/PrivilegedExceptionAction;)Ljava/lang/Object;", doPrivileged) native.Register("java/security/AccessController", "getStackAccessControlContext", "()Ljava/security/AccessControlContext;", getStackAccessControlContext) } // @CallerSensitive // public static native <T> T // doPrivileged(PrivilegedExceptionAction<T> action) // throws PrivilegedActionException; // (Ljava/security/PrivilegedExceptionAction;)Ljava/lang/Object; // @CallerSensitive // public static native <T> T doPrivileged(PrivilegedAction<T> action); // (Ljava/security/PrivilegedAction;)Ljava/lang/Object; func doPrivileged(frame *rtda.Frame) { vars := frame.LocalVars() action := vars.GetRef(0) stack := frame.OperandStack() stack.PushRef(action) method := action.Class().GetInstanceMethod("run", "()Ljava/lang/Object;") // todo base.InvokeMethod(frame, method) } // private static native AccessControlContext getStackAccessControlContext(); // ()Ljava/security/AccessControlContext; func getStackAccessControlContext(frame *rtda.Frame) { // todo frame.OperandStack().PushRef(nil) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/security/AccessController.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
337
```go package io import "path/filepath" import "os" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" const unixfs = "java/io/UnixFileSystem" func init() { native.Register(unixfs, "canonicalize0", "(Ljava/lang/String;)Ljava/lang/String;", canonicalize0) native.Register(unixfs, "getBooleanAttributes0", "(Ljava/io/File;)I", getBooleanAttributes0) } // private native String canonicalize0(String path) throws IOException; // (Ljava/lang/String;)Ljava/lang/String; func canonicalize0(frame *rtda.Frame) { vars := frame.LocalVars() path := vars.GetRef(1) // todo goPath := heap.GoString(path) goPath2 := filepath.Clean(goPath) if goPath2 != goPath { path = heap.JString(frame.Method().Class().Loader(), goPath2) } stack := frame.OperandStack() stack.PushRef(path) } // public native int getBooleanAttributes0(File f); // (Ljava/io/File;)I func getBooleanAttributes0(frame *rtda.Frame) { vars := frame.LocalVars() f := vars.GetRef(1) path := _getPath(f) // todo attributes0 := 0 if _exists(path) { attributes0 |= 0x01 } if _isDir(path) { attributes0 |= 0x04 } stack := frame.OperandStack() stack.PushInt(int32(attributes0)) } func _getPath(fileObj *heap.Object) string { pathStr := fileObj.GetRefVar("path", "Ljava/lang/String;") return heap.GoString(pathStr) } // path_to_url // exists returns whether the given file or directory exists or not func _exists(path string) bool { _, err := os.Stat(path) if err == nil { return true } if os.IsNotExist(err) { return false } return false } // path_to_url func _isDir(path string) bool { fileInfo, err := os.Stat(path) if err == nil { return fileInfo.IsDir() } return false } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/io/UnixFileSystem.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
478
```go package lang import "strings" import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/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) native.Register(jlClass, "getDeclaredFields0", "(Z)[Ljava/lang/reflect/Field;", getDeclaredFields0) native.Register(jlClass, "forName0", "(Ljava/lang/String;ZLjava/lang/ClassLoader;Ljava/lang/Class;)Ljava/lang/Class;", forName0) native.Register(jlClass, "getDeclaredConstructors0", "(Z)[Ljava/lang/reflect/Constructor;", getDeclaredConstructors0) native.Register(jlClass, "getModifiers", "()I", getModifiers) native.Register(jlClass, "getSuperclass", "()Ljava/lang/Class;", getSuperclass) native.Register(jlClass, "getInterfaces0", "()[Ljava/lang/Class;", getInterfaces0) native.Register(jlClass, "isArray", "()Z", isArray) native.Register(jlClass, "getDeclaredMethods0", "(Z)[Ljava/lang/reflect/Method;", getDeclaredMethods0) native.Register(jlClass, "getComponentType", "()Ljava/lang/Class;", getComponentType) native.Register(jlClass, "isAssignableFrom", "(Ljava/lang/Class;)Z", isAssignableFrom) } // 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()) } // private static native Class<?> forName0(String name, boolean initialize, // ClassLoader loader, // Class<?> caller) // throws ClassNotFoundException; // (Ljava/lang/String;ZLjava/lang/ClassLoader;Ljava/lang/Class;)Ljava/lang/Class; func forName0(frame *rtda.Frame) { vars := frame.LocalVars() jName := vars.GetRef(0) initialize := vars.GetBoolean(1) //jLoader := vars.GetRef(2) goName := heap.GoString(jName) goName = strings.Replace(goName, ".", "/", -1) goClass := frame.Method().Class().Loader().LoadClass(goName) jClass := goClass.JClass() if initialize && !goClass.InitStarted() { // undo forName0 thread := frame.Thread() frame.SetNextPC(thread.PC()) // init class base.InitClass(thread, goClass) } else { stack := frame.OperandStack() stack.PushRef(jClass) } } // public native int getModifiers(); // ()I func getModifiers(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) modifiers := class.AccessFlags() stack := frame.OperandStack() stack.PushInt(int32(modifiers)) } // public native Class<? super T> getSuperclass(); // ()Ljava/lang/Class; func getSuperclass(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) superClass := class.SuperClass() stack := frame.OperandStack() if superClass != nil { stack.PushRef(superClass.JClass()) } else { stack.PushRef(nil) } } // private native Class<?>[] getInterfaces0(); // ()[Ljava/lang/Class; func getInterfaces0(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) interfaces := class.Interfaces() classArr := toClassArr(class.Loader(), interfaces) stack := frame.OperandStack() stack.PushRef(classArr) } // public native boolean isArray(); // ()Z func isArray(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) stack := frame.OperandStack() stack.PushBoolean(class.IsArray()) } // public native Class<?> getComponentType(); // ()Ljava/lang/Class; func getComponentType(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() class := this.Extra().(*heap.Class) componentClass := class.ComponentClass() componentClassObj := componentClass.JClass() stack := frame.OperandStack() stack.PushRef(componentClassObj) } // public native boolean isAssignableFrom(Class<?> cls); // (Ljava/lang/Class;)Z func isAssignableFrom(frame *rtda.Frame) { vars := frame.LocalVars() this := vars.GetThis() cls := vars.GetRef(1) thisClass := this.Extra().(*heap.Class) clsClass := cls.Extra().(*heap.Class) ok := thisClass.IsAssignableFrom(clsClass) stack := frame.OperandStack() stack.PushBoolean(ok) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/lang/Class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,441
```go package io import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" const fd = "java/io/FileDescriptor" func init() { native.Register(fd, "set", "(I)J", set) } // private static native long set(int d); // (I)J func set(frame *rtda.Frame) { // todo frame.OperandStack().PushLong(0) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/io/FileDescriptor.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
93
```go package atomic import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { native.Register("java/util/concurrent/atomic/AtomicLong", "VMSupportsCS8", "()Z", vmSupportsCS8) } func vmSupportsCS8(frame *rtda.Frame) { frame.OperandStack().PushBoolean(false) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/util/concurrent/atomic/AtomicLong.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
84
```go package io import "os" import "unsafe" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" const fos = "java/io/FileOutputStream" func init() { native.Register(fos, "writeBytes", "([BIIZ)V", writeBytes) } // private native void writeBytes(byte b[], int off, int len, boolean append) throws IOException; // ([BIIZ)V func writeBytes(frame *rtda.Frame) { vars := frame.LocalVars() //this := vars.GetRef(0) b := vars.GetRef(1) off := vars.GetInt(2) len := vars.GetInt(3) //append := vars.GetBoolean(4) jBytes := b.Data().([]int8) goBytes := castInt8sToUint8s(jBytes) goBytes = goBytes[off : off+len] os.Stdout.Write(goBytes) } func castInt8sToUint8s(jBytes []int8) (goBytes []byte) { ptr := unsafe.Pointer(&jBytes) goBytes = *((*[]byte)(ptr)) return } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/java/io/FileOutputStream.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
238
```go package io import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { native.Register("sun/io/Win32ErrorMode", "setErrorMode", "(J)J", setErrorMode) } func setErrorMode(frame *rtda.Frame) { // todo frame.OperandStack().PushLong(0) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/io/Win32ErrorMode.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
79
```go package reflect import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" func init() { native.Register("sun/reflect/Reflection", "getCallerClass", "()Ljava/lang/Class;", getCallerClass) native.Register("sun/reflect/Reflection", "getClassAccessFlags", "(Ljava/lang/Class;)I", getClassAccessFlags) } // public static native Class<?> getCallerClass(); // ()Ljava/lang/Class; func getCallerClass(frame *rtda.Frame) { // top0 is sun/reflect/Reflection // top1 is the caller of getCallerClass() // top2 is the caller of method callerFrame := frame.Thread().GetFrames()[2] // todo callerClass := callerFrame.Method().Class().JClass() frame.OperandStack().PushRef(callerClass) } // public static native int getClassAccessFlags(Class<?> type); // (Ljava/lang/Class;)I func getClassAccessFlags(frame *rtda.Frame) { vars := frame.LocalVars() _type := vars.GetRef(0) goClass := _type.Extra().(*heap.Class) flags := goClass.AccessFlags() stack := frame.OperandStack() stack.PushInt(int32(flags)) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/reflect/Reflection.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
279
```go package reflect import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" func init() { native.Register("sun/reflect/NativeConstructorAccessorImpl", "newInstance0", "(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;", newInstance0) } // private static native Object newInstance0(Constructor<?> c, Object[] os) // throws InstantiationException, IllegalArgumentException, InvocationTargetException; // (Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object; func newInstance0(frame *rtda.Frame) { vars := frame.LocalVars() constructorObj := vars.GetRef(0) argArrObj := vars.GetRef(1) goConstructor := getGoConstructor(constructorObj) goClass := goConstructor.Class() if !goClass.InitStarted() { frame.RevertNextPC() base.InitClass(frame.Thread(), goClass) return } obj := goClass.NewObject() stack := frame.OperandStack() stack.PushRef(obj) // call <init> ops := convertArgs(obj, argArrObj, goConstructor) shimFrame := rtda.NewShimFrame(frame.Thread(), ops) frame.Thread().PushFrame(shimFrame) base.InvokeMethod(shimFrame, goConstructor) } func getGoMethod(methodObj *heap.Object) *heap.Method { return _getGoMethod(methodObj, false) } func getGoConstructor(constructorObj *heap.Object) *heap.Method { return _getGoMethod(constructorObj, true) } func _getGoMethod(methodObj *heap.Object, isConstructor bool) *heap.Method { extra := methodObj.Extra() if extra != nil { return extra.(*heap.Method) } if isConstructor { root := methodObj.GetRefVar("root", "Ljava/lang/reflect/Constructor;") return root.Extra().(*heap.Method) } else { root := methodObj.GetRefVar("root", "Ljava/lang/reflect/Method;") return root.Extra().(*heap.Method) } } // Object[] -> []interface{} func convertArgs(this, argArr *heap.Object, method *heap.Method) *rtda.OperandStack { if method.ArgSlotCount() == 0 { return nil } // argObjs := argArr.Refs() // argTypes := method.ParsedDescriptor().ParameterTypes() ops := rtda.NewOperandStack(method.ArgSlotCount()) if !method.IsStatic() { ops.PushRef(this) } if method.ArgSlotCount() == 1 && !method.IsStatic() { return ops } // for i, argType := range argTypes { // argObj := argObjs[i] // // if len(argType) == 1 { // // base type // // todo // unboxed := box.Unbox(argObj, argType) // args[i+j] = unboxed // if argType.isLongOrDouble() { // j++ // } // } else { // args[i+j] = argObj // } // } return ops } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/reflect/NativeConstructorAccessorImpl.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
708
```go package misc var _allocated = map[int64][]byte{} var _nextAddress = int64(64) // not zero! func allocate(size int64) (address int64) { mem := make([]byte, size) address = _nextAddress _allocated[address] = mem _nextAddress += size return } func reallocate(address, size int64) int64 { if size == 0 { return 0 } else if address == 0 { return allocate(size) } else { mem := memoryAt(address) if len(mem) >= int(size) { return address } else { delete(_allocated, address) newAddress := allocate(size) newMem := memoryAt(newAddress) copy(newMem, mem) return newAddress } } } func free(address int64) { if _, ok := _allocated[address]; ok { delete(_allocated, address) } else { panic("memory was not allocated!") } } func memoryAt(address int64) []byte { for startAddress, mem := range _allocated { endAddress := startAddress + int64(len(mem)) if address >= startAddress && address < endAddress { offset := address - startAddress return mem[offset:] } } panic("invalid address!") return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/misc/malloc.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
290
```go package misc import "jvmgo/ch11/instructions/base" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { native.Register("sun/misc/VM", "initialize", "()V", initialize) } // private static native void initialize(); // ()V func initialize(frame *rtda.Frame) { classLoader := frame.Method().Class().Loader() jlSysClass := classLoader.LoadClass("java/lang/System") initSysClass := jlSysClass.GetStaticMethod("initializeSystemClass", "()V") base.InvokeMethod(frame, initSysClass) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/misc/VM.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
130
```go package misc import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" import "jvmgo/ch11/rtda/heap" const miscUnsafe = "sun/misc/Unsafe" func init() { native.Register(miscUnsafe, "arrayBaseOffset", "(Ljava/lang/Class;)I", arrayBaseOffset) native.Register(miscUnsafe, "arrayIndexScale", "(Ljava/lang/Class;)I", arrayIndexScale) native.Register(miscUnsafe, "addressSize", "()I", addressSize) native.Register(miscUnsafe, "objectFieldOffset", "(Ljava/lang/reflect/Field;)J", objectFieldOffset) native.Register(miscUnsafe, "compareAndSwapObject", "(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z", compareAndSwapObject) native.Register(miscUnsafe, "getIntVolatile", "(Ljava/lang/Object;J)I", getInt) native.Register(miscUnsafe, "compareAndSwapInt", "(Ljava/lang/Object;JII)Z", compareAndSwapInt) native.Register(miscUnsafe, "getObjectVolatile", "(Ljava/lang/Object;J)Ljava/lang/Object;", getObject) native.Register(miscUnsafe, "compareAndSwapLong", "(Ljava/lang/Object;JJJ)Z", compareAndSwapLong) } // public native int arrayBaseOffset(Class<?> type); // (Ljava/lang/Class;)I func arrayBaseOffset(frame *rtda.Frame) { stack := frame.OperandStack() stack.PushInt(0) // todo } // public native int arrayIndexScale(Class<?> type); // (Ljava/lang/Class;)I func arrayIndexScale(frame *rtda.Frame) { stack := frame.OperandStack() stack.PushInt(1) // todo } // public native int addressSize(); // ()I func addressSize(frame *rtda.Frame) { // vars := frame.LocalVars() // vars.GetRef(0) // this stack := frame.OperandStack() stack.PushInt(8) // todo unsafe.Sizeof(int) } // public native long objectFieldOffset(Field field); // (Ljava/lang/reflect/Field;)J func objectFieldOffset(frame *rtda.Frame) { vars := frame.LocalVars() jField := vars.GetRef(1) offset := jField.GetIntVar("slot", "I") stack := frame.OperandStack() stack.PushLong(int64(offset)) } // public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x) // (Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z func compareAndSwapObject(frame *rtda.Frame) { vars := frame.LocalVars() obj := vars.GetRef(1) fields := obj.Data() offset := vars.GetLong(2) expected := vars.GetRef(4) newVal := vars.GetRef(5) // todo if anys, ok := fields.(heap.Slots); ok { // object swapped := _casObj(obj, anys, offset, expected, newVal) frame.OperandStack().PushBoolean(swapped) } else if objs, ok := fields.([]*heap.Object); ok { // ref[] swapped := _casArr(objs, offset, expected, newVal) frame.OperandStack().PushBoolean(swapped) } else { // todo panic("todo: compareAndSwapObject!") } } func _casObj(obj *heap.Object, fields heap.Slots, offset int64, expected, newVal *heap.Object) bool { current := fields.GetRef(uint(offset)) if current == expected { fields.SetRef(uint(offset), newVal) return true } else { return false } } func _casArr(objs []*heap.Object, offset int64, expected, newVal *heap.Object) bool { current := objs[offset] if current == expected { objs[offset] = newVal return true } else { return false } } // public native boolean getInt(Object o, long offset); // (Ljava/lang/Object;J)I func getInt(frame *rtda.Frame) { vars := frame.LocalVars() fields := vars.GetRef(1).Data() offset := vars.GetLong(2) stack := frame.OperandStack() if slots, ok := fields.(heap.Slots); ok { // object stack.PushInt(slots.GetInt(uint(offset))) } else if shorts, ok := fields.([]int32); ok { // int[] stack.PushInt(int32(shorts[offset])) } else { panic("getInt!") } } // public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x); // (Ljava/lang/Object;JII)Z func compareAndSwapInt(frame *rtda.Frame) { vars := frame.LocalVars() fields := vars.GetRef(1).Data() offset := vars.GetLong(2) expected := vars.GetInt(4) newVal := vars.GetInt(5) if slots, ok := fields.(heap.Slots); ok { // object oldVal := slots.GetInt(uint(offset)) if oldVal == expected { slots.SetInt(uint(offset), newVal) frame.OperandStack().PushBoolean(true) } else { frame.OperandStack().PushBoolean(false) } } else if ints, ok := fields.([]int32); ok { // int[] oldVal := ints[offset] if oldVal == expected { ints[offset] = newVal frame.OperandStack().PushBoolean(true) } else { frame.OperandStack().PushBoolean(false) } } else { // todo panic("todo: compareAndSwapInt!") } } // public native Object getObject(Object o, long offset); // (Ljava/lang/Object;J)Ljava/lang/Object; func getObject(frame *rtda.Frame) { vars := frame.LocalVars() fields := vars.GetRef(1).Data() offset := vars.GetLong(2) if anys, ok := fields.(heap.Slots); ok { // object x := anys.GetRef(uint(offset)) frame.OperandStack().PushRef(x) } else if objs, ok := fields.([]*heap.Object); ok { // ref[] x := objs[offset] frame.OperandStack().PushRef(x) } else { panic("getObject!") } } // public final native boolean compareAndSwapLong(Object o, long offset, long expected, long x); // (Ljava/lang/Object;JJJ)Z func compareAndSwapLong(frame *rtda.Frame) { vars := frame.LocalVars() fields := vars.GetRef(1).Data() offset := vars.GetLong(2) expected := vars.GetLong(4) newVal := vars.GetLong(6) if slots, ok := fields.(heap.Slots); ok { // object oldVal := slots.GetLong(uint(offset)) if oldVal == expected { slots.SetLong(uint(offset), newVal) frame.OperandStack().PushBoolean(true) } else { frame.OperandStack().PushBoolean(false) } } else if longs, ok := fields.([]int64); ok { // long[] oldVal := longs[offset] if oldVal == expected { longs[offset] = newVal frame.OperandStack().PushBoolean(true) } else { frame.OperandStack().PushBoolean(false) } } else { // todo panic("todo: compareAndSwapLong!") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/misc/Unsafe.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,639
```go package misc import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { native.Register("sun/misc/URLClassPath", "getLookupCacheURLs", "(Ljava/lang/ClassLoader;)[Ljava/net/URL;", getLookupCacheURLs) } // private static native URL[] getLookupCacheURLs(ClassLoader var0); // (Ljava/lang/ClassLoader;)[Ljava/net/URL; func getLookupCacheURLs(frame *rtda.Frame) { frame.OperandStack().PushRef(nil) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/misc/URLClassPath.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
118
```go package misc import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { _signal(findSignal, "findSignal", "(Ljava/lang/String;)I") _signal(handle0, "handle0", "(IJ)J") } func _signal(method func(frame *rtda.Frame), name, desc string) { native.Register("sun/misc/Signal", name, desc, method) } // private static native int findSignal(String string); // (Ljava/lang/String;)I func findSignal(frame *rtda.Frame) { vars := frame.LocalVars() vars.GetRef(0) // name stack := frame.OperandStack() stack.PushInt(0) // todo } // private static native long handle0(int i, long l); // (IJ)J func handle0(frame *rtda.Frame) { // todo vars := frame.LocalVars() vars.GetInt(0) vars.GetLong(1) stack := frame.OperandStack() stack.PushLong(0) } // private static native void raise0(int i); ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/misc/Signal.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
234
```go package rtda import "jvmgo/ch11/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) GetFrames() []*Frame { return self.stack.getFrames() } func (self *Thread) IsStackEmpty() bool { return self.stack.isEmpty() } func (self *Thread) ClearStack() { self.stack.clear() } func (self *Thread) NewFrame(method *heap.Method) *Frame { return newFrame(self, method) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/thread.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
275
```go package misc import "math" import "encoding/binary" import "jvmgo/ch11/native" import "jvmgo/ch11/rtda" func init() { _unsafe(allocateMemory, "allocateMemory", "(J)J") _unsafe(reallocateMemory, "reallocateMemory", "(JJ)J") _unsafe(freeMemory, "freeMemory", "(J)V") _unsafe(addressSize, "addressSize", "()I") // _unsafe(putAddress, "putAddress", "(JJ)V") // _unsafe(getAddress, "getAddress", "(J)J") // _unsafe(mem_putByte, "putByte", "(JB)V") _unsafe(mem_getByte, "getByte", "(J)B") // _unsafe(mem_putShort, "putShort", "(JS)V") // _unsafe(mem_getShort, "getShort", "(J)S") // _unsafe(mem_putChar, "putChar", "(JC)V") // _unsafe(mem_getChar, "getChar", "(J)C") // _unsafe(mem_putInt, "putInt", "(JI)V") // _unsafe(mem_getInt, "getInt", "(J)I") _unsafe(mem_putLong, "putLong", "(JJ)V") // _unsafe(mem_getLong, "getLong", "(J)J") // _unsafe(mem_putFloat, "putFloat", "(JF)V") // _unsafe(mem_getFloat, "getFloat", "(J)F") // _unsafe(mem_putDouble, "putDouble", "(JD)V") // _unsafe(mem_getDouble, "getDouble", "(J)D") } func _unsafe(method func(frame *rtda.Frame), name, desc string) { native.Register("sun/misc/Unsafe", name, desc, method) } // public native long allocateMemory(long bytes); // (J)J func allocateMemory(frame *rtda.Frame) { vars := frame.LocalVars() // vars.GetRef(0) // this bytes := vars.GetLong(1) address := allocate(bytes) stack := frame.OperandStack() stack.PushLong(address) } // public native long reallocateMemory(long address, long bytes); // (JJ)J func reallocateMemory(frame *rtda.Frame) { vars := frame.LocalVars() // vars.GetRef(0) // this address := vars.GetLong(1) bytes := vars.GetLong(3) newAddress := reallocate(address, bytes) stack := frame.OperandStack() stack.PushLong(newAddress) } // public native void freeMemory(long address); // (J)V func freeMemory(frame *rtda.Frame) { vars := frame.LocalVars() // vars.GetRef(0) // this address := vars.GetLong(1) free(address) } //// public native void putAddress(long address, long x); //// (JJ)V //func putAddress(frame *rtda.Frame) { // mem_putLong(frame) //} // //// public native long getAddress(long address); //// (J)J //func getAddress(frame *rtda.Frame) { // mem_getLong(frame) //} // //// public native void putByte(long address, byte x); //// (JB)V //func mem_putByte(frame *rtda.Frame) { // mem, value := _put(frame) // PutInt8(mem, int8(value.(int32))) //} // // public native byte getByte(long address); // (J)B func mem_getByte(frame *rtda.Frame) { stack, mem := _get(frame) stack.PushInt(int32(Int8(mem))) } // //// public native void putShort(long address, short x); //// (JS)V //func mem_putShort(frame *rtda.Frame) { // mem, value := _put(frame) // PutInt16(mem, int16(value.(int32))) //} // //// public native short getShort(long address); //// (J)S //func mem_getShort(frame *rtda.Frame) { // stack, mem := _get(frame) // stack.PushInt(int32(Int16(mem))) //} // //// public native void putChar(long address, char x); //// (JC)V //func mem_putChar(frame *rtda.Frame) { // mem, value := _put(frame) // PutUint16(mem, uint16(value.(int32))) //} // //// public native char getChar(long address); //// (J)C //func mem_getChar(frame *rtda.Frame) { // stack, mem := _get(frame) // stack.PushInt(int32(Uint16(mem))) //} // //// public native void putInt(long address, int x); //// (JI)V //func mem_putInt(frame *rtda.Frame) { // mem, value := _put(frame) // PutInt32(mem, value.(int32)) //} // //// public native int getInt(long address); //// (J)I //func mem_getInt(frame *rtda.Frame) { // stack, mem := _get(frame) // stack.PushInt(Int32(mem)) //} // // public native void putLong(long address, long x); // (JJ)V func mem_putLong(frame *rtda.Frame) { vars := frame.LocalVars() // vars.GetRef(0) // this address := vars.GetLong(1) value := vars.GetLong(3) mem := memoryAt(address) PutInt64(mem, value) } // //// public native long getLong(long address); //// (J)J //func mem_getLong(frame *rtda.Frame) { // stack, mem := _get(frame) // stack.PushLong(Int64(mem)) //} // //// public native void putFloat(long address, float x); //// (JJ)V //func mem_putFloat(frame *rtda.Frame) { // mem, value := _put(frame) // PutFloat32(mem, value.(float32)) //} // //// public native float getFloat(long address); //// (J)J //func mem_getFloat(frame *rtda.Frame) { // stack, mem := _get(frame) // stack.PushFloat(Float32(mem)) //} // //// public native void putDouble(long address, double x); //// (JJ)V //func mem_putDouble(frame *rtda.Frame) { // mem, value := _put(frame) // PutFloat64(mem, value.(float64)) //} // //// public native double getDouble(long address); //// (J)J //func mem_getDouble(frame *rtda.Frame) { // stack, mem := _get(frame) // stack.PushDouble(Float64(mem)) //} // //func _put(frame *rtda.Frame) ([]byte, interface{}) { // vars := frame.LocalVars() // // vars.GetRef(0) // this // address := vars.GetLong(1) // value := vars.Get(3) // // mem := memoryAt(address) // return mem, value //} // func _get(frame *rtda.Frame) (*rtda.OperandStack, []byte) { vars := frame.LocalVars() // vars.GetRef(0) // this address := vars.GetLong(1) stack := frame.OperandStack() mem := memoryAt(address) return stack, mem } var _bigEndian = binary.BigEndian func PutInt8(s []byte, val int8) { s[0] = uint8(val) } func Int8(s []byte) int8 { return int8(s[0]) } func PutUint16(s []byte, val uint16) { _bigEndian.PutUint16(s, val) } func Uint16(s []byte) uint16 { return _bigEndian.Uint16(s) } func PutInt16(s []byte, val int16) { _bigEndian.PutUint16(s, uint16(val)) } func Int16(s []byte) int16 { return int16(_bigEndian.Uint16(s)) } func PutInt32(s []byte, val int32) { _bigEndian.PutUint32(s, uint32(val)) } func Int32(s []byte) int32 { return int32(_bigEndian.Uint32(s)) } func PutInt64(s []byte, val int64) { _bigEndian.PutUint64(s, uint64(val)) } func Int64(s []byte) int64 { return int64(_bigEndian.Uint64(s)) } func PutFloat32(s []byte, val float32) { _bigEndian.PutUint32(s, math.Float32bits(val)) } func Float32(s []byte) float32 { return math.Float32frombits(_bigEndian.Uint32(s)) } func PutFloat64(s []byte, val float64) { _bigEndian.PutUint64(s, math.Float64bits(val)) } func Float64(s []byte) float64 { return math.Float64frombits(_bigEndian.Uint64(s)) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/native/sun/misc/Unsafe_mem.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,902
```go package rtda import "math" import "jvmgo/ch11/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) Clear() { self.size = 0 for i := range self.slots { self.slots[i].ref = nil } } 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 } // todo func NewOperandStack(maxStack uint) *OperandStack { return newOperandStack(maxStack) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/operand_stack.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
666
```go package rtda import "math" import "jvmgo/ch11/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) } func (self LocalVars) GetBoolean(index uint) bool { return self.GetInt(index) == 1 } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/local_vars.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
459
```go package rtda import "jvmgo/ch11/rtda/heap" type Slot struct { num int32 ref *heap.Object } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/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/ch11/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/ch11/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) getFrames() []*Frame { frames := make([]*Frame, 0, self.size) for frame := self._top; frame != nil; frame = frame.lower { frames = append(frames, frame) } return frames } func (self *Stack) isEmpty() bool { return self._top == nil } func (self *Stack) clear() { for !self.isEmpty() { self.pop() } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/jvm_stack.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
303
```go package rtda import "jvmgo/ch11/rtda/heap" func NewShimFrame(thread *Thread, ops *OperandStack) *Frame { return &Frame{ thread: thread, method: heap.ShimReturnMethod(), operandStack: ops, } } //func newAthrowFrame(thread *Thread, ex *heap.Object, initArgs []interface{}) *Frame { // // stackSlots := [ex, ex, initArgs] // stackSlots := make([]interface{}, len(initArgs)+2) // stackSlots[0] = ex // stackSlots[1] = ex // copy(stackSlots[2:], initArgs) // // frame := &Frame{} // frame.thread = thread // frame.method = heap.AthrowMethod() // frame.operandStack = &OperandStack{ // size: uint(len(stackSlots)), // slots: stackSlots, // } // return frame //} ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/shim_frames.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
203
```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/ch11/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/ch11/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/ch11/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/ch11/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/ch11/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/ch11/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 sourceFile string 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()) class.sourceFile = getSourceFile(cf) return class } func getSourceFile(cf *classfile.ClassFile) string { if sfAttr := cf.SourceFileAttribute(); sfAttr != nil { return sfAttr.FileName() } return "Unknown" // todo } 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) AccessFlags() uint16 { return self.accessFlags } 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) SourceFile() string { return self.sourceFile } func (self *Class) Loader() *ClassLoader { return self.loader } func (self *Class) SuperClass() *Class { return self.superClass } func (self *Class) Interfaces() []*Class { return self.interfaces } 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) GetStaticMethod(name, descriptor string) *Method { return self.getMethod(name, descriptor, true) } // reflection 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) } func (self *Class) GetFields(publicOnly bool) []*Field { if publicOnly { publicFields := make([]*Field, 0, len(self.fields)) for _, field := range self.fields { if field.IsPublic() { publicFields = append(publicFields, field) } } return publicFields } else { return self.fields } } func (self *Class) GetConstructor(descriptor string) *Method { return self.GetInstanceMethod("<init>", descriptor) } func (self *Class) GetConstructors(publicOnly bool) []*Method { constructors := make([]*Method, 0, len(self.methods)) for _, method := range self.methods { if method.isConstructor() { if !publicOnly || method.IsPublic() { constructors = append(constructors, method) } } } return constructors } func (self *Class) GetMethods(publicOnly bool) []*Method { methods := make([]*Method, 0, len(self.methods)) for _, method := range self.methods { if !method.isClinit() && !method.isConstructor() { if !publicOnly || method.IsPublic() { methods = append(methods, method) } } } return methods } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,576
```go package heap import "jvmgo/ch11/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/ch11/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/ch11/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/ch11/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/ch11/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/ch11/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/ch11/classfile" type ClassMember struct { accessFlags uint16 name string descriptor string signature string annotationData []byte // RuntimeVisibleAnnotations_attribute 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) AccessFlags() uint16 { return self.accessFlags } func (self *ClassMember) Name() string { return self.name } func (self *ClassMember) Descriptor() string { return self.descriptor } func (self *ClassMember) Signature() string { return self.signature } func (self *ClassMember) AnnotationData() []byte { return self.annotationData } 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/ch11/rtda/heap/class_member.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
458
```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/ch11/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/ch11/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 import "jvmgo/ch11/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/ch11/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 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) Data() interface{} { return self.data } 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) } func (self *Object) SetIntVar(name, descriptor string, val int32) { field := self.class.getField(name, descriptor, false) slots := self.data.(Slots) slots.SetInt(field.slotId, val) } func (self *Object) GetIntVar(name, descriptor string) int32 { field := self.class.getField(name, descriptor, false) slots := self.data.(Slots) return slots.GetInt(field.slotId) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/object.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
374
```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/ch11/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/ch11/classfile" type Method struct { ClassMember maxStack uint maxLocals uint code []byte exceptionTable ExceptionTable // todo: rename lineNumberTable *classfile.LineNumberTableAttribute exceptions *classfile.ExceptionsAttribute // todo: rename parameterAnnotationData []byte // RuntimeVisibleParameterAnnotations_attribute annotationDefaultData []byte // AnnotationDefault_attribute parsedDescriptor *MethodDescriptor 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.parsedDescriptor = md 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() self.lineNumberTable = codeAttr.LineNumberTableAttribute() self.exceptionTable = newExceptionTable(codeAttr.ExceptionTable(), self.class.constantPool) } self.exceptions = cfMethod.ExceptionsAttribute() self.annotationData = cfMethod.RuntimeVisibleAnnotationsAttributeData() self.parameterAnnotationData = cfMethod.RuntimeVisibleParameterAnnotationsAttributeData() self.annotationDefaultData = cfMethod.AnnotationDefaultAttributeData() } 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) ParameterAnnotationData() []byte { return self.parameterAnnotationData } func (self *Method) AnnotationDefaultData() []byte { return self.annotationDefaultData } func (self *Method) ParsedDescriptor() *MethodDescriptor { return self.parsedDescriptor } func (self *Method) ArgSlotCount() uint { return self.argSlotCount } func (self *Method) FindExceptionHandler(exClass *Class, pc int) int { handler := self.exceptionTable.findExceptionHandler(exClass, pc) if handler != nil { return handler.handlerPc } return -1 } func (self *Method) GetLineNumber(pc int) int { if self.IsNative() { return -2 } if self.lineNumberTable == nil { return -1 } return self.lineNumberTable.GetLineNumber(pc) } func (self *Method) isConstructor() bool { return !self.IsStatic() && self.name == "<init>" } func (self *Method) isClinit() bool { return self.IsStatic() && self.name == "<clinit>" } // reflection func (self *Method) ParameterTypes() []*Class { if self.argSlotCount == 0 { return nil } paramTypes := self.parsedDescriptor.parameterTypes paramClasses := make([]*Class, len(paramTypes)) for i, paramType := range paramTypes { paramClassName := toClassName(paramType) paramClasses[i] = self.class.loader.LoadClass(paramClassName) } return paramClasses } func (self *Method) ReturnType() *Class { returnType := self.parsedDescriptor.returnType returnClassName := toClassName(returnType) return self.class.loader.LoadClass(returnClassName) } func (self *Method) ExceptionTypes() []*Class { if self.exceptions == nil { return nil } exIndexTable := self.exceptions.ExceptionIndexTable() exClasses := make([]*Class, len(exIndexTable)) cp := self.class.constantPool for i, exIndex := range exIndexTable { classRef := cp.GetConstant(uint(exIndex)).(*ClassRef) exClasses[i] = classRef.ResolvedClass() } return exClasses } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/method.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,317
```go package heap import "fmt" import "jvmgo/ch11/classfile" import "jvmgo/ch11/classpath" /* class names: - primitive types: boolean, byte, int ... - primitive arrays: [Z, [B, [I ... - non-array classes: java/lang/Object ... - array classes: [Ljava/lang/Object; ... */ type ClassLoader struct { cp *classpath.Classpath verboseFlag bool classMap map[string]*Class // loaded classes } func NewClassLoader(cp *classpath.Classpath, verboseFlag bool) *ClassLoader { loader := &ClassLoader{ cp: cp, verboseFlag: verboseFlag, classMap: make(map[string]*Class), } loader.loadBasicClasses() loader.loadPrimitiveClasses() return loader } func (self *ClassLoader) loadBasicClasses() { jlClassClass := self.LoadClass("java/lang/Class") for _, class := range self.classMap { if class.jClass == nil { class.jClass = jlClassClass.NewObject() class.jClass.extra = class } } } func (self *ClassLoader) loadPrimitiveClasses() { for primitiveType, _ := range primitiveTypes { self.loadPrimitiveClass(primitiveType) } } func (self *ClassLoader) loadPrimitiveClass(className string) { class := &Class{ accessFlags: ACC_PUBLIC, // todo name: className, loader: self, initStarted: true, } class.jClass = self.classMap["java/lang/Class"].NewObject() class.jClass.extra = class self.classMap[className] = class } func (self *ClassLoader) LoadClass(name string) *Class { if class, ok := self.classMap[name]; ok { // already loaded return class } var class *Class if name[0] == '[' { // array class class = self.loadArrayClass(name) } else { class = self.loadNonArrayClass(name) } if jlClassClass, ok := self.classMap["java/lang/Class"]; ok { class.jClass = jlClassClass.NewObject() class.jClass.extra = class } return class } func (self *ClassLoader) loadArrayClass(name string) *Class { class := &Class{ accessFlags: ACC_PUBLIC, // todo name: name, loader: self, initStarted: true, superClass: self.LoadClass("java/lang/Object"), interfaces: []*Class{ self.LoadClass("java/lang/Cloneable"), self.LoadClass("java/io/Serializable"), }, } self.classMap[name] = class return class } func (self *ClassLoader) loadNonArrayClass(name string) *Class { data, entry := self.readClass(name) class := self.defineClass(data) link(class) if self.verboseFlag { fmt.Printf("[Loaded %s from %s]\n", name, entry) } return class } func (self *ClassLoader) readClass(name string) ([]byte, classpath.Entry) { data, entry, err := self.cp.ReadClass(name) if err != nil { panic("java.lang.ClassNotFoundException: " + name) } return data, entry } // jvms 5.3.5 func (self *ClassLoader) defineClass(data []byte) *Class { class := parseClass(data) hackClass(class) class.loader = self resolveSuperClass(class) resolveInterfaces(class) self.classMap[class.name] = class return class } func parseClass(data []byte) *Class { cf, err := classfile.Parse(data) if err != nil { //panic("java.lang.ClassFormatError") panic(err) } return newClass(cf) } // jvms 5.4.3.1 func resolveSuperClass(class *Class) { if class.name != "java/lang/Object" { class.superClass = class.loader.LoadClass(class.superClassName) } } func resolveInterfaces(class *Class) { interfaceCount := len(class.interfaceNames) if interfaceCount > 0 { class.interfaces = make([]*Class, interfaceCount) for i, interfaceName := range class.interfaceNames { class.interfaces[i] = class.loader.LoadClass(interfaceName) } } } func link(class *Class) { verify(class) prepare(class) } func verify(class *Class) { // todo } // jvms 5.4.2 func prepare(class *Class) { calcInstanceFieldSlotIds(class) calcStaticFieldSlotIds(class) allocAndInitStaticVars(class) } func calcInstanceFieldSlotIds(class *Class) { slotId := uint(0) if class.superClass != nil { slotId = class.superClass.instanceSlotCount } for _, field := range class.fields { if !field.IsStatic() { field.slotId = slotId slotId++ if field.isLongOrDouble() { slotId++ } } } class.instanceSlotCount = slotId } func calcStaticFieldSlotIds(class *Class) { slotId := uint(0) for _, field := range class.fields { if field.IsStatic() { field.slotId = slotId slotId++ if field.isLongOrDouble() { slotId++ } } } class.staticSlotCount = slotId } func allocAndInitStaticVars(class *Class) { class.staticVars = newSlots(class.staticSlotCount) for _, field := range class.fields { if field.IsStatic() && field.IsFinal() { initStaticFinalVar(class, field) } } } func initStaticFinalVar(class *Class, field *Field) { vars := class.staticVars cp := class.constantPool cpIndex := field.ConstValueIndex() slotId := field.SlotId() if cpIndex > 0 { switch field.Descriptor() { case "Z", "B", "C", "S", "I": val := cp.GetConstant(cpIndex).(int32) vars.SetInt(slotId, val) case "J": val := cp.GetConstant(cpIndex).(int64) vars.SetLong(slotId, val) case "F": val := cp.GetConstant(cpIndex).(float32) vars.SetFloat(slotId, val) case "D": val := cp.GetConstant(cpIndex).(float64) vars.SetDouble(slotId, val) case "Ljava/lang/String;": goStr := cp.GetConstant(cpIndex).(string) jStr := JString(class.Loader(), goStr) vars.SetRef(slotId, jStr) } } } // todo func hackClass(class *Class) { if class.name == "java/lang/ClassLoader" { loadLibrary := class.GetStaticMethod("loadLibrary", "(Ljava/lang/Class;Ljava/lang/String;Z)V") loadLibrary.code = []byte{0xb1} // return void } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/class_loader.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
1,520
```go package heap import "jvmgo/ch11/classfile" type ExceptionTable []*ExceptionHandler type ExceptionHandler struct { startPc int endPc int handlerPc int catchType *ClassRef } func newExceptionTable(entries []*classfile.ExceptionTableEntry, cp *ConstantPool) ExceptionTable { table := make([]*ExceptionHandler, len(entries)) for i, entry := range entries { table[i] = &ExceptionHandler{ startPc: int(entry.StartPc()), endPc: int(entry.EndPc()), handlerPc: int(entry.HandlerPc()), catchType: getCatchType(uint(entry.CatchType()), cp), } } return table } func getCatchType(index uint, cp *ConstantPool) *ClassRef { if index == 0 { return nil // catch all } return cp.GetConstant(index).(*ClassRef) } func (self ExceptionTable) findExceptionHandler(exClass *Class, pc int) *ExceptionHandler { for _, handler := range self { // jvms: The start_pc is inclusive and end_pc is exclusive if pc >= handler.startPc && pc < handler.endPc { if handler.catchType == nil { return handler } catchClass := handler.catchType.ResolvedClass() if catchClass == exClass || catchClass.IsSuperClassOf(exClass) { return handler } } } return nil } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/exception_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
315
```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/ch11/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/ch11/rtda/heap/method_lookup.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
164
```go package heap import "math" type Slot struct { num int32 ref *Object } type Slots []Slot func newSlots(slotCount uint) Slots { if slotCount > 0 { return make([]Slot, slotCount) } return nil } func (self Slots) SetInt(index uint, val int32) { self[index].num = val } func (self Slots) GetInt(index uint) int32 { return self[index].num } func (self Slots) SetFloat(index uint, val float32) { bits := math.Float32bits(val) self[index].num = int32(bits) } func (self Slots) GetFloat(index uint) float32 { bits := uint32(self[index].num) return math.Float32frombits(bits) } // long consumes two slots func (self Slots) SetLong(index uint, val int64) { self[index].num = int32(val) self[index+1].num = int32(val >> 32) } func (self Slots) 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 Slots) SetDouble(index uint, val float64) { bits := math.Float64bits(val) self.SetLong(index, int64(bits)) } func (self Slots) GetDouble(index uint) float64 { bits := uint64(self.GetLong(index)) return math.Float64frombits(bits) } func (self Slots) SetRef(index uint, ref *Object) { self[index].ref = ref } func (self Slots) GetRef(index uint) *Object { return self[index].ref } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/slots.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
373
```go package heap import "jvmgo/ch11/classfile" type InterfaceMethodRef struct { MemberRef method *Method } func newInterfaceMethodRef(cp *ConstantPool, refInfo *classfile.ConstantInterfaceMethodrefInfo) *InterfaceMethodRef { ref := &InterfaceMethodRef{} ref.cp = cp ref.copyMemberRefInfo(&refInfo.ConstantMemberrefInfo) return ref } func (self *InterfaceMethodRef) ResolvedInterfaceMethod() *Method { if self.method == nil { self.resolveInterfaceMethodRef() } return self.method } // jvms8 5.4.3.4 func (self *InterfaceMethodRef) resolveInterfaceMethodRef() { d := self.cp.class c := self.ResolvedClass() if !c.IsInterface() { panic("java.lang.IncompatibleClassChangeError") } method := lookupInterfaceMethod(c, self.name, self.descriptor) if method == nil { panic("java.lang.NoSuchMethodError") } if !method.isAccessibleTo(d) { panic("java.lang.IllegalAccessError") } self.method = method } // todo func lookupInterfaceMethod(iface *Class, name, descriptor string) *Method { for _, method := range iface.methods { if method.name == name && method.descriptor == descriptor { return method } } return lookupMethodInInterfaces(iface.interfaces, name, descriptor) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/cp_interface_methodref.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
300
```go package heap var ( _shimClass = &Class{name: "~shim"} _returnCode = []byte{0xb1} // return _athrowCode = []byte{0xbf} // athrow _returnMethod = &Method{ ClassMember: ClassMember{ accessFlags: ACC_STATIC, name: "<return>", class: _shimClass, }, code: _returnCode, } _athrowMethod = &Method{ ClassMember: ClassMember{ accessFlags: ACC_STATIC, name: "<athrow>", class: _shimClass, }, code: _athrowCode, } ) func ShimReturnMethod() *Method { return _returnMethod } // //func AthrowMethod() *Method { // return _athrowMethod //} // //func BootstrapMethod() *Method { // method := &Method{} // method.class = &Class{name: "~shim"} // method.name = "<bootstrap>" // method.accessFlags = ACC_STATIC // method.maxStack = 8 // method.maxLocals = 8 // method.argSlotCount = 2 // method.code = []byte{0xff, 0xb1} // bootstrap, return // return method //} ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/shim_methods.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
280
```go package heap func (self *Object) Bytes() []int8 { return self.data.([]int8) } func (self *Object) Shorts() []int16 { return self.data.([]int16) } func (self *Object) Ints() []int32 { return self.data.([]int32) } func (self *Object) Longs() []int64 { return self.data.([]int64) } func (self *Object) Chars() []uint16 { return self.data.([]uint16) } func (self *Object) Floats() []float32 { return self.data.([]float32) } func (self *Object) Doubles() []float64 { return self.data.([]float64) } func (self *Object) Refs() []*Object { return self.data.([]*Object) } func (self *Object) ArrayLength() int32 { switch self.data.(type) { case []int8: return int32(len(self.data.([]int8))) case []int16: return int32(len(self.data.([]int16))) case []int32: return int32(len(self.data.([]int32))) case []int64: return int32(len(self.data.([]int64))) case []uint16: return int32(len(self.data.([]uint16))) case []float32: return int32(len(self.data.([]float32))) case []float64: return int32(len(self.data.([]float64))) case []*Object: return int32(len(self.data.([]*Object))) default: panic("Not array!") } } func ArrayCopy(src, dst *Object, srcPos, dstPos, length int32) { switch src.data.(type) { case []int8: _src := src.data.([]int8)[srcPos : srcPos+length] _dst := dst.data.([]int8)[dstPos : dstPos+length] copy(_dst, _src) case []int16: _src := src.data.([]int16)[srcPos : srcPos+length] _dst := dst.data.([]int16)[dstPos : dstPos+length] copy(_dst, _src) case []int32: _src := src.data.([]int32)[srcPos : srcPos+length] _dst := dst.data.([]int32)[dstPos : dstPos+length] copy(_dst, _src) case []int64: _src := src.data.([]int64)[srcPos : srcPos+length] _dst := dst.data.([]int64)[dstPos : dstPos+length] copy(_dst, _src) case []uint16: _src := src.data.([]uint16)[srcPos : srcPos+length] _dst := dst.data.([]uint16)[dstPos : dstPos+length] copy(_dst, _src) case []float32: _src := src.data.([]float32)[srcPos : srcPos+length] _dst := dst.data.([]float32)[dstPos : dstPos+length] copy(_dst, _src) case []float64: _src := src.data.([]float64)[srcPos : srcPos+length] _dst := dst.data.([]float64)[dstPos : dstPos+length] copy(_dst, _src) case []*Object: _src := src.data.([]*Object)[srcPos : srcPos+length] _dst := dst.data.([]*Object)[dstPos : dstPos+length] copy(_dst, _src) default: panic("Not array!") } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/array_object.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
783
```go package heap import "jvmgo/ch11/classfile" type Field struct { ClassMember constValueIndex uint slotId uint } func newFields(class *Class, cfFields []*classfile.MemberInfo) []*Field { fields := make([]*Field, len(cfFields)) for i, cfField := range cfFields { fields[i] = &Field{} fields[i].class = class fields[i].copyMemberInfo(cfField) fields[i].copyAttributes(cfField) } return fields } func (self *Field) copyAttributes(cfField *classfile.MemberInfo) { if valAttr := cfField.ConstantValueAttribute(); valAttr != nil { self.constValueIndex = uint(valAttr.ConstantValueIndex()) } } func (self *Field) IsVolatile() bool { return 0 != self.accessFlags&ACC_VOLATILE } func (self *Field) IsTransient() bool { return 0 != self.accessFlags&ACC_TRANSIENT } func (self *Field) IsEnum() bool { return 0 != self.accessFlags&ACC_ENUM } func (self *Field) ConstValueIndex() uint { return self.constValueIndex } func (self *Field) SlotId() uint { return self.slotId } func (self *Field) isLongOrDouble() bool { return self.descriptor == "J" || self.descriptor == "D" } // reflection func (self *Field) Type() *Class { className := toClassName(self.descriptor) return self.class.loader.LoadClass(className) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/field.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
326
```go package heap func (self *Class) IsArray() bool { return self.name[0] == '[' } func (self *Class) ComponentClass() *Class { componentClassName := getComponentClassName(self.name) return self.loader.LoadClass(componentClassName) } func (self *Class) NewArray(count uint) *Object { if !self.IsArray() { panic("Not array class: " + self.name) } switch self.Name() { case "[Z": return &Object{self, make([]int8, count), nil} case "[B": return &Object{self, make([]int8, count), nil} case "[C": return &Object{self, make([]uint16, count), nil} case "[S": return &Object{self, make([]int16, count), nil} case "[I": return &Object{self, make([]int32, count), nil} case "[J": return &Object{self, make([]int64, count), nil} case "[F": return &Object{self, make([]float32, count), nil} case "[D": return &Object{self, make([]float64, count), nil} default: return &Object{self, make([]*Object, count), nil} } } func NewByteArray(loader *ClassLoader, bytes []int8) *Object { return &Object{loader.LoadClass("[B"), bytes, nil} } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/array_class.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
305
```go package classpath import "os" import "strings" // :(linux/unix) or ;(windows) const pathListSeparator = string(os.PathListSeparator) type Entry interface { // className: fully/qualified/ClassName.class readClass(className string) ([]byte, Entry, error) String() string } func newEntry(path string) Entry { if strings.Contains(path, pathListSeparator) { return newCompositeEntry(path) } if strings.HasSuffix(path, "*") { return newWildcardEntry(path) } if strings.HasSuffix(path, ".jar") || strings.HasSuffix(path, ".JAR") || strings.HasSuffix(path, ".zip") || strings.HasSuffix(path, ".ZIP") { return newZipEntry(path) } return newDirEntry(path) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classpath/entry.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
168
```go package heap func (self *Object) Clone() *Object { return &Object{ class: self.class, data: self.cloneData(), } } func (self *Object) cloneData() interface{} { switch self.data.(type) { case []int8: elements := self.data.([]int8) elements2 := make([]int8, len(elements)) copy(elements2, elements) return elements2 case []int16: elements := self.data.([]int16) elements2 := make([]int16, len(elements)) copy(elements2, elements) return elements2 case []uint16: elements := self.data.([]uint16) elements2 := make([]uint16, len(elements)) copy(elements2, elements) return elements2 case []int32: elements := self.data.([]int32) elements2 := make([]int32, len(elements)) copy(elements2, elements) return elements2 case []int64: elements := self.data.([]int64) elements2 := make([]int64, len(elements)) copy(elements2, elements) return elements2 case []float32: elements := self.data.([]float32) elements2 := make([]float32, len(elements)) copy(elements2, elements) return elements2 case []float64: elements := self.data.([]float64) elements2 := make([]float64, len(elements)) copy(elements2, elements) return elements2 case []*Object: elements := self.data.([]*Object) elements2 := make([]*Object, len(elements)) copy(elements2, elements) return elements2 default: // []Slot slots := self.data.(Slots) slots2 := newSlots(uint(len(slots))) copy(slots2, slots) return slots2 } } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/rtda/heap/object_clone.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
423
```go package classpath import "errors" import "strings" type CompositeEntry []Entry func newCompositeEntry(pathList string) CompositeEntry { compositeEntry := []Entry{} for _, path := range strings.Split(pathList, pathListSeparator) { entry := newEntry(path) compositeEntry = append(compositeEntry, entry) } return compositeEntry } func (self CompositeEntry) readClass(className string) ([]byte, Entry, error) { for _, entry := range self { data, from, err := entry.readClass(className) if err == nil { return data, from, nil } } return nil, nil, errors.New("class not found: " + className) } func (self CompositeEntry) String() string { strs := make([]string, len(self)) for i, entry := range self { strs[i] = entry.String() } return strings.Join(strs, pathListSeparator) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classpath/entry_composite.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
202
```go package classpath import "archive/zip" import "errors" import "io/ioutil" import "path/filepath" type ZipEntry struct { absPath string zipRC *zip.ReadCloser } func newZipEntry(path string) *ZipEntry { absPath, err := filepath.Abs(path) if err != nil { panic(err) } return &ZipEntry{absPath, nil} } func (self *ZipEntry) readClass(className string) ([]byte, Entry, error) { if self.zipRC == nil { err := self.openJar() if err != nil { return nil, nil, err } } classFile := self.findClass(className) if classFile == nil { return nil, nil, errors.New("class not found: " + className) } data, err := readClass(classFile) return data, self, err } // todo: close zip func (self *ZipEntry) openJar() error { r, err := zip.OpenReader(self.absPath) if err == nil { self.zipRC = r } return err } func (self *ZipEntry) findClass(className string) *zip.File { for _, f := range self.zipRC.File { if f.Name == className { return f } } return nil } func readClass(classFile *zip.File) ([]byte, error) { rc, err := classFile.Open() if err != nil { return nil, err } // read class data data, err := ioutil.ReadAll(rc) rc.Close() if err != nil { return nil, err } return data, nil } func (self *ZipEntry) String() string { return self.absPath } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classpath/entry_zip.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
374
```go package classpath import "os" import "path/filepath" import "strings" func newWildcardEntry(path string) CompositeEntry { baseDir := path[:len(path)-1] // remove * compositeEntry := []Entry{} walkFn := func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() && path != baseDir { return filepath.SkipDir } if strings.HasSuffix(path, ".jar") || strings.HasSuffix(path, ".JAR") { jarEntry := newZipEntry(path) compositeEntry = append(compositeEntry, jarEntry) } return nil } filepath.Walk(baseDir, walkFn) return compositeEntry } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classpath/entry_wildcard.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
168
```go package classpath import "io/ioutil" import "path/filepath" type DirEntry struct { absDir string } func newDirEntry(path string) *DirEntry { absDir, err := filepath.Abs(path) if err != nil { panic(err) } return &DirEntry{absDir} } func (self *DirEntry) readClass(className string) ([]byte, Entry, error) { fileName := filepath.Join(self.absDir, className) data, err := ioutil.ReadFile(fileName) return data, self, err } func (self *DirEntry) String() string { return self.absDir } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classpath/entry_dir.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
131
```go package classpath import "os" import "path/filepath" type Classpath struct { bootClasspath Entry extClasspath Entry userClasspath Entry } func Parse(jreOption, cpOption string) *Classpath { cp := &Classpath{} cp.parseBootAndExtClasspath(jreOption) cp.parseUserClasspath(cpOption) return cp } func (self *Classpath) parseBootAndExtClasspath(jreOption string) { jreDir := getJreDir(jreOption) // jre/lib/* jreLibPath := filepath.Join(jreDir, "lib", "*") self.bootClasspath = newWildcardEntry(jreLibPath) // jre/lib/ext/* jreExtPath := filepath.Join(jreDir, "lib", "ext", "*") self.extClasspath = newWildcardEntry(jreExtPath) } func getJreDir(jreOption string) string { if jreOption != "" && exists(jreOption) { return jreOption } if exists("./jre") { return "./jre" } if jh := os.Getenv("JAVA_HOME"); jh != "" { return filepath.Join(jh, "jre") } panic("Can not find jre folder!") } func exists(path string) bool { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { return false } } return true } func (self *Classpath) parseUserClasspath(cpOption string) { if cpOption == "" { cpOption = "." } self.userClasspath = newEntry(cpOption) } // className: fully/qualified/ClassName func (self *Classpath) ReadClass(className string) ([]byte, Entry, error) { className = className + ".class" if data, entry, err := self.bootClasspath.readClass(className); err == nil { return data, entry, err } if data, entry, err := self.extClasspath.readClass(className); err == nil { return data, entry, err } return self.userClasspath.readClass(className) } func (self *Classpath) String() string { return self.userClasspath.String() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch11/classpath/classpath.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
476
```go package main import "flag" import "fmt" import "os" // java [-options] class [args...] type Cmd struct { helpFlag bool versionFlag bool cpOption string XjreOption string class string args []string } func parseCmd() *Cmd { cmd := &Cmd{} flag.Usage = printUsage flag.BoolVar(&cmd.helpFlag, "help", false, "print help message") flag.BoolVar(&cmd.helpFlag, "?", false, "print help message") flag.BoolVar(&cmd.versionFlag, "version", false, "print version and exit") flag.StringVar(&cmd.cpOption, "classpath", "", "classpath") flag.StringVar(&cmd.cpOption, "cp", "", "classpath") flag.StringVar(&cmd.XjreOption, "Xjre", "", "path to jre") flag.Parse() args := flag.Args() if len(args) > 0 { cmd.class = args[0] cmd.args = args[1:] } return cmd } func printUsage() { fmt.Printf("Usage: %s [-options] class [args...]\n", os.Args[0]) //flag.PrintDefaults() } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch04/cmd.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
254
```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/ch04/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 /* 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) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch04/classfile/member_info.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
326
```go package main import "fmt" import _ "jvmgo/ch04/classfile" import _ "jvmgo/ch04/classpath" import "jvmgo/ch04/rtda" func main() { cmd := parseCmd() if cmd.versionFlag { fmt.Println("version 0.0.1") } else if cmd.helpFlag || cmd.class == "" { printUsage() } else { startJVM(cmd) } } func startJVM(cmd *Cmd) { frame := rtda.NewFrame(100, 100) testLocalVars(frame.LocalVars()) testOperandStack(frame.OperandStack()) } func testLocalVars(vars rtda.LocalVars) { vars.SetInt(0, 100) vars.SetInt(1, -100) vars.SetLong(2, 2997924580) vars.SetLong(4, -2997924580) vars.SetFloat(6, 3.1415926) vars.SetDouble(7, 2.71828182845) vars.SetRef(9, nil) println(vars.GetInt(0)) println(vars.GetInt(1)) println(vars.GetLong(2)) println(vars.GetLong(4)) println(vars.GetFloat(6)) println(vars.GetDouble(7)) println(vars.GetRef(9)) } func testOperandStack(ops *rtda.OperandStack) { ops.PushInt(100) ops.PushInt(-100) ops.PushLong(2997924580) ops.PushLong(-2997924580) ops.PushFloat(3.1415926) ops.PushDouble(2.71828182845) ops.PushRef(nil) println(ops.PopRef()) println(ops.PopDouble()) println(ops.PopFloat()) println(ops.PopLong()) println(ops.PopLong()) println(ops.PopInt()) println(ops.PopInt()) } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch04/main.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
397
```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/ch04/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/ch04/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/ch04/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/ch04/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 /* 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/ch04/classfile/attr_line_number_table.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
255
```go package classfile /* CONSTANT_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/ch04/classfile/cp_name_and_type.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
88
```go package classfile /* Deprecated_attribute { u2 attribute_name_index; u4 attribute_length; } */ type DeprecatedAttribute struct { MarkerAttribute } /* Synthetic_attribute { u2 attribute_name_index; u4 attribute_length; } */ type SyntheticAttribute struct { MarkerAttribute } type MarkerAttribute struct{} func (self *MarkerAttribute) readInfo(reader *ClassReader) { // read nothing } ```
/content/code_sandbox/v1/code/go/src/jvmgo/ch04/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/ch04/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/ch04/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/ch04/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/ch04/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/ch04/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/ch04/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/ch04/classfile/attr_constant_value.go
go
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
95