Debian Codegraph @

libgo/go/reflect/makefunc_ffi.go

raw
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package reflect
6
7 import (
8 "internal/goarch"
9 "unsafe"
10 )
11
12 // The makeFuncFFI function, written in C, fills in an FFI closure.
13 // It arranges for ffiCall to be invoked directly from FFI.
14 func makeFuncFFI(cif unsafe.Pointer, impl unsafe.Pointer)
15
16 // The makeCIF function, implemented in the runtime package, allocates a CIF.
17 func makeCIF(ft *funcType) unsafe.Pointer
18
19 // Export ffiCallbackGo so that C code in makefunc_ffi_c.c can call it.
20 //go:linkname ffiCallbackGo
21
22 // ffiCallbackGo implements the Go side of the libffi callback.
23 //
24 // The call chain arriving here looks like
25 // some_go_caller
26 // ->some_ffi_internals
27 // ->ffi_callback (in C)
28 // ->ffiCallbackGo
29 //
30 // The ffi_callback handles __go_makefunc_can_recover, and
31 // then passes off the data as received from ffi here.
32 func ffiCallbackGo(results unsafe.Pointer, params unsafe.Pointer, impl *makeFuncImpl, wordsize int32, bigEndian bool) {
33 ftyp := impl.typ
34 in := make([]Value, 0, len(ftyp.in))
35 ap := params
36 for _, rt := range ftyp.in {
37 p := unsafe_New(rt)
38 typedmemmove(rt, p, *(*unsafe.Pointer)(ap))
39 v := Value{rt, p, flag(rt.Kind()) | flagIndir}
40 in = append(in, v)
41 ap = (unsafe.Pointer)(uintptr(ap) + goarch.PtrSize)
42 }
43
44 out := impl.call(in)
45
46 checkValue := func(v Value, typ *rtype, addr unsafe.Pointer) {
47 if v.flag&flagRO != 0 {
48 panic("reflect: function created by MakeFunc using " + funcName(impl.fn) +
49 " returned value obtained from unexported field")
50 }
51
52 // Convert v to type typ if v is assignable to a variable
53 // of type t in the language spec.
54 // See issue 28761.
55 v = v.assignTo("reflect.MakeFunc", typ, addr)
56 }
57
58 // In libffi a single integer return value is always promoted
59 // to a full word. This only matters for integers whose size
60 // is less than the size of a full word. There is similar code
61 // in libgo/runtime/go-reflect-call.c.
62 if len(ftyp.out) == 1 {
63 typ := ftyp.out[0]
64 switch typ.Kind() {
65 case Bool, Int8, Int16, Int32, Uint8, Uint16, Uint32:
66 v := out[0]
67 checkValue(v, typ, nil)
68
69 if bigEndian {
70 results = unsafe.Pointer(uintptr(results) + uintptr(wordsize) - typ.size)
71 }
72
73 memmove(results, v.ptr, typ.size)
74 return
75 }
76 }
77
78 off := uintptr(0)
79 for i, typ := range ftyp.out {
80 v := out[i]
81
82 off = align(off, uintptr(typ.fieldAlign))
83 addr := unsafe.Pointer(uintptr(results) + off)
84
85 checkValue(v, typ, addr)
86
87 if v.flag&flagIndir == 0 && (v.kind() == Ptr || v.kind() == UnsafePointer) {
88 *(*unsafe.Pointer)(addr) = v.ptr
89 } else {
90 typedmemmove(typ, addr, v.ptr)
91 }
92 off += typ.size
93 }
94 }