| 1 | // Package unsafe provides wrapper of standard library unsafe package to be imported natively in Yaegi. |
| 2 | package unsafe |
| 3 | |
| 4 | import ( |
| 5 | "reflect" |
| 6 | "unsafe" |
| 7 | ) |
| 8 | |
| 9 | // Symbols stores the map of unsafe package symbols. |
| 10 | var Symbols = map[string]map[string]reflect.Value{} |
| 11 | |
| 12 | func init() { |
| 13 | Symbols["github.com/traefik/yaegi/stdlib/unsafe/unsafe"] = map[string]reflect.Value{ |
| 14 | "Symbols": reflect.ValueOf(Symbols), |
| 15 | } |
| 16 | Symbols["github.com/traefik/yaegi/yaegi"] = map[string]reflect.Value{ |
| 17 | "convert": reflect.ValueOf(convert), |
| 18 | } |
| 19 | |
| 20 | Symbols["unsafe/unsafe"]["Add"] = reflect.ValueOf(add) |
| 21 | |
| 22 | // Add builtin functions to unsafe, also implemented in interp/cfg.go. |
| 23 | Symbols["unsafe/unsafe"]["Sizeof"] = reflect.ValueOf(sizeof) |
| 24 | Symbols["unsafe/unsafe"]["Alignof"] = reflect.ValueOf(alignof) |
| 25 | // The following is used for signature check only. |
| 26 | Symbols["unsafe/unsafe"]["Offsetof"] = reflect.ValueOf(func(interface{}) uintptr { return 0 }) |
| 27 | } |
| 28 | |
| 29 | func convert(from, to reflect.Type) func(src, dest reflect.Value) { |
| 30 | switch { |
| 31 | case to.Kind() == reflect.UnsafePointer && from.Kind() == reflect.Uintptr: |
| 32 | return uintptrToUnsafePtr |
| 33 | case to.Kind() == reflect.UnsafePointer: |
| 34 | return func(src, dest reflect.Value) { |
| 35 | dest.SetPointer(unsafe.Pointer(src.Pointer())) |
| 36 | } |
| 37 | case to.Kind() == reflect.Uintptr && from.Kind() == reflect.UnsafePointer: |
| 38 | return func(src, dest reflect.Value) { |
| 39 | ptr := src.Interface().(unsafe.Pointer) |
| 40 | dest.Set(reflect.ValueOf(uintptr(ptr))) |
| 41 | } |
| 42 | case from.Kind() == reflect.UnsafePointer: |
| 43 | return func(src, dest reflect.Value) { |
| 44 | ptr := src.Interface().(unsafe.Pointer) |
| 45 | v := reflect.NewAt(dest.Type().Elem(), ptr) |
| 46 | dest.Set(v) |
| 47 | } |
| 48 | default: |
| 49 | return nil |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func add(ptr unsafe.Pointer, l int) unsafe.Pointer { |
| 54 | return unsafe.Add(ptr, l) |
| 55 | } |
| 56 | |
| 57 | func sizeof(i interface{}) uintptr { |
| 58 | return reflect.ValueOf(i).Type().Size() |
| 59 | } |
| 60 | |
| 61 | func alignof(i interface{}) uintptr { |
| 62 | return uintptr(reflect.ValueOf(i).Type().Align()) |
| 63 | } |
| 64 | |
| 65 | //go:nocheckptr |
| 66 | func uintptrToUnsafePtr(src, dest reflect.Value) { |
| 67 | dest.SetPointer(unsafe.Pointer(src.Interface().(uintptr))) //nolint:govet |
| 68 | } |
| 69 | |
| 70 | //go:generate ../../internal/cmd/extract/extract unsafe |