| 1 | //go:build go1.21 |
| 2 | // +build go1.21 |
| 3 | |
| 4 | // Package unsafe2 provides helpers to generate recursive struct types. |
| 5 | package unsafe2 |
| 6 | |
| 7 | import ( |
| 8 | "reflect" |
| 9 | "unsafe" |
| 10 | ) |
| 11 | |
| 12 | type dummy struct{} |
| 13 | |
| 14 | // DummyType represents a stand-in for a recursive type. |
| 15 | var DummyType = reflect.TypeOf(dummy{}) |
| 16 | |
| 17 | // The following type sizes must match their original definition in Go src/internal/abi/type.go. |
| 18 | type abiType struct { |
| 19 | _ uintptr |
| 20 | _ uintptr |
| 21 | _ uint32 |
| 22 | _ uint8 |
| 23 | _ uint8 |
| 24 | _ uint8 |
| 25 | _ uint8 |
| 26 | _ uintptr |
| 27 | _ uintptr |
| 28 | _ int32 |
| 29 | _ int32 |
| 30 | } |
| 31 | |
| 32 | type abiName struct { |
| 33 | Bytes *byte |
| 34 | } |
| 35 | |
| 36 | type abiStructField struct { |
| 37 | Name abiName |
| 38 | Typ *abiType |
| 39 | Offset uintptr |
| 40 | } |
| 41 | |
| 42 | type abiStructType struct { |
| 43 | abiType |
| 44 | PkgPath abiName |
| 45 | Fields []abiStructField |
| 46 | } |
| 47 | |
| 48 | type emptyInterface struct { |
| 49 | typ *abiType |
| 50 | _ unsafe.Pointer |
| 51 | } |
| 52 | |
| 53 | // SetFieldType sets the type of the struct field at the given index, to the given type. |
| 54 | // |
| 55 | // The struct type must have been created at runtime. This is very unsafe. |
| 56 | func SetFieldType(s reflect.Type, idx int, t reflect.Type) { |
| 57 | if s.Kind() != reflect.Struct || idx >= s.NumField() { |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | rtyp := unpackType(s) |
| 62 | styp := (*abiStructType)(unsafe.Pointer(rtyp)) |
| 63 | f := styp.Fields[idx] |
| 64 | f.Typ = unpackType(t) |
| 65 | styp.Fields[idx] = f |
| 66 | } |
| 67 | |
| 68 | func unpackType(t reflect.Type) *abiType { |
| 69 | v := reflect.New(t).Elem().Interface() |
| 70 | eface := *(*emptyInterface)(unsafe.Pointer(&v)) |
| 71 | return eface.typ |
| 72 | } |