message.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Copyright 2018 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. package impl
  5. import (
  6. "fmt"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. pref "google.golang.org/protobuf/reflect/protoreflect"
  13. piface "google.golang.org/protobuf/runtime/protoiface"
  14. )
  15. // MessageInfo provides protobuf related functionality for a given Go type
  16. // that represents a message. A given instance of MessageInfo is tied to
  17. // exactly one Go type, which must be a pointer to a struct type.
  18. type MessageInfo struct {
  19. // GoType is the underlying message Go type and must be populated.
  20. // Once set, this field must never be mutated.
  21. GoType reflect.Type // pointer to struct
  22. // PBType is the underlying message descriptor type and must be populated.
  23. // Once set, this field must never be mutated.
  24. PBType pref.MessageType
  25. // Exporter must be provided in a purego environment in order to provide
  26. // access to unexported fields.
  27. Exporter exporter
  28. // OneofWrappers is list of pointers to oneof wrapper struct types.
  29. OneofWrappers []interface{}
  30. initMu sync.Mutex // protects all unexported fields
  31. initDone uint32
  32. reflectMessageInfo
  33. // Information used by the fast-path methods.
  34. methods piface.Methods
  35. coderMessageInfo
  36. extensionFieldInfosMu sync.RWMutex
  37. extensionFieldInfos map[pref.ExtensionType]*extensionFieldInfo
  38. }
  39. type reflectMessageInfo struct {
  40. fields map[pref.FieldNumber]*fieldInfo
  41. oneofs map[pref.Name]*oneofInfo
  42. getUnknown func(pointer) pref.RawFields
  43. setUnknown func(pointer, pref.RawFields)
  44. extensionMap func(pointer) *extensionMap
  45. nilMessage atomicNilMessage
  46. }
  47. // exporter is a function that returns a reference to the ith field of v,
  48. // where v is a pointer to a struct. It returns nil if it does not support
  49. // exporting the requested field (e.g., already exported).
  50. type exporter func(v interface{}, i int) interface{}
  51. var prefMessageType = reflect.TypeOf((*pref.Message)(nil)).Elem()
  52. // getMessageInfo returns the MessageInfo (if any) for a type.
  53. //
  54. // We find the MessageInfo by calling the ProtoReflect method on the type's
  55. // zero value and looking at the returned type to see if it is a
  56. // messageReflectWrapper. Note that the MessageInfo may still be uninitialized
  57. // at this point.
  58. func getMessageInfo(mt reflect.Type) (mi *MessageInfo, ok bool) {
  59. method, ok := mt.MethodByName("ProtoReflect")
  60. if !ok {
  61. return nil, false
  62. }
  63. if method.Type.NumIn() != 1 || method.Type.NumOut() != 1 || method.Type.Out(0) != prefMessageType {
  64. return nil, false
  65. }
  66. ret := reflect.Zero(mt).Method(method.Index).Call(nil)
  67. m, ok := ret[0].Elem().Interface().(*messageReflectWrapper)
  68. if !ok {
  69. return nil, ok
  70. }
  71. return m.mi, true
  72. }
  73. func (mi *MessageInfo) init() {
  74. // This function is called in the hot path. Inline the sync.Once
  75. // logic, since allocating a closure for Once.Do is expensive.
  76. // Keep init small to ensure that it can be inlined.
  77. if atomic.LoadUint32(&mi.initDone) == 0 {
  78. mi.initOnce()
  79. }
  80. }
  81. func (mi *MessageInfo) initOnce() {
  82. mi.initMu.Lock()
  83. defer mi.initMu.Unlock()
  84. if mi.initDone == 1 {
  85. return
  86. }
  87. t := mi.GoType
  88. if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
  89. panic(fmt.Sprintf("got %v, want *struct kind", t))
  90. }
  91. si := mi.makeStructInfo(t.Elem())
  92. mi.makeKnownFieldsFunc(si)
  93. mi.makeUnknownFieldsFunc(t.Elem(), si)
  94. mi.makeExtensionFieldsFunc(t.Elem(), si)
  95. mi.makeMethods(t.Elem(), si)
  96. atomic.StoreUint32(&mi.initDone, 1)
  97. }
  98. type (
  99. SizeCache = int32
  100. UnknownFields = []byte
  101. ExtensionFields = map[int32]ExtensionField
  102. )
  103. var (
  104. sizecacheType = reflect.TypeOf(SizeCache(0))
  105. unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
  106. extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
  107. )
  108. type structInfo struct {
  109. sizecacheOffset offset
  110. unknownOffset offset
  111. extensionOffset offset
  112. fieldsByNumber map[pref.FieldNumber]reflect.StructField
  113. oneofsByName map[pref.Name]reflect.StructField
  114. oneofWrappersByType map[reflect.Type]pref.FieldNumber
  115. oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
  116. }
  117. func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
  118. si := structInfo{
  119. sizecacheOffset: invalidOffset,
  120. unknownOffset: invalidOffset,
  121. extensionOffset: invalidOffset,
  122. fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
  123. oneofsByName: map[pref.Name]reflect.StructField{},
  124. oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
  125. oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
  126. }
  127. if f, _ := t.FieldByName("sizeCache"); f.Type == sizecacheType {
  128. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  129. }
  130. if f, _ := t.FieldByName("XXX_sizecache"); f.Type == sizecacheType {
  131. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  132. }
  133. if f, _ := t.FieldByName("unknownFields"); f.Type == unknownFieldsType {
  134. si.unknownOffset = offsetOf(f, mi.Exporter)
  135. }
  136. if f, _ := t.FieldByName("XXX_unrecognized"); f.Type == unknownFieldsType {
  137. si.unknownOffset = offsetOf(f, mi.Exporter)
  138. }
  139. if f, _ := t.FieldByName("extensionFields"); f.Type == extensionFieldsType {
  140. si.extensionOffset = offsetOf(f, mi.Exporter)
  141. }
  142. if f, _ := t.FieldByName("XXX_InternalExtensions"); f.Type == extensionFieldsType {
  143. si.extensionOffset = offsetOf(f, mi.Exporter)
  144. }
  145. if f, _ := t.FieldByName("XXX_extensions"); f.Type == extensionFieldsType {
  146. si.extensionOffset = offsetOf(f, mi.Exporter)
  147. }
  148. // Generate a mapping of field numbers and names to Go struct field or type.
  149. fieldLoop:
  150. for i := 0; i < t.NumField(); i++ {
  151. f := t.Field(i)
  152. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  153. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  154. n, _ := strconv.ParseUint(s, 10, 64)
  155. si.fieldsByNumber[pref.FieldNumber(n)] = f
  156. continue fieldLoop
  157. }
  158. }
  159. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  160. si.oneofsByName[pref.Name(s)] = f
  161. continue fieldLoop
  162. }
  163. }
  164. // Derive a mapping of oneof wrappers to fields.
  165. oneofWrappers := mi.OneofWrappers
  166. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  167. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  168. }
  169. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  170. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  171. }
  172. for _, v := range oneofWrappers {
  173. tf := reflect.TypeOf(v).Elem()
  174. f := tf.Field(0)
  175. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  176. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  177. n, _ := strconv.ParseUint(s, 10, 64)
  178. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  179. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  180. break
  181. }
  182. }
  183. }
  184. return si
  185. }
  186. // makeKnownFieldsFunc generates functions for operations that can be performed
  187. // on each protobuf message field. It takes in a reflect.Type representing the
  188. // Go struct and matches message fields with struct fields.
  189. //
  190. // This code assumes that the struct is well-formed and panics if there are
  191. // any discrepancies.
  192. func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
  193. mi.fields = map[pref.FieldNumber]*fieldInfo{}
  194. for i := 0; i < mi.PBType.Descriptor().Fields().Len(); i++ {
  195. fd := mi.PBType.Descriptor().Fields().Get(i)
  196. fs := si.fieldsByNumber[fd.Number()]
  197. var fi fieldInfo
  198. switch {
  199. case fd.ContainingOneof() != nil:
  200. fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()])
  201. case fd.IsMap():
  202. fi = fieldInfoForMap(fd, fs, mi.Exporter)
  203. case fd.IsList():
  204. fi = fieldInfoForList(fd, fs, mi.Exporter)
  205. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  206. fi = fieldInfoForMessage(fd, fs, mi.Exporter)
  207. default:
  208. fi = fieldInfoForScalar(fd, fs, mi.Exporter)
  209. }
  210. mi.fields[fd.Number()] = &fi
  211. }
  212. mi.oneofs = map[pref.Name]*oneofInfo{}
  213. for i := 0; i < mi.PBType.Descriptor().Oneofs().Len(); i++ {
  214. od := mi.PBType.Descriptor().Oneofs().Get(i)
  215. mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], mi.Exporter, si.oneofWrappersByType)
  216. }
  217. }
  218. func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) {
  219. mi.getUnknown = func(pointer) pref.RawFields { return nil }
  220. mi.setUnknown = func(pointer, pref.RawFields) { return }
  221. if si.unknownOffset.IsValid() {
  222. mi.getUnknown = func(p pointer) pref.RawFields {
  223. if p.IsNil() {
  224. return nil
  225. }
  226. rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
  227. return pref.RawFields(*rv.Interface().(*[]byte))
  228. }
  229. mi.setUnknown = func(p pointer, b pref.RawFields) {
  230. if p.IsNil() {
  231. panic("invalid SetUnknown on nil Message")
  232. }
  233. rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
  234. *rv.Interface().(*[]byte) = []byte(b)
  235. }
  236. } else {
  237. mi.getUnknown = func(pointer) pref.RawFields {
  238. return nil
  239. }
  240. mi.setUnknown = func(p pointer, _ pref.RawFields) {
  241. if p.IsNil() {
  242. panic("invalid SetUnknown on nil Message")
  243. }
  244. }
  245. }
  246. }
  247. func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) {
  248. if si.extensionOffset.IsValid() {
  249. mi.extensionMap = func(p pointer) *extensionMap {
  250. if p.IsNil() {
  251. return (*extensionMap)(nil)
  252. }
  253. v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType)
  254. return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
  255. }
  256. } else {
  257. mi.extensionMap = func(pointer) *extensionMap {
  258. return (*extensionMap)(nil)
  259. }
  260. }
  261. }
  262. // TODO: Move this to be on the reflect message instance.
  263. func (mi *MessageInfo) Methods() *piface.Methods {
  264. mi.init()
  265. return &mi.methods
  266. }