1 // Go support for Protocol Buffers - Google's data interchange format
3 // Copyright 2017 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
10 // * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 // * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
16 // * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 type generatedDiscarder interface {
46 // DiscardUnknown recursively discards all unknown fields from this message
47 // and all embedded messages.
49 // When unmarshaling a message with unrecognized fields, the tags and values
50 // of such fields are preserved in the Message. This allows a later call to
51 // marshal to be able to produce a message that continues to have those
52 // unrecognized fields. To avoid this, DiscardUnknown is used to
53 // explicitly clear the unknown fields after unmarshaling.
55 // For proto2 messages, the unknown fields of message extensions are only
56 // discarded from messages that have been accessed via GetExtension.
57 func DiscardUnknown(m Message) {
58 if m, ok := m.(generatedDiscarder); ok {
59 m.XXX_DiscardUnknown()
62 // TODO: Dynamically populate a InternalMessageInfo for legacy messages,
63 // but the master branch has no implementation for InternalMessageInfo,
64 // so it would be more work to replicate that approach.
68 // DiscardUnknown recursively discards all unknown fields.
69 func (a *InternalMessageInfo) DiscardUnknown(m Message) {
70 di := atomicLoadDiscardInfo(&a.discard)
72 di = getDiscardInfo(reflect.TypeOf(m).Elem())
73 atomicStoreDiscardInfo(&a.discard, di)
75 di.discard(toPointer(&m))
78 type discardInfo struct {
81 initialized int32 // 0: only typ is valid, 1: everything is valid
84 fields []discardFieldInfo
88 type discardFieldInfo struct {
89 field field // Offset of field, guaranteed to be valid
90 discard func(src pointer)
94 discardInfoMap = map[reflect.Type]*discardInfo{}
95 discardInfoLock sync.Mutex
98 func getDiscardInfo(t reflect.Type) *discardInfo {
99 discardInfoLock.Lock()
100 defer discardInfoLock.Unlock()
101 di := discardInfoMap[t]
103 di = &discardInfo{typ: t}
104 discardInfoMap[t] = di
109 func (di *discardInfo) discard(src pointer) {
111 return // Nothing to do.
114 if atomic.LoadInt32(&di.initialized) == 0 {
115 di.computeDiscardInfo()
118 for _, fi := range di.fields {
119 sfp := src.offset(fi.field)
123 // For proto2 messages, only discard unknown fields in message extensions
124 // that have been accessed via GetExtension.
125 if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
126 // Ignore lock since DiscardUnknown is not concurrency safe.
127 emm, _ := em.extensionsRead()
128 for _, mx := range emm {
129 if m, ok := mx.value.(Message); ok {
135 if di.unrecognized.IsValid() {
136 *src.offset(di.unrecognized).toBytes() = nil
140 func (di *discardInfo) computeDiscardInfo() {
142 defer di.lock.Unlock()
143 if di.initialized != 0 {
149 for i := 0; i < n; i++ {
151 if strings.HasPrefix(f.Name, "XXX_") {
155 dfi := discardFieldInfo{field: toField(&f)}
158 // Unwrap tf to get its most basic type.
159 var isPointer, isSlice bool
160 if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
164 if tf.Kind() == reflect.Ptr {
168 if isPointer && isSlice && tf.Kind() != reflect.Struct {
169 panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
176 panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
177 case isSlice: // E.g., []*pb.T
178 discardInfo := getDiscardInfo(tf)
179 dfi.discard = func(src pointer) {
180 sps := src.getPointerSlice()
181 for _, sp := range sps {
183 discardInfo.discard(sp)
187 default: // E.g., *pb.T
188 discardInfo := getDiscardInfo(tf)
189 dfi.discard = func(src pointer) {
190 sp := src.getPointer()
192 discardInfo.discard(sp)
198 case isPointer || isSlice:
199 panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
200 default: // E.g., map[K]V
201 if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
202 dfi.discard = func(src pointer) {
203 sm := src.asPointerTo(tf).Elem()
207 for _, key := range sm.MapKeys() {
208 val := sm.MapIndex(key)
209 DiscardUnknown(val.Interface().(Message))
213 dfi.discard = func(pointer) {} // Noop
216 case reflect.Interface:
217 // Must be oneof field.
219 case isPointer || isSlice:
220 panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
221 default: // E.g., interface{}
222 // TODO: Make this faster?
223 dfi.discard = func(src pointer) {
224 su := src.asPointerTo(tf).Elem()
226 sv := su.Elem().Elem().Field(0)
227 if sv.Kind() == reflect.Ptr && sv.IsNil() {
230 switch sv.Type().Kind() {
231 case reflect.Ptr: // Proto struct (e.g., *T)
232 DiscardUnknown(sv.Interface().(Message))
240 di.fields = append(di.fields, dfi)
243 di.unrecognized = invalidField
244 if f, ok := t.FieldByName("XXX_unrecognized"); ok {
245 if f.Type != reflect.TypeOf([]byte{}) {
246 panic("expected XXX_unrecognized to be of type []byte")
248 di.unrecognized = toField(&f)
251 atomic.StoreInt32(&di.initialized, 1)
254 func discardLegacy(m Message) {
255 v := reflect.ValueOf(m)
256 if v.Kind() != reflect.Ptr || v.IsNil() {
260 if v.Kind() != reflect.Struct {
265 for i := 0; i < v.NumField(); i++ {
267 if strings.HasPrefix(f.Name, "XXX_") {
273 // Unwrap tf to get its most basic type.
274 var isPointer, isSlice bool
275 if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
279 if tf.Kind() == reflect.Ptr {
283 if isPointer && isSlice && tf.Kind() != reflect.Struct {
284 panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
291 panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
292 case isSlice: // E.g., []*pb.T
293 for j := 0; j < vf.Len(); j++ {
294 discardLegacy(vf.Index(j).Interface().(Message))
296 default: // E.g., *pb.T
297 discardLegacy(vf.Interface().(Message))
301 case isPointer || isSlice:
302 panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
303 default: // E.g., map[K]V
304 tv := vf.Type().Elem()
305 if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
306 for _, key := range vf.MapKeys() {
307 val := vf.MapIndex(key)
308 discardLegacy(val.Interface().(Message))
312 case reflect.Interface:
313 // Must be oneof field.
315 case isPointer || isSlice:
316 panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
317 default: // E.g., test_proto.isCommunique_Union interface
318 if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
319 vf = vf.Elem() // E.g., *test_proto.Communique_Msg
321 vf = vf.Elem() // E.g., test_proto.Communique_Msg
322 vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
323 if vf.Kind() == reflect.Ptr {
324 discardLegacy(vf.Interface().(Message))
332 if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
333 if vf.Type() != reflect.TypeOf([]byte{}) {
334 panic("expected XXX_unrecognized to be of type []byte")
336 vf.Set(reflect.ValueOf([]byte(nil)))
339 // For proto2 messages, only discard unknown fields in message extensions
340 // that have been accessed via GetExtension.
341 if em, err := extendable(m); err == nil {
342 // Ignore lock since discardLegacy is not concurrency safe.
343 emm, _ := em.extensionsRead()
344 for _, mx := range emm {
345 if m, ok := mx.value.(Message); ok {