message.go 15 KB

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