You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

message.go 6.7 kB

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