message.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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/reflect/protoreflect"
  13. pref "google.golang.org/protobuf/reflect/protoreflect"
  14. piface "google.golang.org/protobuf/runtime/protoiface"
  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 pref.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().(pref.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. type (
  80. SizeCache = int32
  81. WeakFields = map[int32]piface.MessageV1
  82. UnknownFields = []byte
  83. ExtensionFields = map[int32]ExtensionField
  84. )
  85. var (
  86. sizecacheType = reflect.TypeOf(SizeCache(0))
  87. weakFieldsType = reflect.TypeOf(WeakFields(nil))
  88. unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
  89. extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
  90. )
  91. type structInfo struct {
  92. sizecacheOffset offset
  93. weakOffset offset
  94. unknownOffset offset
  95. extensionOffset offset
  96. fieldsByNumber map[pref.FieldNumber]reflect.StructField
  97. oneofsByName map[pref.Name]reflect.StructField
  98. oneofWrappersByType map[reflect.Type]pref.FieldNumber
  99. oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
  100. }
  101. func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
  102. si := structInfo{
  103. sizecacheOffset: invalidOffset,
  104. weakOffset: invalidOffset,
  105. unknownOffset: invalidOffset,
  106. extensionOffset: invalidOffset,
  107. fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
  108. oneofsByName: map[pref.Name]reflect.StructField{},
  109. oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
  110. oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
  111. }
  112. if f, _ := t.FieldByName("sizeCache"); f.Type == sizecacheType {
  113. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  114. }
  115. if f, _ := t.FieldByName("XXX_sizecache"); f.Type == sizecacheType {
  116. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  117. }
  118. if f, _ := t.FieldByName("XXX_weak"); f.Type == weakFieldsType {
  119. si.weakOffset = offsetOf(f, mi.Exporter)
  120. }
  121. if f, _ := t.FieldByName("unknownFields"); f.Type == unknownFieldsType {
  122. si.unknownOffset = offsetOf(f, mi.Exporter)
  123. }
  124. if f, _ := t.FieldByName("XXX_unrecognized"); f.Type == unknownFieldsType {
  125. si.unknownOffset = offsetOf(f, mi.Exporter)
  126. }
  127. if f, _ := t.FieldByName("extensionFields"); f.Type == extensionFieldsType {
  128. si.extensionOffset = offsetOf(f, mi.Exporter)
  129. }
  130. if f, _ := t.FieldByName("XXX_InternalExtensions"); f.Type == extensionFieldsType {
  131. si.extensionOffset = offsetOf(f, mi.Exporter)
  132. }
  133. if f, _ := t.FieldByName("XXX_extensions"); f.Type == extensionFieldsType {
  134. si.extensionOffset = offsetOf(f, mi.Exporter)
  135. }
  136. // Generate a mapping of field numbers and names to Go struct field or type.
  137. fieldLoop:
  138. for i := 0; i < t.NumField(); i++ {
  139. f := t.Field(i)
  140. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  141. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  142. n, _ := strconv.ParseUint(s, 10, 64)
  143. si.fieldsByNumber[pref.FieldNumber(n)] = f
  144. continue fieldLoop
  145. }
  146. }
  147. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  148. si.oneofsByName[pref.Name(s)] = f
  149. continue fieldLoop
  150. }
  151. }
  152. // Derive a mapping of oneof wrappers to fields.
  153. oneofWrappers := mi.OneofWrappers
  154. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  155. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  156. }
  157. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  158. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  159. }
  160. for _, v := range oneofWrappers {
  161. tf := reflect.TypeOf(v).Elem()
  162. f := tf.Field(0)
  163. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  164. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  165. n, _ := strconv.ParseUint(s, 10, 64)
  166. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  167. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  168. break
  169. }
  170. }
  171. }
  172. return si
  173. }
  174. func (mi *MessageInfo) New() protoreflect.Message {
  175. return mi.MessageOf(reflect.New(mi.GoReflectType.Elem()).Interface())
  176. }
  177. func (mi *MessageInfo) Zero() protoreflect.Message {
  178. return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface())
  179. }
  180. func (mi *MessageInfo) Descriptor() protoreflect.MessageDescriptor { return mi.Desc }