message.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. WeakFields = map[int32]piface.MessageV1
  101. UnknownFields = []byte
  102. ExtensionFields = map[int32]ExtensionField
  103. )
  104. var (
  105. sizecacheType = reflect.TypeOf(SizeCache(0))
  106. weakFieldsType = reflect.TypeOf(WeakFields(nil))
  107. unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
  108. extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
  109. )
  110. type structInfo struct {
  111. sizecacheOffset offset
  112. weakOffset offset
  113. unknownOffset offset
  114. extensionOffset offset
  115. fieldsByNumber map[pref.FieldNumber]reflect.StructField
  116. oneofsByName map[pref.Name]reflect.StructField
  117. oneofWrappersByType map[reflect.Type]pref.FieldNumber
  118. oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
  119. }
  120. func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
  121. si := structInfo{
  122. sizecacheOffset: invalidOffset,
  123. weakOffset: invalidOffset,
  124. unknownOffset: invalidOffset,
  125. extensionOffset: invalidOffset,
  126. fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
  127. oneofsByName: map[pref.Name]reflect.StructField{},
  128. oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
  129. oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
  130. }
  131. if f, _ := t.FieldByName("sizeCache"); f.Type == sizecacheType {
  132. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  133. }
  134. if f, _ := t.FieldByName("XXX_sizecache"); f.Type == sizecacheType {
  135. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  136. }
  137. if f, _ := t.FieldByName("XXX_weak"); f.Type == weakFieldsType {
  138. si.weakOffset = offsetOf(f, mi.Exporter)
  139. }
  140. if f, _ := t.FieldByName("unknownFields"); f.Type == unknownFieldsType {
  141. si.unknownOffset = offsetOf(f, mi.Exporter)
  142. }
  143. if f, _ := t.FieldByName("XXX_unrecognized"); f.Type == unknownFieldsType {
  144. si.unknownOffset = offsetOf(f, mi.Exporter)
  145. }
  146. if f, _ := t.FieldByName("extensionFields"); f.Type == extensionFieldsType {
  147. si.extensionOffset = offsetOf(f, mi.Exporter)
  148. }
  149. if f, _ := t.FieldByName("XXX_InternalExtensions"); f.Type == extensionFieldsType {
  150. si.extensionOffset = offsetOf(f, mi.Exporter)
  151. }
  152. if f, _ := t.FieldByName("XXX_extensions"); f.Type == extensionFieldsType {
  153. si.extensionOffset = offsetOf(f, mi.Exporter)
  154. }
  155. // Generate a mapping of field numbers and names to Go struct field or type.
  156. fieldLoop:
  157. for i := 0; i < t.NumField(); i++ {
  158. f := t.Field(i)
  159. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  160. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  161. n, _ := strconv.ParseUint(s, 10, 64)
  162. si.fieldsByNumber[pref.FieldNumber(n)] = f
  163. continue fieldLoop
  164. }
  165. }
  166. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  167. si.oneofsByName[pref.Name(s)] = f
  168. continue fieldLoop
  169. }
  170. }
  171. // Derive a mapping of oneof wrappers to fields.
  172. oneofWrappers := mi.OneofWrappers
  173. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  174. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  175. }
  176. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  177. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  178. }
  179. for _, v := range oneofWrappers {
  180. tf := reflect.TypeOf(v).Elem()
  181. f := tf.Field(0)
  182. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  183. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  184. n, _ := strconv.ParseUint(s, 10, 64)
  185. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  186. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  187. break
  188. }
  189. }
  190. }
  191. return si
  192. }
  193. // makeKnownFieldsFunc generates functions for operations that can be performed
  194. // on each protobuf message field. It takes in a reflect.Type representing the
  195. // Go struct and matches message fields with struct fields.
  196. //
  197. // This code assumes that the struct is well-formed and panics if there are
  198. // any discrepancies.
  199. func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
  200. mi.fields = map[pref.FieldNumber]*fieldInfo{}
  201. for i := 0; i < mi.PBType.Fields().Len(); i++ {
  202. fd := mi.PBType.Fields().Get(i)
  203. fs := si.fieldsByNumber[fd.Number()]
  204. var fi fieldInfo
  205. switch {
  206. case fd.ContainingOneof() != nil:
  207. fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()])
  208. case fd.IsMap():
  209. fi = fieldInfoForMap(fd, fs, mi.Exporter)
  210. case fd.IsList():
  211. fi = fieldInfoForList(fd, fs, mi.Exporter)
  212. case fd.IsWeak():
  213. fi = fieldInfoForWeakMessage(fd, si.weakOffset)
  214. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  215. fi = fieldInfoForMessage(fd, fs, mi.Exporter)
  216. default:
  217. fi = fieldInfoForScalar(fd, fs, mi.Exporter)
  218. }
  219. mi.fields[fd.Number()] = &fi
  220. }
  221. mi.oneofs = map[pref.Name]*oneofInfo{}
  222. for i := 0; i < mi.PBType.Oneofs().Len(); i++ {
  223. od := mi.PBType.Oneofs().Get(i)
  224. mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], mi.Exporter, si.oneofWrappersByType)
  225. }
  226. }
  227. func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) {
  228. mi.getUnknown = func(pointer) pref.RawFields { return nil }
  229. mi.setUnknown = func(pointer, pref.RawFields) { return }
  230. if si.unknownOffset.IsValid() {
  231. mi.getUnknown = func(p pointer) pref.RawFields {
  232. if p.IsNil() {
  233. return nil
  234. }
  235. rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
  236. return pref.RawFields(*rv.Interface().(*[]byte))
  237. }
  238. mi.setUnknown = func(p pointer, b pref.RawFields) {
  239. if p.IsNil() {
  240. panic("invalid SetUnknown on nil Message")
  241. }
  242. rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
  243. *rv.Interface().(*[]byte) = []byte(b)
  244. }
  245. } else {
  246. mi.getUnknown = func(pointer) pref.RawFields {
  247. return nil
  248. }
  249. mi.setUnknown = func(p pointer, _ pref.RawFields) {
  250. if p.IsNil() {
  251. panic("invalid SetUnknown on nil Message")
  252. }
  253. }
  254. }
  255. }
  256. func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) {
  257. if si.extensionOffset.IsValid() {
  258. mi.extensionMap = func(p pointer) *extensionMap {
  259. if p.IsNil() {
  260. return (*extensionMap)(nil)
  261. }
  262. v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType)
  263. return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
  264. }
  265. } else {
  266. mi.extensionMap = func(pointer) *extensionMap {
  267. return (*extensionMap)(nil)
  268. }
  269. }
  270. }