message.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. )
  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. // 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 pref.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 = []byte
  95. ExtensionFields = map[int32]ExtensionField
  96. )
  97. var (
  98. sizecacheType = reflect.TypeOf(SizeCache(0))
  99. weakFieldsType = reflect.TypeOf(WeakFields(nil))
  100. unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
  101. extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
  102. )
  103. type structInfo struct {
  104. sizecacheOffset offset
  105. weakOffset offset
  106. unknownOffset offset
  107. extensionOffset offset
  108. fieldsByNumber map[pref.FieldNumber]reflect.StructField
  109. oneofsByName map[pref.Name]reflect.StructField
  110. oneofWrappersByType map[reflect.Type]pref.FieldNumber
  111. oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
  112. }
  113. func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
  114. si := structInfo{
  115. sizecacheOffset: invalidOffset,
  116. weakOffset: invalidOffset,
  117. unknownOffset: invalidOffset,
  118. extensionOffset: invalidOffset,
  119. fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
  120. oneofsByName: map[pref.Name]reflect.StructField{},
  121. oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
  122. oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
  123. }
  124. fieldLoop:
  125. for i := 0; i < t.NumField(); i++ {
  126. switch f := t.Field(i); f.Name {
  127. case genid.SizeCache_goname, genid.SizeCacheA_goname:
  128. if f.Type == sizecacheType {
  129. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  130. }
  131. case genid.WeakFields_goname, genid.WeakFieldsA_goname:
  132. if f.Type == weakFieldsType {
  133. si.weakOffset = offsetOf(f, mi.Exporter)
  134. }
  135. case genid.UnknownFields_goname, genid.UnknownFieldsA_goname:
  136. if f.Type == unknownFieldsType {
  137. si.unknownOffset = offsetOf(f, mi.Exporter)
  138. }
  139. case genid.ExtensionFields_goname, genid.ExtensionFieldsA_goname, genid.ExtensionFieldsB_goname:
  140. if f.Type == extensionFieldsType {
  141. si.extensionOffset = offsetOf(f, mi.Exporter)
  142. }
  143. default:
  144. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  145. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  146. n, _ := strconv.ParseUint(s, 10, 64)
  147. si.fieldsByNumber[pref.FieldNumber(n)] = f
  148. continue fieldLoop
  149. }
  150. }
  151. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  152. si.oneofsByName[pref.Name(s)] = f
  153. continue fieldLoop
  154. }
  155. }
  156. }
  157. // Derive a mapping of oneof wrappers to fields.
  158. oneofWrappers := mi.OneofWrappers
  159. for _, method := range []string{"XXX_OneofFuncs", "XXX_OneofWrappers"} {
  160. if fn, ok := reflect.PtrTo(t).MethodByName(method); ok {
  161. for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) {
  162. if vs, ok := v.Interface().([]interface{}); ok {
  163. oneofWrappers = vs
  164. }
  165. }
  166. }
  167. }
  168. for _, v := range oneofWrappers {
  169. tf := reflect.TypeOf(v).Elem()
  170. f := tf.Field(0)
  171. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  172. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  173. n, _ := strconv.ParseUint(s, 10, 64)
  174. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  175. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  176. break
  177. }
  178. }
  179. }
  180. return si
  181. }
  182. func (mi *MessageInfo) New() protoreflect.Message {
  183. return mi.MessageOf(reflect.New(mi.GoReflectType.Elem()).Interface())
  184. }
  185. func (mi *MessageInfo) Zero() protoreflect.Message {
  186. return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface())
  187. }
  188. func (mi *MessageInfo) Descriptor() protoreflect.MessageDescriptor { return mi.Desc }