message.go 8.3 KB

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