wrapper.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /**
  2. * Copyright 2023 ByteDance Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package loader
  17. import (
  18. `reflect`
  19. `unsafe`
  20. `github.com/bytedance/sonic/internal/abi`
  21. `github.com/bytedance/sonic/internal/rt`
  22. )
  23. var _C_Redzone = []bool{false, false, false, false}
  24. // CFunc is a function information for C func
  25. type CFunc struct {
  26. // C function name
  27. Name string
  28. // entry pc relative to entire text segment
  29. EntryOff uint32
  30. // function text size in bytes
  31. TextSize uint32
  32. // maximum stack depth of the function
  33. MaxStack uintptr
  34. // PC->SP delta lists of the function
  35. Pcsp [][2]uint32
  36. }
  37. // GoC is the wrapper for Go calls to C
  38. type GoC struct {
  39. // CName is the name of corresponding C function
  40. CName string
  41. // CEntry points out where to store the entry address of corresponding C function.
  42. // It won't be set if nil
  43. CEntry *uintptr
  44. // GoFunc is the POINTER of corresponding go stub function.
  45. // It is used to generate Go-C ABI conversion wrapper and receive the wrapper's address
  46. // eg. &func(a int, b int) int
  47. // FOR
  48. // int add(int a, int b)
  49. // It won't be set if nil
  50. GoFunc interface{}
  51. }
  52. // WrapGoC wraps C functions and loader it into Go stubs
  53. func WrapGoC(text []byte, natives []CFunc, stubs []GoC, modulename string, filename string) {
  54. funcs := make([]Func, len(natives))
  55. // register C funcs
  56. for i, f := range natives {
  57. fn := Func{
  58. Flag: FuncFlag_ASM,
  59. EntryOff: f.EntryOff,
  60. TextSize: f.TextSize,
  61. Name: f.Name,
  62. }
  63. if len(f.Pcsp) != 0 {
  64. fn.Pcsp = (*Pcdata)(unsafe.Pointer(&natives[i].Pcsp))
  65. }
  66. // NOTICE: always forbid async preempt
  67. fn.PcUnsafePoint = &Pcdata{
  68. {PC: f.TextSize, Val: PCDATA_UnsafePointUnsafe},
  69. }
  70. // NOTICE: always refer to first file
  71. fn.Pcfile = &Pcdata{
  72. {PC: f.TextSize, Val: 0},
  73. }
  74. // NOTICE: always refer to first line
  75. fn.Pcline = &Pcdata{
  76. {PC: f.TextSize, Val: 1},
  77. }
  78. // NOTICE: copystack need locals stackmap
  79. fn.PcStackMapIndex = &Pcdata{
  80. {PC: f.TextSize, Val: 0},
  81. }
  82. sm := rt.StackMapBuilder{}
  83. sm.AddField(false)
  84. fn.ArgsPointerMaps = sm.Build()
  85. fn.LocalsPointerMaps = sm.Build()
  86. funcs[i] = fn
  87. }
  88. rets := Load(text, funcs, modulename, []string{filename})
  89. // got absolute entry address
  90. native_entry := **(**uintptr)(unsafe.Pointer(&rets[0]))
  91. // println("native_entry: ", native_entry)
  92. wraps := make([]Func, 0, len(stubs))
  93. wrapIds := make([]int, 0, len(stubs))
  94. code := make([]byte, 0, len(wraps))
  95. entryOff := uint32(0)
  96. // register go wrappers
  97. for i := range stubs {
  98. for j := range natives {
  99. if stubs[i].CName != natives[j].Name {
  100. continue
  101. }
  102. // calculate corresponding C entry
  103. pc := uintptr(native_entry + uintptr(natives[j].EntryOff))
  104. if stubs[i].CEntry != nil {
  105. *stubs[i].CEntry = pc
  106. }
  107. // no need to generate wrapper, continue next
  108. if stubs[i].GoFunc == nil {
  109. continue
  110. }
  111. // assemble wrapper codes
  112. layout := abi.NewFunctionLayout(reflect.TypeOf(stubs[i].GoFunc).Elem())
  113. frame := abi.NewFrame(&layout, _C_Redzone, true)
  114. tcode := abi.CallC(pc, frame, natives[j].MaxStack)
  115. code = append(code, tcode...)
  116. size := uint32(len(tcode))
  117. fn := Func{
  118. Flag: FuncFlag_ASM,
  119. ArgsSize: int32(layout.ArgSize()),
  120. EntryOff: entryOff,
  121. TextSize: size,
  122. Name: stubs[i].CName + "_go",
  123. }
  124. // add check-stack and grow-stack texts' pcsp
  125. fn.Pcsp = &Pcdata{
  126. {PC: uint32(frame.StackCheckTextSize()), Val: 0},
  127. {PC: size - uint32(frame.GrowStackTextSize()), Val: int32(frame.Size())},
  128. {PC: size, Val: 0},
  129. }
  130. // NOTICE: always refer to first file
  131. fn.Pcfile = &Pcdata{
  132. {PC: size, Val: 0},
  133. }
  134. // NOTICE: always refer to first line
  135. fn.Pcline = &Pcdata{
  136. {PC: size, Val: 1},
  137. }
  138. // NOTICE: always forbid async preempt
  139. fn.PcUnsafePoint = &Pcdata{
  140. {PC: size, Val: PCDATA_UnsafePointUnsafe},
  141. }
  142. // register pointer stackmaps
  143. fn.PcStackMapIndex = &Pcdata{
  144. {PC: size, Val: 0},
  145. }
  146. fn.ArgsPointerMaps = frame.ArgPtrs()
  147. fn.LocalsPointerMaps = frame.LocalPtrs()
  148. entryOff += size
  149. wraps = append(wraps, fn)
  150. wrapIds = append(wrapIds, i)
  151. }
  152. }
  153. gofuncs := Load(code, wraps, modulename+"/go", []string{filename+".go"})
  154. // set go func value
  155. for i := range gofuncs {
  156. idx := wrapIds[i]
  157. w := rt.UnpackEface(stubs[idx].GoFunc)
  158. *(*Function)(w.Value) = gofuncs[i]
  159. }
  160. }