message.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. "sort"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. pvalue "google.golang.org/protobuf/internal/value"
  14. pref "google.golang.org/protobuf/reflect/protoreflect"
  15. piface "google.golang.org/protobuf/runtime/protoiface"
  16. )
  17. // MessageType provides protobuf related functionality for a given Go type
  18. // that represents a message. A given instance of MessageType is tied to
  19. // exactly one Go type, which must be a pointer to a struct type.
  20. type MessageType struct {
  21. // GoType is the underlying message Go type and must be populated.
  22. // Once set, this field must never be mutated.
  23. GoType reflect.Type // pointer to struct
  24. // PBType is the underlying message descriptor type and must be populated.
  25. // Once set, this field must never be mutated.
  26. PBType pref.MessageType
  27. initMu sync.Mutex // protects all unexported fields
  28. initDone uint32
  29. // Keep a separate slice of fields for efficient field encoding in tag order
  30. // and because iterating over a slice is substantially faster than a map.
  31. fields map[pref.FieldNumber]*fieldInfo
  32. fieldsOrdered []*fieldInfo
  33. oneofs map[pref.Name]*oneofInfo
  34. unknownFields func(*messageDataType) pref.UnknownFields
  35. extensionFields func(*messageDataType) pref.KnownFields
  36. methods piface.Methods
  37. extensionOffset offset
  38. sizecacheOffset offset
  39. unknownOffset offset
  40. extensionFieldInfosMu sync.RWMutex
  41. extensionFieldInfos map[*piface.ExtensionDescV1]*extensionFieldInfo
  42. }
  43. var prefMessageType = reflect.TypeOf((*pref.Message)(nil)).Elem()
  44. // getMessageType returns the MessageType (if any) for a type.
  45. //
  46. // We find the MessageType by calling the ProtoReflect method on the type's
  47. // zero value and looking at the returned type to see if it is a
  48. // messageReflectWrapper. Note that the MessageType may still be uninitialized
  49. // at this point.
  50. func getMessageType(mt reflect.Type) (mi *MessageType, ok bool) {
  51. method, ok := mt.MethodByName("ProtoReflect")
  52. if !ok {
  53. return nil, false
  54. }
  55. if method.Type.NumIn() != 1 || method.Type.NumOut() != 1 || method.Type.Out(0) != prefMessageType {
  56. return nil, false
  57. }
  58. ret := reflect.Zero(mt).Method(method.Index).Call(nil)
  59. m, ok := ret[0].Elem().Interface().(*messageReflectWrapper)
  60. if !ok {
  61. return nil, ok
  62. }
  63. return m.mi, true
  64. }
  65. func (mi *MessageType) init() {
  66. // This function is called in the hot path. Inline the sync.Once
  67. // logic, since allocating a closure for Once.Do is expensive.
  68. // Keep init small to ensure that it can be inlined.
  69. if atomic.LoadUint32(&mi.initDone) == 1 {
  70. return
  71. }
  72. mi.initOnce()
  73. }
  74. func (mi *MessageType) 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())
  87. mi.makeExtensionFieldsFunc(t.Elem())
  88. mi.makeMethods(t.Elem())
  89. atomic.StoreUint32(&mi.initDone, 1)
  90. }
  91. var sizecacheType = reflect.TypeOf(int32(0))
  92. func (mi *MessageType) makeMethods(t reflect.Type) {
  93. mi.extensionOffset = invalidOffset
  94. if fx, _ := t.FieldByName("XXX_InternalExtensions"); fx.Type == extType {
  95. mi.extensionOffset = offsetOf(fx)
  96. } else if fx, _ = t.FieldByName("XXX_extensions"); fx.Type == extType {
  97. mi.extensionOffset = offsetOf(fx)
  98. }
  99. mi.sizecacheOffset = invalidOffset
  100. if fx, _ := t.FieldByName("XXX_sizecache"); fx.Type == sizecacheType {
  101. mi.sizecacheOffset = offsetOf(fx)
  102. }
  103. mi.unknownOffset = invalidOffset
  104. if fx, _ := t.FieldByName("XXX_unrecognized"); fx.Type == bytesType {
  105. mi.unknownOffset = offsetOf(fx)
  106. }
  107. mi.methods.Flags = piface.MethodFlagDeterministicMarshal
  108. mi.methods.MarshalAppend = mi.marshalAppend
  109. mi.methods.Size = mi.size
  110. }
  111. type structInfo struct {
  112. fieldsByNumber map[pref.FieldNumber]reflect.StructField
  113. oneofsByName map[pref.Name]reflect.StructField
  114. oneofWrappersByType map[reflect.Type]pref.FieldNumber
  115. oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
  116. }
  117. func (mi *MessageType) makeStructInfo(t reflect.Type) structInfo {
  118. // Generate a mapping of field numbers and names to Go struct field or type.
  119. si := structInfo{
  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. f := t.Field(i)
  128. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  129. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  130. n, _ := strconv.ParseUint(s, 10, 64)
  131. si.fieldsByNumber[pref.FieldNumber(n)] = f
  132. continue fieldLoop
  133. }
  134. }
  135. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  136. si.oneofsByName[pref.Name(s)] = f
  137. continue fieldLoop
  138. }
  139. }
  140. var oneofWrappers []interface{}
  141. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  142. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  143. }
  144. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  145. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  146. }
  147. for _, v := range oneofWrappers {
  148. tf := reflect.TypeOf(v).Elem()
  149. f := tf.Field(0)
  150. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  151. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  152. n, _ := strconv.ParseUint(s, 10, 64)
  153. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  154. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  155. break
  156. }
  157. }
  158. }
  159. return si
  160. }
  161. // makeKnownFieldsFunc generates functions for operations that can be performed
  162. // on each protobuf message field. It takes in a reflect.Type representing the
  163. // Go struct and matches message fields with struct fields.
  164. //
  165. // This code assumes that the struct is well-formed and panics if there are
  166. // any discrepancies.
  167. func (mi *MessageType) makeKnownFieldsFunc(si structInfo) {
  168. mi.fields = map[pref.FieldNumber]*fieldInfo{}
  169. mi.fieldsOrdered = make([]*fieldInfo, 0, mi.PBType.Fields().Len())
  170. for i := 0; i < mi.PBType.Descriptor().Fields().Len(); i++ {
  171. fd := mi.PBType.Descriptor().Fields().Get(i)
  172. fs := si.fieldsByNumber[fd.Number()]
  173. var fi fieldInfo
  174. switch {
  175. case fd.ContainingOneof() != nil:
  176. fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], si.oneofWrappersByNumber[fd.Number()])
  177. // There is one fieldInfo for each proto message field, but only one struct
  178. // field for all message fields in a oneof. We install the encoder functions
  179. // on the fieldInfo for the first field in the oneof.
  180. //
  181. // A slightly simpler approach would be to have each fieldInfo's encoder
  182. // handle the case where that field is set, but this would require more
  183. // checks against the current oneof type than a single map lookup.
  184. if fd.ContainingOneof().Fields().Get(0).Name() == fd.Name() {
  185. fi.funcs = makeOneofFieldCoder(si.oneofsByName[fd.ContainingOneof().Name()], fd.ContainingOneof(), si.fieldsByNumber, si.oneofWrappersByNumber)
  186. }
  187. case fd.IsMap():
  188. fi = fieldInfoForMap(fd, fs)
  189. case fd.IsList():
  190. fi = fieldInfoForList(fd, fs)
  191. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  192. fi = fieldInfoForMessage(fd, fs)
  193. default:
  194. fi = fieldInfoForScalar(fd, fs)
  195. }
  196. fi.num = fd.Number()
  197. mi.fields[fd.Number()] = &fi
  198. mi.fieldsOrdered = append(mi.fieldsOrdered, &fi)
  199. }
  200. sort.Slice(mi.fieldsOrdered, func(i, j int) bool {
  201. return mi.fieldsOrdered[i].num < mi.fieldsOrdered[j].num
  202. })
  203. mi.oneofs = map[pref.Name]*oneofInfo{}
  204. for i := 0; i < mi.PBType.Descriptor().Oneofs().Len(); i++ {
  205. od := mi.PBType.Descriptor().Oneofs().Get(i)
  206. mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], si.oneofWrappersByType)
  207. }
  208. }
  209. func (mi *MessageType) makeUnknownFieldsFunc(t reflect.Type) {
  210. if f := makeLegacyUnknownFieldsFunc(t); f != nil {
  211. mi.unknownFields = f
  212. return
  213. }
  214. mi.unknownFields = func(*messageDataType) pref.UnknownFields {
  215. return emptyUnknownFields{}
  216. }
  217. }
  218. func (mi *MessageType) makeExtensionFieldsFunc(t reflect.Type) {
  219. if f := makeLegacyExtensionFieldsFunc(t); f != nil {
  220. mi.extensionFields = f
  221. return
  222. }
  223. mi.extensionFields = func(*messageDataType) pref.KnownFields {
  224. return emptyExtensionFields{}
  225. }
  226. }
  227. func (mi *MessageType) MessageOf(p interface{}) pref.Message {
  228. return (*messageReflectWrapper)(mi.dataTypeOf(p))
  229. }
  230. func (mi *MessageType) Methods() *piface.Methods {
  231. mi.init()
  232. return &mi.methods
  233. }
  234. func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType {
  235. // TODO: Remove this check? This API is primarily used by generated code,
  236. // and should not violate this assumption. Leave this check in for now to
  237. // provide some sanity checks during development. This can be removed if
  238. // it proves to be detrimental to performance.
  239. if reflect.TypeOf(p) != mi.GoType {
  240. panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
  241. }
  242. return &messageDataType{pointerOfIface(p), mi}
  243. }
  244. // messageDataType is a tuple of a pointer to the message data and
  245. // a pointer to the message type.
  246. //
  247. // TODO: Unfortunately, we need to close over a pointer and MessageType,
  248. // which incurs an an allocation. This pair is similar to a Go interface,
  249. // which is essentially a tuple of the same thing. We can make this efficient
  250. // with reflect.NamedOf (see https://golang.org/issues/16522).
  251. //
  252. // With that hypothetical API, we could dynamically create a new named type
  253. // that has the same underlying type as MessageType.GoType, and
  254. // dynamically create methods that close over MessageType.
  255. // Since the new type would have the same underlying type, we could directly
  256. // convert between pointers of those types, giving us an efficient way to swap
  257. // out the method set.
  258. //
  259. // Barring the ability to dynamically create named types, the workaround is
  260. // 1. either to accept the cost of an allocation for this wrapper struct or
  261. // 2. generate more types and methods, at the expense of binary size increase.
  262. type messageDataType struct {
  263. p pointer
  264. mi *MessageType
  265. }
  266. type messageReflectWrapper messageDataType
  267. // TODO: Remove this.
  268. func (m *messageReflectWrapper) Type() pref.MessageType {
  269. return m.mi.PBType
  270. }
  271. func (m *messageReflectWrapper) Descriptor() pref.MessageDescriptor {
  272. return m.mi.PBType.Descriptor()
  273. }
  274. func (m *messageReflectWrapper) KnownFields() pref.KnownFields {
  275. m.mi.init()
  276. return (*knownFields)(m)
  277. }
  278. func (m *messageReflectWrapper) UnknownFields() pref.UnknownFields {
  279. m.mi.init()
  280. return m.mi.unknownFields((*messageDataType)(m))
  281. }
  282. func (m *messageReflectWrapper) New() pref.Message {
  283. return m.mi.PBType.New()
  284. }
  285. func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
  286. if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
  287. return m
  288. }
  289. return (*messageIfaceWrapper)(m)
  290. }
  291. func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
  292. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  293. }
  294. var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
  295. type messageIfaceWrapper messageDataType
  296. func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
  297. return (*messageReflectWrapper)(m)
  298. }
  299. func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
  300. // TODO: Consider not recreating this on every call.
  301. m.mi.init()
  302. return &piface.Methods{
  303. Flags: piface.MethodFlagDeterministicMarshal,
  304. MarshalAppend: m.marshalAppend,
  305. Size: m.size,
  306. }
  307. }
  308. func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
  309. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  310. }
  311. func (m *messageIfaceWrapper) marshalAppend(b []byte, _ pref.ProtoMessage, opts piface.MarshalOptions) ([]byte, error) {
  312. return m.mi.marshalAppendPointer(b, m.p, newMarshalOptions(opts))
  313. }
  314. func (m *messageIfaceWrapper) size(msg pref.ProtoMessage) (size int) {
  315. return m.mi.sizePointer(m.p, 0)
  316. }
  317. type knownFields messageDataType
  318. func (fs *knownFields) Len() (cnt int) {
  319. for _, fi := range fs.mi.fields {
  320. if fi.has(fs.p) {
  321. cnt++
  322. }
  323. }
  324. return cnt + fs.extensionFields().Len()
  325. }
  326. func (fs *knownFields) Has(n pref.FieldNumber) bool {
  327. if fi := fs.mi.fields[n]; fi != nil {
  328. return fi.has(fs.p)
  329. }
  330. return fs.extensionFields().Has(n)
  331. }
  332. func (fs *knownFields) Get(n pref.FieldNumber) pref.Value {
  333. if fi := fs.mi.fields[n]; fi != nil {
  334. return fi.get(fs.p)
  335. }
  336. return fs.extensionFields().Get(n)
  337. }
  338. func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) {
  339. if fi := fs.mi.fields[n]; fi != nil {
  340. fi.set(fs.p, v)
  341. return
  342. }
  343. if fs.mi.PBType.Descriptor().ExtensionRanges().Has(n) {
  344. fs.extensionFields().Set(n, v)
  345. return
  346. }
  347. panic(fmt.Sprintf("invalid field: %d", n))
  348. }
  349. func (fs *knownFields) Clear(n pref.FieldNumber) {
  350. if fi := fs.mi.fields[n]; fi != nil {
  351. fi.clear(fs.p)
  352. return
  353. }
  354. if fs.mi.PBType.Descriptor().ExtensionRanges().Has(n) {
  355. fs.extensionFields().Clear(n)
  356. return
  357. }
  358. }
  359. func (fs *knownFields) WhichOneof(s pref.Name) pref.FieldNumber {
  360. if oi := fs.mi.oneofs[s]; oi != nil {
  361. return oi.which(fs.p)
  362. }
  363. return 0
  364. }
  365. func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) {
  366. for n, fi := range fs.mi.fields {
  367. if fi.has(fs.p) {
  368. if !f(n, fi.get(fs.p)) {
  369. return
  370. }
  371. }
  372. }
  373. fs.extensionFields().Range(f)
  374. }
  375. func (fs *knownFields) NewMessage(n pref.FieldNumber) pref.Message {
  376. if fi := fs.mi.fields[n]; fi != nil {
  377. return fi.newMessage()
  378. }
  379. if fs.mi.PBType.Descriptor().ExtensionRanges().Has(n) {
  380. return fs.extensionFields().NewMessage(n)
  381. }
  382. panic(fmt.Sprintf("invalid field: %d", n))
  383. }
  384. func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes {
  385. return fs.extensionFields().ExtensionTypes()
  386. }
  387. func (fs *knownFields) extensionFields() pref.KnownFields {
  388. return fs.mi.extensionFields((*messageDataType)(fs))
  389. }
  390. type emptyUnknownFields struct{}
  391. func (emptyUnknownFields) Len() int { return 0 }
  392. func (emptyUnknownFields) Get(pref.FieldNumber) pref.RawFields { return nil }
  393. func (emptyUnknownFields) Set(pref.FieldNumber, pref.RawFields) { return } // noop
  394. func (emptyUnknownFields) Range(func(pref.FieldNumber, pref.RawFields) bool) { return }
  395. func (emptyUnknownFields) IsSupported() bool { return false }
  396. type emptyExtensionFields struct{}
  397. func (emptyExtensionFields) Len() int { return 0 }
  398. func (emptyExtensionFields) Has(pref.FieldNumber) bool { return false }
  399. func (emptyExtensionFields) Get(pref.FieldNumber) pref.Value { return pref.Value{} }
  400. func (emptyExtensionFields) Set(pref.FieldNumber, pref.Value) { panic("extensions not supported") }
  401. func (emptyExtensionFields) Clear(pref.FieldNumber) { return } // noop
  402. func (emptyExtensionFields) WhichOneof(pref.Name) pref.FieldNumber { return 0 }
  403. func (emptyExtensionFields) Range(func(pref.FieldNumber, pref.Value) bool) { return }
  404. func (emptyExtensionFields) NewMessage(pref.FieldNumber) pref.Message {
  405. panic("extensions not supported")
  406. }
  407. func (emptyExtensionFields) ExtensionTypes() pref.ExtensionFieldTypes { return emptyExtensionTypes{} }
  408. type emptyExtensionTypes struct{}
  409. func (emptyExtensionTypes) Len() int { return 0 }
  410. func (emptyExtensionTypes) Register(pref.ExtensionType) { panic("extensions not supported") }
  411. func (emptyExtensionTypes) Remove(pref.ExtensionType) { return } // noop
  412. func (emptyExtensionTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil }
  413. func (emptyExtensionTypes) ByName(pref.FullName) pref.ExtensionType { return nil }
  414. func (emptyExtensionTypes) Range(func(pref.ExtensionType) bool) { return }