message.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. "google.golang.org/protobuf/internal/genid"
  13. "google.golang.org/protobuf/reflect/protoreflect"
  14. "google.golang.org/protobuf/reflect/protoregistry"
  15. )
  16. // MessageInfo provides protobuf related functionality for a given Go type
  17. // that represents a message. A given instance of MessageInfo is tied to
  18. // exactly one Go type, which must be a pointer to a struct type.
  19. //
  20. // The exported fields must be populated before any methods are called
  21. // and cannot be mutated after set.
  22. type MessageInfo struct {
  23. // GoReflectType is the underlying message Go type and must be populated.
  24. GoReflectType reflect.Type // pointer to struct
  25. // Desc is the underlying message descriptor type and must be populated.
  26. Desc protoreflect.MessageDescriptor
  27. // Exporter must be provided in a purego environment in order to provide
  28. // access to unexported fields.
  29. Exporter exporter
  30. // OneofWrappers is list of pointers to oneof wrapper struct types.
  31. OneofWrappers []interface{}
  32. initMu sync.Mutex // protects all unexported fields
  33. initDone uint32
  34. reflectMessageInfo // for reflection implementation
  35. coderMessageInfo // for fast-path method implementations
  36. }
  37. // exporter is a function that returns a reference to the ith field of v,
  38. // where v is a pointer to a struct. It returns nil if it does not support
  39. // exporting the requested field (e.g., already exported).
  40. type exporter func(v interface{}, i int) interface{}
  41. // getMessageInfo returns the MessageInfo for any message type that
  42. // is generated by our implementation of protoc-gen-go (for v2 and on).
  43. // If it is unable to obtain a MessageInfo, it returns nil.
  44. func getMessageInfo(mt reflect.Type) *MessageInfo {
  45. m, ok := reflect.Zero(mt).Interface().(protoreflect.ProtoMessage)
  46. if !ok {
  47. return nil
  48. }
  49. mr, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *MessageInfo })
  50. if !ok {
  51. return nil
  52. }
  53. return mr.ProtoMessageInfo()
  54. }
  55. func (mi *MessageInfo) init() {
  56. // This function is called in the hot path. Inline the sync.Once logic,
  57. // since allocating a closure for Once.Do is expensive.
  58. // Keep init small to ensure that it can be inlined.
  59. if atomic.LoadUint32(&mi.initDone) == 0 {
  60. mi.initOnce()
  61. }
  62. }
  63. func (mi *MessageInfo) initOnce() {
  64. mi.initMu.Lock()
  65. defer mi.initMu.Unlock()
  66. if mi.initDone == 1 {
  67. return
  68. }
  69. t := mi.GoReflectType
  70. if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
  71. panic(fmt.Sprintf("got %v, want *struct kind", t))
  72. }
  73. t = t.Elem()
  74. si := mi.makeStructInfo(t)
  75. mi.makeReflectFuncs(t, si)
  76. mi.makeCoderMethods(t, si)
  77. atomic.StoreUint32(&mi.initDone, 1)
  78. }
  79. // getPointer returns the pointer for a message, which should be of
  80. // the type of the MessageInfo. If the message is of a different type,
  81. // it returns ok==false.
  82. func (mi *MessageInfo) getPointer(m protoreflect.Message) (p pointer, ok bool) {
  83. switch m := m.(type) {
  84. case *messageState:
  85. return m.pointer(), m.messageInfo() == mi
  86. case *messageReflectWrapper:
  87. return m.pointer(), m.messageInfo() == mi
  88. }
  89. return pointer{}, false
  90. }
  91. type (
  92. SizeCache = int32
  93. WeakFields = map[int32]protoreflect.ProtoMessage
  94. UnknownFields = unknownFieldsA // TODO: switch to unknownFieldsB
  95. unknownFieldsA = []byte
  96. unknownFieldsB = *[]byte
  97. ExtensionFields = map[int32]ExtensionField
  98. )
  99. var (
  100. sizecacheType = reflect.TypeOf(SizeCache(0))
  101. weakFieldsType = reflect.TypeOf(WeakFields(nil))
  102. unknownFieldsAType = reflect.TypeOf(unknownFieldsA(nil))
  103. unknownFieldsBType = reflect.TypeOf(unknownFieldsB(nil))
  104. extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
  105. )
  106. type structInfo struct {
  107. sizecacheOffset offset
  108. sizecacheType reflect.Type
  109. weakOffset offset
  110. weakType reflect.Type
  111. unknownOffset offset
  112. unknownType reflect.Type
  113. extensionOffset offset
  114. extensionType reflect.Type
  115. fieldsByNumber map[protoreflect.FieldNumber]reflect.StructField
  116. oneofsByName map[protoreflect.Name]reflect.StructField
  117. oneofWrappersByType map[reflect.Type]protoreflect.FieldNumber
  118. oneofWrappersByNumber map[protoreflect.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[protoreflect.FieldNumber]reflect.StructField{},
  127. oneofsByName: map[protoreflect.Name]reflect.StructField{},
  128. oneofWrappersByType: map[reflect.Type]protoreflect.FieldNumber{},
  129. oneofWrappersByNumber: map[protoreflect.FieldNumber]reflect.Type{},
  130. }
  131. fieldLoop:
  132. for i := 0; i < t.NumField(); i++ {
  133. switch f := t.Field(i); f.Name {
  134. case genid.SizeCache_goname, genid.SizeCacheA_goname:
  135. if f.Type == sizecacheType {
  136. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  137. si.sizecacheType = f.Type
  138. }
  139. case genid.WeakFields_goname, genid.WeakFieldsA_goname:
  140. if f.Type == weakFieldsType {
  141. si.weakOffset = offsetOf(f, mi.Exporter)
  142. si.weakType = f.Type
  143. }
  144. case genid.UnknownFields_goname, genid.UnknownFieldsA_goname:
  145. if f.Type == unknownFieldsAType || f.Type == unknownFieldsBType {
  146. si.unknownOffset = offsetOf(f, mi.Exporter)
  147. si.unknownType = f.Type
  148. }
  149. case genid.ExtensionFields_goname, genid.ExtensionFieldsA_goname, genid.ExtensionFieldsB_goname:
  150. if f.Type == extensionFieldsType {
  151. si.extensionOffset = offsetOf(f, mi.Exporter)
  152. si.extensionType = f.Type
  153. }
  154. default:
  155. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  156. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  157. n, _ := strconv.ParseUint(s, 10, 64)
  158. si.fieldsByNumber[protoreflect.FieldNumber(n)] = f
  159. continue fieldLoop
  160. }
  161. }
  162. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  163. si.oneofsByName[protoreflect.Name(s)] = f
  164. continue fieldLoop
  165. }
  166. }
  167. }
  168. // Derive a mapping of oneof wrappers to fields.
  169. oneofWrappers := mi.OneofWrappers
  170. methods := make([]reflect.Method, 0, 2)
  171. if m, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  172. methods = append(methods, m)
  173. }
  174. if m, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  175. methods = append(methods, m)
  176. }
  177. for _, fn := range methods {
  178. for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) {
  179. if vs, ok := v.Interface().([]interface{}); ok {
  180. oneofWrappers = vs
  181. }
  182. }
  183. }
  184. for _, v := range oneofWrappers {
  185. tf := reflect.TypeOf(v).Elem()
  186. f := tf.Field(0)
  187. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  188. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  189. n, _ := strconv.ParseUint(s, 10, 64)
  190. si.oneofWrappersByType[tf] = protoreflect.FieldNumber(n)
  191. si.oneofWrappersByNumber[protoreflect.FieldNumber(n)] = tf
  192. break
  193. }
  194. }
  195. }
  196. return si
  197. }
  198. func (mi *MessageInfo) New() protoreflect.Message {
  199. m := reflect.New(mi.GoReflectType.Elem()).Interface()
  200. if r, ok := m.(protoreflect.ProtoMessage); ok {
  201. return r.ProtoReflect()
  202. }
  203. return mi.MessageOf(m)
  204. }
  205. func (mi *MessageInfo) Zero() protoreflect.Message {
  206. return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface())
  207. }
  208. func (mi *MessageInfo) Descriptor() protoreflect.MessageDescriptor {
  209. return mi.Desc
  210. }
  211. func (mi *MessageInfo) Enum(i int) protoreflect.EnumType {
  212. mi.init()
  213. fd := mi.Desc.Fields().Get(i)
  214. return Export{}.EnumTypeOf(mi.fieldTypes[fd.Number()])
  215. }
  216. func (mi *MessageInfo) Message(i int) protoreflect.MessageType {
  217. mi.init()
  218. fd := mi.Desc.Fields().Get(i)
  219. switch {
  220. case fd.IsWeak():
  221. mt, _ := protoregistry.GlobalTypes.FindMessageByName(fd.Message().FullName())
  222. return mt
  223. case fd.IsMap():
  224. return mapEntryType{fd.Message(), mi.fieldTypes[fd.Number()]}
  225. default:
  226. return Export{}.MessageTypeOf(mi.fieldTypes[fd.Number()])
  227. }
  228. }
  229. type mapEntryType struct {
  230. desc protoreflect.MessageDescriptor
  231. valType interface{} // zero value of enum or message type
  232. }
  233. func (mt mapEntryType) New() protoreflect.Message {
  234. return nil
  235. }
  236. func (mt mapEntryType) Zero() protoreflect.Message {
  237. return nil
  238. }
  239. func (mt mapEntryType) Descriptor() protoreflect.MessageDescriptor {
  240. return mt.desc
  241. }
  242. func (mt mapEntryType) Enum(i int) protoreflect.EnumType {
  243. fd := mt.desc.Fields().Get(i)
  244. if fd.Enum() == nil {
  245. return nil
  246. }
  247. return Export{}.EnumTypeOf(mt.valType)
  248. }
  249. func (mt mapEntryType) Message(i int) protoreflect.MessageType {
  250. fd := mt.desc.Fields().Get(i)
  251. if fd.Message() == nil {
  252. return nil
  253. }
  254. return Export{}.MessageTypeOf(mt.valType)
  255. }