podman
1// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2017 The Go Authors. All rights reserved.
4// https://github.com/golang/protobuf
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
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
15// distribution.
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.
19//
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.
31
32package proto33
34import (35"fmt"36"reflect"37"strings"38"sync"39"sync/atomic"40)
41
42type generatedDiscarder interface {43XXX_DiscardUnknown()44}
45
46// DiscardUnknown recursively discards all unknown fields from this message
47// and all embedded messages.
48//
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.
54//
55// For proto2 messages, the unknown fields of message extensions are only
56// discarded from messages that have been accessed via GetExtension.
57func DiscardUnknown(m Message) {58if m, ok := m.(generatedDiscarder); ok {59m.XXX_DiscardUnknown()60return61}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.65discardLegacy(m)66}
67
68// DiscardUnknown recursively discards all unknown fields.
69func (a *InternalMessageInfo) DiscardUnknown(m Message) {70di := atomicLoadDiscardInfo(&a.discard)71if di == nil {72di = getDiscardInfo(reflect.TypeOf(m).Elem())73atomicStoreDiscardInfo(&a.discard, di)74}75di.discard(toPointer(&m))76}
77
78type discardInfo struct {79typ reflect.Type80
81initialized int32 // 0: only typ is valid, 1: everything is valid82lock sync.Mutex83
84fields []discardFieldInfo85unrecognized field
86}
87
88type discardFieldInfo struct {89field field // Offset of field, guaranteed to be valid90discard func(src pointer)91}
92
93var (94discardInfoMap = map[reflect.Type]*discardInfo{}95discardInfoLock sync.Mutex96)
97
98func getDiscardInfo(t reflect.Type) *discardInfo {99discardInfoLock.Lock()100defer discardInfoLock.Unlock()101di := discardInfoMap[t]102if di == nil {103di = &discardInfo{typ: t}104discardInfoMap[t] = di105}106return di107}
108
109func (di *discardInfo) discard(src pointer) {110if src.isNil() {111return // Nothing to do.112}113
114if atomic.LoadInt32(&di.initialized) == 0 {115di.computeDiscardInfo()116}117
118for _, fi := range di.fields {119sfp := src.offset(fi.field)120fi.discard(sfp)121}122
123// For proto2 messages, only discard unknown fields in message extensions124// that have been accessed via GetExtension.125if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {126// Ignore lock since DiscardUnknown is not concurrency safe.127emm, _ := em.extensionsRead()128for _, mx := range emm {129if m, ok := mx.value.(Message); ok {130DiscardUnknown(m)131}132}133}134
135if di.unrecognized.IsValid() {136*src.offset(di.unrecognized).toBytes() = nil137}138}
139
140func (di *discardInfo) computeDiscardInfo() {141di.lock.Lock()142defer di.lock.Unlock()143if di.initialized != 0 {144return145}146t := di.typ147n := t.NumField()148
149for i := 0; i < n; i++ {150f := t.Field(i)151if strings.HasPrefix(f.Name, "XXX_") {152continue153}154
155dfi := discardFieldInfo{field: toField(&f)}156tf := f.Type157
158// Unwrap tf to get its most basic type.159var isPointer, isSlice bool160if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {161isSlice = true162tf = tf.Elem()163}164if tf.Kind() == reflect.Ptr {165isPointer = true166tf = tf.Elem()167}168if isPointer && isSlice && tf.Kind() != reflect.Struct {169panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))170}171
172switch tf.Kind() {173case reflect.Struct:174switch {175case !isPointer:176panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))177case isSlice: // E.g., []*pb.T178discardInfo := getDiscardInfo(tf)179dfi.discard = func(src pointer) {180sps := src.getPointerSlice()181for _, sp := range sps {182if !sp.isNil() {183discardInfo.discard(sp)184}185}186}187default: // E.g., *pb.T188discardInfo := getDiscardInfo(tf)189dfi.discard = func(src pointer) {190sp := src.getPointer()191if !sp.isNil() {192discardInfo.discard(sp)193}194}195}196case reflect.Map:197switch {198case isPointer || isSlice:199panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))200default: // E.g., map[K]V201if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)202dfi.discard = func(src pointer) {203sm := src.asPointerTo(tf).Elem()204if sm.Len() == 0 {205return206}207for _, key := range sm.MapKeys() {208val := sm.MapIndex(key)209DiscardUnknown(val.Interface().(Message))210}211}212} else {213dfi.discard = func(pointer) {} // Noop214}215}216case reflect.Interface:217// Must be oneof field.218switch {219case isPointer || isSlice:220panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))221default: // E.g., interface{}222// TODO: Make this faster?223dfi.discard = func(src pointer) {224su := src.asPointerTo(tf).Elem()225if !su.IsNil() {226sv := su.Elem().Elem().Field(0)227if sv.Kind() == reflect.Ptr && sv.IsNil() {228return229}230switch sv.Type().Kind() {231case reflect.Ptr: // Proto struct (e.g., *T)232DiscardUnknown(sv.Interface().(Message))233}234}235}236}237default:238continue239}240di.fields = append(di.fields, dfi)241}242
243di.unrecognized = invalidField244if f, ok := t.FieldByName("XXX_unrecognized"); ok {245if f.Type != reflect.TypeOf([]byte{}) {246panic("expected XXX_unrecognized to be of type []byte")247}248di.unrecognized = toField(&f)249}250
251atomic.StoreInt32(&di.initialized, 1)252}
253
254func discardLegacy(m Message) {255v := reflect.ValueOf(m)256if v.Kind() != reflect.Ptr || v.IsNil() {257return258}259v = v.Elem()260if v.Kind() != reflect.Struct {261return262}263t := v.Type()264
265for i := 0; i < v.NumField(); i++ {266f := t.Field(i)267if strings.HasPrefix(f.Name, "XXX_") {268continue269}270vf := v.Field(i)271tf := f.Type272
273// Unwrap tf to get its most basic type.274var isPointer, isSlice bool275if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {276isSlice = true277tf = tf.Elem()278}279if tf.Kind() == reflect.Ptr {280isPointer = true281tf = tf.Elem()282}283if isPointer && isSlice && tf.Kind() != reflect.Struct {284panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))285}286
287switch tf.Kind() {288case reflect.Struct:289switch {290case !isPointer:291panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))292case isSlice: // E.g., []*pb.T293for j := 0; j < vf.Len(); j++ {294discardLegacy(vf.Index(j).Interface().(Message))295}296default: // E.g., *pb.T297discardLegacy(vf.Interface().(Message))298}299case reflect.Map:300switch {301case isPointer || isSlice:302panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))303default: // E.g., map[K]V304tv := vf.Type().Elem()305if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)306for _, key := range vf.MapKeys() {307val := vf.MapIndex(key)308discardLegacy(val.Interface().(Message))309}310}311}312case reflect.Interface:313// Must be oneof field.314switch {315case isPointer || isSlice:316panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))317default: // E.g., test_proto.isCommunique_Union interface318if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {319vf = vf.Elem() // E.g., *test_proto.Communique_Msg320if !vf.IsNil() {321vf = vf.Elem() // E.g., test_proto.Communique_Msg322vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value323if vf.Kind() == reflect.Ptr {324discardLegacy(vf.Interface().(Message))325}326}327}328}329}330}331
332if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {333if vf.Type() != reflect.TypeOf([]byte{}) {334panic("expected XXX_unrecognized to be of type []byte")335}336vf.Set(reflect.ValueOf([]byte(nil)))337}338
339// For proto2 messages, only discard unknown fields in message extensions340// that have been accessed via GetExtension.341if em, err := extendable(m); err == nil {342// Ignore lock since discardLegacy is not concurrency safe.343emm, _ := em.extensionsRead()344for _, mx := range emm {345if m, ok := mx.value.(Message); ok {346discardLegacy(m)347}348}349}350}
351