message.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. pvalue "google.golang.org/protobuf/internal/value"
  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. type MessageInfo struct {
  20. // GoType is the underlying message Go type and must be populated.
  21. // Once set, this field must never be mutated.
  22. GoType reflect.Type // pointer to struct
  23. // PBType is the underlying message descriptor type and must be populated.
  24. // Once set, this field must never be mutated.
  25. PBType pref.MessageType
  26. initMu sync.Mutex // protects all unexported fields
  27. initDone uint32
  28. fields map[pref.FieldNumber]*fieldInfo
  29. oneofs map[pref.Name]*oneofInfo
  30. getUnknown func(pointer) pref.RawFields
  31. setUnknown func(pointer, pref.RawFields)
  32. extensionMap func(pointer) *extensionMap
  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. var prefMessageType = reflect.TypeOf((*pref.Message)(nil)).Elem()
  40. // getMessageInfo returns the MessageInfo (if any) for a type.
  41. //
  42. // We find the MessageInfo by calling the ProtoReflect method on the type's
  43. // zero value and looking at the returned type to see if it is a
  44. // messageReflectWrapper. Note that the MessageInfo may still be uninitialized
  45. // at this point.
  46. func getMessageInfo(mt reflect.Type) (mi *MessageInfo, ok bool) {
  47. method, ok := mt.MethodByName("ProtoReflect")
  48. if !ok {
  49. return nil, false
  50. }
  51. if method.Type.NumIn() != 1 || method.Type.NumOut() != 1 || method.Type.Out(0) != prefMessageType {
  52. return nil, false
  53. }
  54. ret := reflect.Zero(mt).Method(method.Index).Call(nil)
  55. m, ok := ret[0].Elem().Interface().(*messageReflectWrapper)
  56. if !ok {
  57. return nil, ok
  58. }
  59. return m.mi, true
  60. }
  61. func (mi *MessageInfo) init() {
  62. // This function is called in the hot path. Inline the sync.Once
  63. // logic, since allocating a closure for Once.Do is expensive.
  64. // Keep init small to ensure that it can be inlined.
  65. if atomic.LoadUint32(&mi.initDone) == 1 {
  66. return
  67. }
  68. mi.initOnce()
  69. }
  70. func (mi *MessageInfo) initOnce() {
  71. mi.initMu.Lock()
  72. defer mi.initMu.Unlock()
  73. if mi.initDone == 1 {
  74. return
  75. }
  76. t := mi.GoType
  77. if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
  78. panic(fmt.Sprintf("got %v, want *struct kind", t))
  79. }
  80. si := mi.makeStructInfo(t.Elem())
  81. mi.makeKnownFieldsFunc(si)
  82. mi.makeUnknownFieldsFunc(t.Elem())
  83. mi.makeExtensionFieldsFunc(t.Elem())
  84. mi.makeMethods(t.Elem(), si)
  85. atomic.StoreUint32(&mi.initDone, 1)
  86. }
  87. type (
  88. SizeCache = int32
  89. UnknownFields = []byte
  90. ExtensionFields = map[int32]ExtensionField
  91. )
  92. var (
  93. sizecacheType = reflect.TypeOf(SizeCache(0))
  94. unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
  95. extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
  96. )
  97. type structInfo struct {
  98. fieldsByNumber map[pref.FieldNumber]reflect.StructField
  99. oneofsByName map[pref.Name]reflect.StructField
  100. oneofWrappersByType map[reflect.Type]pref.FieldNumber
  101. oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
  102. }
  103. func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
  104. // Generate a mapping of field numbers and names to Go struct field or type.
  105. si := structInfo{
  106. fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
  107. oneofsByName: map[pref.Name]reflect.StructField{},
  108. oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
  109. oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
  110. }
  111. fieldLoop:
  112. for i := 0; i < t.NumField(); i++ {
  113. f := t.Field(i)
  114. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  115. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  116. n, _ := strconv.ParseUint(s, 10, 64)
  117. si.fieldsByNumber[pref.FieldNumber(n)] = f
  118. continue fieldLoop
  119. }
  120. }
  121. if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
  122. si.oneofsByName[pref.Name(s)] = f
  123. continue fieldLoop
  124. }
  125. }
  126. var oneofWrappers []interface{}
  127. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
  128. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
  129. }
  130. if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
  131. oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
  132. }
  133. for _, v := range oneofWrappers {
  134. tf := reflect.TypeOf(v).Elem()
  135. f := tf.Field(0)
  136. for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
  137. if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
  138. n, _ := strconv.ParseUint(s, 10, 64)
  139. si.oneofWrappersByType[tf] = pref.FieldNumber(n)
  140. si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
  141. break
  142. }
  143. }
  144. }
  145. return si
  146. }
  147. // makeKnownFieldsFunc generates functions for operations that can be performed
  148. // on each protobuf message field. It takes in a reflect.Type representing the
  149. // Go struct and matches message fields with struct fields.
  150. //
  151. // This code assumes that the struct is well-formed and panics if there are
  152. // any discrepancies.
  153. func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
  154. mi.fields = map[pref.FieldNumber]*fieldInfo{}
  155. for i := 0; i < mi.PBType.Descriptor().Fields().Len(); i++ {
  156. fd := mi.PBType.Descriptor().Fields().Get(i)
  157. fs := si.fieldsByNumber[fd.Number()]
  158. var fi fieldInfo
  159. switch {
  160. case fd.ContainingOneof() != nil:
  161. fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], si.oneofWrappersByNumber[fd.Number()])
  162. case fd.IsMap():
  163. fi = fieldInfoForMap(fd, fs)
  164. case fd.IsList():
  165. fi = fieldInfoForList(fd, fs)
  166. case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
  167. fi = fieldInfoForMessage(fd, fs)
  168. default:
  169. fi = fieldInfoForScalar(fd, fs)
  170. }
  171. mi.fields[fd.Number()] = &fi
  172. }
  173. mi.oneofs = map[pref.Name]*oneofInfo{}
  174. for i := 0; i < mi.PBType.Descriptor().Oneofs().Len(); i++ {
  175. od := mi.PBType.Descriptor().Oneofs().Get(i)
  176. mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], si.oneofWrappersByType)
  177. }
  178. }
  179. func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type) {
  180. mi.getUnknown = func(pointer) pref.RawFields { return nil }
  181. mi.setUnknown = func(pointer, pref.RawFields) { return }
  182. fu, _ := t.FieldByName("XXX_unrecognized")
  183. if fu.Type == unknownFieldsType {
  184. fieldOffset := offsetOf(fu)
  185. mi.getUnknown = func(p pointer) pref.RawFields {
  186. if p.IsNil() {
  187. return nil
  188. }
  189. rv := p.Apply(fieldOffset).AsValueOf(unknownFieldsType)
  190. return pref.RawFields(*rv.Interface().(*[]byte))
  191. }
  192. mi.setUnknown = func(p pointer, b pref.RawFields) {
  193. if p.IsNil() {
  194. panic("invalid SetUnknown on nil Message")
  195. }
  196. rv := p.Apply(fieldOffset).AsValueOf(unknownFieldsType)
  197. *rv.Interface().(*[]byte) = []byte(b)
  198. }
  199. } else {
  200. mi.getUnknown = func(pointer) pref.RawFields {
  201. return nil
  202. }
  203. mi.setUnknown = func(p pointer, _ pref.RawFields) {
  204. if p.IsNil() {
  205. panic("invalid SetUnknown on nil Message")
  206. }
  207. }
  208. }
  209. }
  210. func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type) {
  211. fx, _ := t.FieldByName("XXX_extensions")
  212. if fx.Type != extensionFieldsType {
  213. fx, _ = t.FieldByName("XXX_InternalExtensions")
  214. }
  215. if fx.Type == extensionFieldsType {
  216. fieldOffset := offsetOf(fx)
  217. mi.extensionMap = func(p pointer) *extensionMap {
  218. if p.IsNil() {
  219. return (*extensionMap)(nil)
  220. }
  221. v := p.Apply(fieldOffset).AsValueOf(extensionFieldsType)
  222. return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
  223. }
  224. } else {
  225. mi.extensionMap = func(pointer) *extensionMap {
  226. return (*extensionMap)(nil)
  227. }
  228. }
  229. }
  230. func (mi *MessageInfo) MessageOf(p interface{}) pref.Message {
  231. return (*messageReflectWrapper)(mi.dataTypeOf(p))
  232. }
  233. func (mi *MessageInfo) Methods() *piface.Methods {
  234. mi.init()
  235. return &mi.methods
  236. }
  237. func (mi *MessageInfo) dataTypeOf(p interface{}) *messageDataType {
  238. // TODO: Remove this check? This API is primarily used by generated code,
  239. // and should not violate this assumption. Leave this check in for now to
  240. // provide some sanity checks during development. This can be removed if
  241. // it proves to be detrimental to performance.
  242. if reflect.TypeOf(p) != mi.GoType {
  243. panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.GoType))
  244. }
  245. return &messageDataType{pointerOfIface(p), mi}
  246. }
  247. // messageDataType is a tuple of a pointer to the message data and
  248. // a pointer to the message type.
  249. //
  250. // TODO: Unfortunately, we need to close over a pointer and MessageInfo,
  251. // which incurs an an allocation. This pair is similar to a Go interface,
  252. // which is essentially a tuple of the same thing. We can make this efficient
  253. // with reflect.NamedOf (see https://golang.org/issues/16522).
  254. //
  255. // With that hypothetical API, we could dynamically create a new named type
  256. // that has the same underlying type as MessageInfo.GoType, and
  257. // dynamically create methods that close over MessageInfo.
  258. // Since the new type would have the same underlying type, we could directly
  259. // convert between pointers of those types, giving us an efficient way to swap
  260. // out the method set.
  261. //
  262. // Barring the ability to dynamically create named types, the workaround is
  263. // 1. either to accept the cost of an allocation for this wrapper struct or
  264. // 2. generate more types and methods, at the expense of binary size increase.
  265. type messageDataType struct {
  266. p pointer
  267. mi *MessageInfo
  268. }
  269. type messageReflectWrapper messageDataType
  270. func (m *messageReflectWrapper) Descriptor() pref.MessageDescriptor {
  271. return m.mi.PBType.Descriptor()
  272. }
  273. func (m *messageReflectWrapper) New() pref.Message {
  274. return m.mi.PBType.New()
  275. }
  276. func (m *messageReflectWrapper) Interface() pref.ProtoMessage {
  277. if m, ok := m.ProtoUnwrap().(pref.ProtoMessage); ok {
  278. return m
  279. }
  280. return (*messageIfaceWrapper)(m)
  281. }
  282. func (m *messageReflectWrapper) ProtoUnwrap() interface{} {
  283. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  284. }
  285. func (m *messageReflectWrapper) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
  286. m.mi.init()
  287. for _, fi := range m.mi.fields {
  288. if fi.has(m.p) {
  289. if !f(fi.fieldDesc, fi.get(m.p)) {
  290. return
  291. }
  292. }
  293. }
  294. m.mi.extensionMap(m.p).Range(f)
  295. }
  296. func (m *messageReflectWrapper) Has(fd pref.FieldDescriptor) bool {
  297. if fi, xt := m.checkField(fd); fi != nil {
  298. return fi.has(m.p)
  299. } else {
  300. return m.mi.extensionMap(m.p).Has(xt)
  301. }
  302. }
  303. func (m *messageReflectWrapper) Clear(fd pref.FieldDescriptor) {
  304. if fi, xt := m.checkField(fd); fi != nil {
  305. fi.clear(m.p)
  306. } else {
  307. m.mi.extensionMap(m.p).Clear(xt)
  308. }
  309. }
  310. func (m *messageReflectWrapper) Get(fd pref.FieldDescriptor) pref.Value {
  311. if fi, xt := m.checkField(fd); fi != nil {
  312. return fi.get(m.p)
  313. } else {
  314. return m.mi.extensionMap(m.p).Get(xt)
  315. }
  316. }
  317. func (m *messageReflectWrapper) Set(fd pref.FieldDescriptor, v pref.Value) {
  318. if fi, xt := m.checkField(fd); fi != nil {
  319. fi.set(m.p, v)
  320. } else {
  321. m.mi.extensionMap(m.p).Set(xt, v)
  322. }
  323. }
  324. func (m *messageReflectWrapper) Mutable(fd pref.FieldDescriptor) pref.Value {
  325. if fi, xt := m.checkField(fd); fi != nil {
  326. return fi.mutable(m.p)
  327. } else {
  328. return m.mi.extensionMap(m.p).Mutable(xt)
  329. }
  330. }
  331. func (m *messageReflectWrapper) NewMessage(fd pref.FieldDescriptor) pref.Message {
  332. if fi, xt := m.checkField(fd); fi != nil {
  333. return fi.newMessage()
  334. } else {
  335. return xt.New().Message()
  336. }
  337. }
  338. func (m *messageReflectWrapper) WhichOneof(od pref.OneofDescriptor) pref.FieldDescriptor {
  339. m.mi.init()
  340. if oi := m.mi.oneofs[od.Name()]; oi != nil && oi.oneofDesc == od {
  341. return od.Fields().ByNumber(oi.which(m.p))
  342. }
  343. panic("invalid oneof descriptor")
  344. }
  345. func (m *messageReflectWrapper) GetUnknown() pref.RawFields {
  346. m.mi.init()
  347. return m.mi.getUnknown(m.p)
  348. }
  349. func (m *messageReflectWrapper) SetUnknown(b pref.RawFields) {
  350. m.mi.init()
  351. m.mi.setUnknown(m.p, b)
  352. }
  353. // checkField verifies that the provided field descriptor is valid.
  354. // Exactly one of the returned values is populated.
  355. func (m *messageReflectWrapper) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) {
  356. m.mi.init()
  357. if fi := m.mi.fields[fd.Number()]; fi != nil {
  358. if fi.fieldDesc != fd {
  359. panic("mismatching field descriptor")
  360. }
  361. return fi, nil
  362. }
  363. if fd.IsExtension() {
  364. if fd.ContainingMessage().FullName() != m.mi.PBType.FullName() {
  365. // TODO: Should this be exact containing message descriptor match?
  366. panic("mismatching containing message")
  367. }
  368. if !m.mi.PBType.ExtensionRanges().Has(fd.Number()) {
  369. panic("invalid extension field")
  370. }
  371. return nil, fd.(pref.ExtensionType)
  372. }
  373. panic("invalid field descriptor")
  374. }
  375. type extensionMap map[int32]ExtensionField
  376. func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) {
  377. if m != nil {
  378. for _, x := range *m {
  379. xt := x.GetType()
  380. if !f(xt, xt.ValueOf(x.GetValue())) {
  381. return
  382. }
  383. }
  384. }
  385. }
  386. func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) {
  387. if m != nil {
  388. _, ok = (*m)[int32(xt.Number())]
  389. }
  390. return ok
  391. }
  392. func (m *extensionMap) Clear(xt pref.ExtensionType) {
  393. delete(*m, int32(xt.Number()))
  394. }
  395. func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value {
  396. if m != nil {
  397. if x, ok := (*m)[int32(xt.Number())]; ok {
  398. return xt.ValueOf(x.GetValue())
  399. }
  400. }
  401. if !isComposite(xt) {
  402. return defaultValueOf(xt)
  403. }
  404. return frozenValueOf(xt.New())
  405. }
  406. func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) {
  407. if *m == nil {
  408. *m = make(map[int32]ExtensionField)
  409. }
  410. var x ExtensionField
  411. x.SetType(xt)
  412. x.SetEagerValue(xt.InterfaceOf(v))
  413. (*m)[int32(xt.Number())] = x
  414. }
  415. func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value {
  416. if !isComposite(xt) {
  417. panic("invalid Mutable on field with non-composite type")
  418. }
  419. if x, ok := (*m)[int32(xt.Number())]; ok {
  420. return xt.ValueOf(x.GetValue())
  421. }
  422. v := xt.New()
  423. m.Set(xt, v)
  424. return v
  425. }
  426. func isComposite(fd pref.FieldDescriptor) bool {
  427. return fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind || fd.IsList() || fd.IsMap()
  428. }
  429. var _ pvalue.Unwrapper = (*messageReflectWrapper)(nil)
  430. type messageIfaceWrapper messageDataType
  431. func (m *messageIfaceWrapper) ProtoReflect() pref.Message {
  432. return (*messageReflectWrapper)(m)
  433. }
  434. func (m *messageIfaceWrapper) XXX_Methods() *piface.Methods {
  435. // TODO: Consider not recreating this on every call.
  436. m.mi.init()
  437. return &piface.Methods{
  438. Flags: piface.MethodFlagDeterministicMarshal,
  439. MarshalAppend: m.marshalAppend,
  440. Size: m.size,
  441. }
  442. }
  443. func (m *messageIfaceWrapper) ProtoUnwrap() interface{} {
  444. return m.p.AsIfaceOf(m.mi.GoType.Elem())
  445. }
  446. func (m *messageIfaceWrapper) marshalAppend(b []byte, _ pref.ProtoMessage, opts piface.MarshalOptions) ([]byte, error) {
  447. return m.mi.marshalAppendPointer(b, m.p, newMarshalOptions(opts))
  448. }
  449. func (m *messageIfaceWrapper) size(msg pref.ProtoMessage) (size int) {
  450. return m.mi.sizePointer(m.p, 0)
  451. }