message.go 17 KB

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