message.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. pref "google.golang.org/protobuf/reflect/protoreflect"
  13. piface "google.golang.org/protobuf/runtime/protoiface"
  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. type MessageInfo struct {
  19. // GoType is the underlying message Go type and must be populated.
  20. // Once set, this field must never be mutated.
  21. GoType reflect.Type // pointer to struct
  22. // PBType is the underlying message descriptor type and must be populated.
  23. // Once set, this field must never be mutated.
  24. PBType pref.MessageType
  25. // Exporter must be provided in a purego environment in order to provide
  26. // access to unexported fields.
  27. Exporter exporter
  28. // OneofWrappers is list of pointers to oneof wrapper struct types.
  29. OneofWrappers []interface{}
  30. initMu sync.Mutex // protects all unexported fields
  31. initDone uint32
  32. reflectMessageInfo
  33. // Information used by the fast-path methods.
  34. methods piface.Methods
  35. coderMessageInfo
  36. extensionFieldInfosMu sync.RWMutex
  37. extensionFieldInfos map[pref.ExtensionType]*extensionFieldInfo
  38. }
  39. type reflectMessageInfo struct {
  40. fields map[pref.FieldNumber]*fieldInfo
  41. oneofs map[pref.Name]*oneofInfo
  42. getUnknown func(pointer) pref.RawFields
  43. setUnknown func(pointer, pref.RawFields)
  44. extensionMap func(pointer) *extensionMap
  45. nilMessage atomicNilMessage
  46. }
  47. // exporter is a function that returns a reference to the ith field of v,
  48. // where v is a pointer to a struct. It returns nil if it does not support
  49. // exporting the requested field (e.g., already exported).
  50. type exporter func(v interface{}, i int) interface{}
  51. var prefMessageType = reflect.TypeOf((*pref.Message)(nil)).Elem()
  52. // getMessageInfo returns the MessageInfo for any message type that
  53. // is generated by our implementation of protoc-gen-go (for v2 and on).
  54. // If it is unable to obtain a MessageInfo, it returns nil.
  55. func getMessageInfo(mt reflect.Type) *MessageInfo {
  56. m, ok := reflect.Zero(mt).Interface().(pref.ProtoMessage)
  57. if !ok {
  58. return nil
  59. }
  60. mr, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *MessageInfo })
  61. if !ok {
  62. return nil
  63. }
  64. return mr.ProtoMessageInfo()
  65. }
  66. func (mi *MessageInfo) init() {
  67. // This function is called in the hot path. Inline the sync.Once
  68. // logic, since allocating a closure for Once.Do is expensive.
  69. // Keep init small to ensure that it can be inlined.
  70. if atomic.LoadUint32(&mi.initDone) == 0 {
  71. mi.initOnce()
  72. }
  73. }
  74. func (mi *MessageInfo) initOnce() {
  75. mi.initMu.Lock()
  76. defer mi.initMu.Unlock()
  77. if mi.initDone == 1 {
  78. return
  79. }
  80. t := mi.GoType
  81. if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
  82. panic(fmt.Sprintf("got %v, want *struct kind", t))
  83. }
  84. si := mi.makeStructInfo(t.Elem())
  85. mi.makeKnownFieldsFunc(si)
  86. mi.makeUnknownFieldsFunc(t.Elem(), si)
  87. mi.makeExtensionFieldsFunc(t.Elem(), si)
  88. mi.makeMethods(t.Elem(), si)
  89. atomic.StoreUint32(&mi.initDone, 1)
  90. }
  91. type (
  92. SizeCache = int32
  93. WeakFields = map[int32]piface.MessageV1
  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. if f, _ := t.FieldByName("sizeCache"); f.Type == sizecacheType {
  125. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  126. }
  127. if f, _ := t.FieldByName("XXX_sizecache"); f.Type == sizecacheType {
  128. si.sizecacheOffset = offsetOf(f, mi.Exporter)
  129. }
  130. if f, _ := t.FieldByName("XXX_weak"); f.Type == weakFieldsType {
  131. si.weakOffset = offsetOf(f, mi.Exporter)
  132. }
  133. if f, _ := t.FieldByName("unknownFields"); f.Type == unknownFieldsType {
  134. si.unknownOffset = offsetOf(f, mi.Exporter)
  135. }
  136. if f, _ := t.FieldByName("XXX_unrecognized"); f.Type == unknownFieldsType {
  137. si.unknownOffset = offsetOf(f, mi.Exporter)
  138. }
  139. if f, _ := t.FieldByName("extensionFields"); f.Type == extensionFieldsType {
  140. si.extensionOffset = offsetOf(f, mi.Exporter)
  141. }
  142. if f, _ := t.FieldByName("XXX_InternalExtensions"); f.Type == extensionFieldsType {
  143. si.extensionOffset = offsetOf(f, mi.Exporter)
  144. }
  145. if f, _ := t.FieldByName("XXX_extensions"); f.Type == extensionFieldsType {
  146. si.extensionOffset = offsetOf(f, mi.Exporter)
  147. }
  148. // Generate a mapping of field numbers and names to Go struct field or type.
  149. fieldLoop:
  150. for i := 0; i < t.NumField(); i++ {
  151. f := t.Field(i)
  152. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  153. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  154. n, _ := strconv.ParseUint(s, 10, 64)
  155. si.fieldsByNumber[pref.FieldNumber(n)] = f
  156. continue fieldLoop
  157. }
  158. }
  159. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  160. si.oneofsByName[pref.Name(s)] = f
  161. continue fieldLoop
  162. }
  163. }
  164. // Derive a mapping of oneof wrappers to fields.
  165. oneofWrappers := mi.OneofWrappers
  166. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  167. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  168. }
  169. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  170. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  171. }
  172. for _, v := range oneofWrappers {
  173. tf := reflect.TypeOf(v).Elem()
  174. f := tf.Field(0)
  175. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  176. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  177. n, _ := strconv.ParseUint(s, 10, 64)
  178. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  179. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  180. break
  181. }
  182. }
  183. }
  184. return si
  185. }
  186. // makeKnownFieldsFunc generates functions for operations that can be performed
  187. // on each protobuf message field. It takes in a reflect.Type representing the
  188. // Go struct and matches message fields with struct fields.
  189. //
  190. // This code assumes that the struct is well-formed and panics if there are
  191. // any discrepancies.
  192. func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
  193. mi.fields = map[pref.FieldNumber]*fieldInfo{}
  194. for i := 0; i < mi.PBType.Fields().Len(); i++ {
  195. fd := mi.PBType.Fields().Get(i)
  196. fs := si.fieldsByNumber[fd.Number()]
  197. var fi fieldInfo
  198. switch {
  199. case fd.ContainingOneof() != nil:
  200. fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()])
  201. case fd.IsMap():
  202. fi = fieldInfoForMap(fd, fs, mi.Exporter)
  203. case fd.IsList():
  204. fi = fieldInfoForList(fd, fs, mi.Exporter)
  205. case fd.IsWeak():
  206. fi = fieldInfoForWeakMessage(fd, si.weakOffset)
  207. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  208. fi = fieldInfoForMessage(fd, fs, mi.Exporter)
  209. default:
  210. fi = fieldInfoForScalar(fd, fs, mi.Exporter)
  211. }
  212. mi.fields[fd.Number()] = &fi
  213. }
  214. mi.oneofs = map[pref.Name]*oneofInfo{}
  215. for i := 0; i < mi.PBType.Oneofs().Len(); i++ {
  216. od := mi.PBType.Oneofs().Get(i)
  217. mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], mi.Exporter, si.oneofWrappersByType)
  218. }
  219. }
  220. func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) {
  221. mi.getUnknown = func(pointer) pref.RawFields { return nil }
  222. mi.setUnknown = func(pointer, pref.RawFields) { return }
  223. if si.unknownOffset.IsValid() {
  224. mi.getUnknown = func(p pointer) pref.RawFields {
  225. if p.IsNil() {
  226. return nil
  227. }
  228. rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
  229. return pref.RawFields(*rv.Interface().(*[]byte))
  230. }
  231. mi.setUnknown = func(p pointer, b pref.RawFields) {
  232. if p.IsNil() {
  233. panic("invalid SetUnknown on nil Message")
  234. }
  235. rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
  236. *rv.Interface().(*[]byte) = []byte(b)
  237. }
  238. } else {
  239. mi.getUnknown = func(pointer) pref.RawFields {
  240. return nil
  241. }
  242. mi.setUnknown = func(p pointer, _ pref.RawFields) {
  243. if p.IsNil() {
  244. panic("invalid SetUnknown on nil Message")
  245. }
  246. }
  247. }
  248. }
  249. func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) {
  250. if si.extensionOffset.IsValid() {
  251. mi.extensionMap = func(p pointer) *extensionMap {
  252. if p.IsNil() {
  253. return (*extensionMap)(nil)
  254. }
  255. v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType)
  256. return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
  257. }
  258. } else {
  259. mi.extensionMap = func(pointer) *extensionMap {
  260. return (*extensionMap)(nil)
  261. }
  262. }
  263. }