message.go 8.2 KB

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