discard.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // Copyright 2017 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 proto
  5. import (
  6. "fmt"
  7. "reflect"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "google.golang.org/protobuf/reflect/protoreflect"
  12. )
  13. type generatedDiscarder interface {
  14. XXX_DiscardUnknown()
  15. }
  16. // DiscardUnknown recursively discards all unknown fields from this message
  17. // and all embedded messages.
  18. //
  19. // When unmarshaling a message with unrecognized fields, the tags and values
  20. // of such fields are preserved in the Message. This allows a later call to
  21. // marshal to be able to produce a message that continues to have those
  22. // unrecognized fields. To avoid this, DiscardUnknown is used to
  23. // explicitly clear the unknown fields after unmarshaling.
  24. //
  25. // For proto2 messages, the unknown fields of message extensions are only
  26. // discarded from messages that have been accessed via GetExtension.
  27. func DiscardUnknown(m Message) {
  28. if discardUnknownAlt != nil {
  29. discardUnknownAlt(m) // populated by hooks_enabled.go
  30. return
  31. }
  32. if m, ok := m.(generatedDiscarder); ok {
  33. m.XXX_DiscardUnknown()
  34. return
  35. }
  36. // TODO: Dynamically populate a InternalMessageInfo for legacy messages,
  37. // but the master branch has no implementation for InternalMessageInfo,
  38. // so it would be more work to replicate that approach.
  39. discardLegacy(m)
  40. }
  41. // DiscardUnknown recursively discards all unknown fields.
  42. func (a *InternalMessageInfo) DiscardUnknown(m Message) {
  43. di := atomicLoadDiscardInfo(&a.discard)
  44. if di == nil {
  45. di = getDiscardInfo(reflect.TypeOf(m).Elem())
  46. atomicStoreDiscardInfo(&a.discard, di)
  47. }
  48. di.discard(toPointer(&m))
  49. }
  50. type discardInfo struct {
  51. typ reflect.Type
  52. initialized int32 // 0: only typ is valid, 1: everything is valid
  53. lock sync.Mutex
  54. fields []discardFieldInfo
  55. unrecognized field
  56. }
  57. type discardFieldInfo struct {
  58. field field // Offset of field, guaranteed to be valid
  59. discard func(src pointer)
  60. }
  61. var (
  62. discardInfoMap = map[reflect.Type]*discardInfo{}
  63. discardInfoLock sync.Mutex
  64. )
  65. func getDiscardInfo(t reflect.Type) *discardInfo {
  66. discardInfoLock.Lock()
  67. defer discardInfoLock.Unlock()
  68. di := discardInfoMap[t]
  69. if di == nil {
  70. di = &discardInfo{typ: t}
  71. discardInfoMap[t] = di
  72. }
  73. return di
  74. }
  75. func (di *discardInfo) discard(src pointer) {
  76. if src.isNil() {
  77. return // Nothing to do.
  78. }
  79. if atomic.LoadInt32(&di.initialized) == 0 {
  80. di.computeDiscardInfo()
  81. }
  82. for _, fi := range di.fields {
  83. sfp := src.offset(fi.field)
  84. fi.discard(sfp)
  85. }
  86. // For proto2 messages, only discard unknown fields in message extensions
  87. // that have been accessed via GetExtension.
  88. if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
  89. em.Range(func(_ protoreflect.FieldNumber, mx Extension) bool {
  90. if m, ok := mx.GetValue().(Message); ok {
  91. DiscardUnknown(m)
  92. }
  93. return true
  94. })
  95. }
  96. if di.unrecognized.IsValid() {
  97. *src.offset(di.unrecognized).toBytes() = nil
  98. }
  99. }
  100. func (di *discardInfo) computeDiscardInfo() {
  101. di.lock.Lock()
  102. defer di.lock.Unlock()
  103. if di.initialized != 0 {
  104. return
  105. }
  106. t := di.typ
  107. n := t.NumField()
  108. for i := 0; i < n; i++ {
  109. f := t.Field(i)
  110. if strings.HasPrefix(f.Name, "XXX_") || f.PkgPath != "" {
  111. continue
  112. }
  113. dfi := discardFieldInfo{field: toField(&f, nil)}
  114. tf := f.Type
  115. // Unwrap tf to get its most basic type.
  116. var isPointer, isSlice bool
  117. if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
  118. isSlice = true
  119. tf = tf.Elem()
  120. }
  121. if tf.Kind() == reflect.Ptr {
  122. isPointer = true
  123. tf = tf.Elem()
  124. }
  125. if isPointer && isSlice && tf.Kind() != reflect.Struct {
  126. panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
  127. }
  128. switch tf.Kind() {
  129. case reflect.Struct:
  130. switch {
  131. case !isPointer:
  132. panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
  133. case isSlice: // E.g., []*pb.T
  134. di := getDiscardInfo(tf)
  135. dfi.discard = func(src pointer) {
  136. sps := src.getPointerSlice()
  137. for _, sp := range sps {
  138. if !sp.isNil() {
  139. di.discard(sp)
  140. }
  141. }
  142. }
  143. default: // E.g., *pb.T
  144. di := getDiscardInfo(tf)
  145. dfi.discard = func(src pointer) {
  146. sp := src.getPointer()
  147. if !sp.isNil() {
  148. di.discard(sp)
  149. }
  150. }
  151. }
  152. case reflect.Map:
  153. switch {
  154. case isPointer || isSlice:
  155. panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
  156. default: // E.g., map[K]V
  157. if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
  158. dfi.discard = func(src pointer) {
  159. sm := src.asPointerTo(tf).Elem()
  160. if sm.Len() == 0 {
  161. return
  162. }
  163. for _, key := range sm.MapKeys() {
  164. val := sm.MapIndex(key)
  165. DiscardUnknown(val.Interface().(Message))
  166. }
  167. }
  168. } else {
  169. dfi.discard = func(pointer) {} // Noop
  170. }
  171. }
  172. case reflect.Interface:
  173. // Must be oneof field.
  174. switch {
  175. case isPointer || isSlice:
  176. panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
  177. default: // E.g., interface{}
  178. // TODO: Make this faster?
  179. dfi.discard = func(src pointer) {
  180. su := src.asPointerTo(tf).Elem()
  181. if !su.IsNil() {
  182. sv := su.Elem().Elem().Field(0)
  183. if sv.Kind() == reflect.Ptr && sv.IsNil() {
  184. return
  185. }
  186. switch sv.Type().Kind() {
  187. case reflect.Ptr: // Proto struct (e.g., *T)
  188. DiscardUnknown(sv.Interface().(Message))
  189. }
  190. }
  191. }
  192. }
  193. default:
  194. continue
  195. }
  196. di.fields = append(di.fields, dfi)
  197. }
  198. expFunc := exporterFunc(t)
  199. di.unrecognized = invalidField
  200. if f, ok := t.FieldByName("XXX_unrecognized"); ok {
  201. if f.Type != reflect.TypeOf([]byte{}) {
  202. panic("expected XXX_unrecognized to be of type []byte")
  203. }
  204. di.unrecognized = toField(&f, nil)
  205. }
  206. if f, ok := t.FieldByName("unknownFields"); ok {
  207. if f.Type != reflect.TypeOf([]byte{}) {
  208. panic("expected unknownFields to be of type []byte")
  209. }
  210. di.unrecognized = toField(&f, expFunc)
  211. }
  212. atomic.StoreInt32(&di.initialized, 1)
  213. }
  214. func discardLegacy(m Message) {
  215. v := reflect.ValueOf(m)
  216. if v.Kind() != reflect.Ptr || v.IsNil() {
  217. return
  218. }
  219. v = v.Elem()
  220. if v.Kind() != reflect.Struct {
  221. return
  222. }
  223. t := v.Type()
  224. for i := 0; i < v.NumField(); i++ {
  225. f := t.Field(i)
  226. if strings.HasPrefix(f.Name, "XXX_") || f.PkgPath != "" {
  227. continue
  228. }
  229. vf := v.Field(i)
  230. tf := f.Type
  231. // Unwrap tf to get its most basic type.
  232. var isPointer, isSlice bool
  233. if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
  234. isSlice = true
  235. tf = tf.Elem()
  236. }
  237. if tf.Kind() == reflect.Ptr {
  238. isPointer = true
  239. tf = tf.Elem()
  240. }
  241. if isPointer && isSlice && tf.Kind() != reflect.Struct {
  242. panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
  243. }
  244. switch tf.Kind() {
  245. case reflect.Struct:
  246. switch {
  247. case !isPointer:
  248. panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
  249. case isSlice: // E.g., []*pb.T
  250. for j := 0; j < vf.Len(); j++ {
  251. discardLegacy(vf.Index(j).Interface().(Message))
  252. }
  253. default: // E.g., *pb.T
  254. discardLegacy(vf.Interface().(Message))
  255. }
  256. case reflect.Map:
  257. switch {
  258. case isPointer || isSlice:
  259. panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
  260. default: // E.g., map[K]V
  261. tv := vf.Type().Elem()
  262. if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
  263. for _, key := range vf.MapKeys() {
  264. val := vf.MapIndex(key)
  265. discardLegacy(val.Interface().(Message))
  266. }
  267. }
  268. }
  269. case reflect.Interface:
  270. // Must be oneof field.
  271. switch {
  272. case isPointer || isSlice:
  273. panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
  274. default: // E.g., test_proto.isCommunique_Union interface
  275. if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
  276. vf = vf.Elem() // E.g., *test_proto.Communique_Msg
  277. if !vf.IsNil() {
  278. vf = vf.Elem() // E.g., test_proto.Communique_Msg
  279. vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
  280. if vf.Kind() == reflect.Ptr {
  281. discardLegacy(vf.Interface().(Message))
  282. }
  283. }
  284. }
  285. }
  286. }
  287. }
  288. if vf := unknownFieldsValue(v); vf.IsValid() {
  289. if vf.Type() != reflect.TypeOf([]byte{}) {
  290. panic("expected unknown fields to be of type []byte")
  291. }
  292. vf.Set(reflect.ValueOf([]byte(nil)))
  293. }
  294. // For proto2 messages, only discard unknown fields in message extensions
  295. // that have been accessed via GetExtension.
  296. if em, err := extendable(m); err == nil {
  297. em.Range(func(_ protoreflect.FieldNumber, mx Extension) bool {
  298. if m, ok := mx.GetValue().(Message); ok {
  299. discardLegacy(m)
  300. }
  301. return true
  302. })
  303. }
  304. }