1
2
3
4
5 package impl
6
7 import (
8 "fmt"
9 "reflect"
10 "strings"
11 "sync"
12
13 "google.golang.org/protobuf/internal/descopts"
14 ptag "google.golang.org/protobuf/internal/encoding/tag"
15 "google.golang.org/protobuf/internal/errors"
16 "google.golang.org/protobuf/internal/filedesc"
17 "google.golang.org/protobuf/internal/strs"
18 "google.golang.org/protobuf/reflect/protoreflect"
19 "google.golang.org/protobuf/runtime/protoiface"
20 )
21
22
23
24 func legacyWrapMessage(v reflect.Value) protoreflect.Message {
25 t := v.Type()
26 if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
27 return aberrantMessage{v: v}
28 }
29 mt := legacyLoadMessageInfo(t, "")
30 return mt.MessageOf(v.Interface())
31 }
32
33
34
35
36 func legacyLoadMessageType(t reflect.Type, name protoreflect.FullName) protoreflect.MessageType {
37 if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
38 return aberrantMessageType{t}
39 }
40 return legacyLoadMessageInfo(t, name)
41 }
42
43 var legacyMessageTypeCache sync.Map
44
45
46
47
48 func legacyLoadMessageInfo(t reflect.Type, name protoreflect.FullName) *MessageInfo {
49
50 if mt, ok := legacyMessageTypeCache.Load(t); ok {
51 return mt.(*MessageInfo)
52 }
53
54
55 mi := &MessageInfo{
56 Desc: legacyLoadMessageDesc(t, name),
57 GoReflectType: t,
58 }
59
60 var hasMarshal, hasUnmarshal bool
61 v := reflect.Zero(t).Interface()
62 if _, hasMarshal = v.(legacyMarshaler); hasMarshal {
63 mi.methods.Marshal = legacyMarshal
64
65
66
67
68
69 mi.methods.Flags |= protoiface.SupportMarshalDeterministic
70 }
71 if _, hasUnmarshal = v.(legacyUnmarshaler); hasUnmarshal {
72 mi.methods.Unmarshal = legacyUnmarshal
73 }
74 if _, hasMerge := v.(legacyMerger); hasMerge || (hasMarshal && hasUnmarshal) {
75 mi.methods.Merge = legacyMerge
76 }
77
78 if mi, ok := legacyMessageTypeCache.LoadOrStore(t, mi); ok {
79 return mi.(*MessageInfo)
80 }
81 return mi
82 }
83
84 var legacyMessageDescCache sync.Map
85
86
87
88
89
90 func LegacyLoadMessageDesc(t reflect.Type) protoreflect.MessageDescriptor {
91 return legacyLoadMessageDesc(t, "")
92 }
93 func legacyLoadMessageDesc(t reflect.Type, name protoreflect.FullName) protoreflect.MessageDescriptor {
94
95 if mi, ok := legacyMessageDescCache.Load(t); ok {
96 return mi.(protoreflect.MessageDescriptor)
97 }
98
99
100 mv := reflect.Zero(t).Interface()
101 if _, ok := mv.(protoreflect.ProtoMessage); ok {
102 panic(fmt.Sprintf("%v already implements proto.Message", t))
103 }
104 mdV1, ok := mv.(messageV1)
105 if !ok {
106 return aberrantLoadMessageDesc(t, name)
107 }
108
109
110
111
112
113 b, idxs := func() ([]byte, []int) {
114 defer func() {
115 recover()
116 }()
117 return mdV1.Descriptor()
118 }()
119 if b == nil {
120 return aberrantLoadMessageDesc(t, name)
121 }
122
123
124
125
126 if t.Elem().Kind() == reflect.Struct {
127 if nfield := t.Elem().NumField(); nfield > 0 {
128 hasProtoField := false
129 for i := 0; i < nfield; i++ {
130 f := t.Elem().Field(i)
131 if f.Tag.Get("protobuf") != "" || f.Tag.Get("protobuf_oneof") != "" || strings.HasPrefix(f.Name, "XXX_") {
132 hasProtoField = true
133 break
134 }
135 }
136 if !hasProtoField {
137 return aberrantLoadMessageDesc(t, name)
138 }
139 }
140 }
141
142 md := legacyLoadFileDesc(b).Messages().Get(idxs[0])
143 for _, i := range idxs[1:] {
144 md = md.Messages().Get(i)
145 }
146 if name != "" && md.FullName() != name {
147 panic(fmt.Sprintf("mismatching message name: got %v, want %v", md.FullName(), name))
148 }
149 if md, ok := legacyMessageDescCache.LoadOrStore(t, md); ok {
150 return md.(protoreflect.MessageDescriptor)
151 }
152 return md
153 }
154
155 var (
156 aberrantMessageDescLock sync.Mutex
157 aberrantMessageDescCache map[reflect.Type]protoreflect.MessageDescriptor
158 )
159
160
161
162
163
164
165 func aberrantLoadMessageDesc(t reflect.Type, name protoreflect.FullName) protoreflect.MessageDescriptor {
166 aberrantMessageDescLock.Lock()
167 defer aberrantMessageDescLock.Unlock()
168 if aberrantMessageDescCache == nil {
169 aberrantMessageDescCache = make(map[reflect.Type]protoreflect.MessageDescriptor)
170 }
171 return aberrantLoadMessageDescReentrant(t, name)
172 }
173 func aberrantLoadMessageDescReentrant(t reflect.Type, name protoreflect.FullName) protoreflect.MessageDescriptor {
174
175 if md, ok := aberrantMessageDescCache[t]; ok {
176 return md
177 }
178
179
180
181
182 md := &filedesc.Message{L2: new(filedesc.MessageL2)}
183 md.L0.FullName = aberrantDeriveMessageName(t, name)
184 md.L0.ParentFile = filedesc.SurrogateProto2
185 aberrantMessageDescCache[t] = md
186
187 if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
188 return md
189 }
190
191
192 for i := 0; i < t.Elem().NumField(); i++ {
193 f := t.Elem().Field(i)
194 if tag := f.Tag.Get("protobuf"); tag != "" {
195 switch f.Type.Kind() {
196 case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
197 md.L0.ParentFile = filedesc.SurrogateProto3
198 }
199 for _, s := range strings.Split(tag, ",") {
200 if s == "proto3" {
201 md.L0.ParentFile = filedesc.SurrogateProto3
202 }
203 }
204 }
205 }
206
207 md.L1.EditionFeatures = md.L0.ParentFile.L1.EditionFeatures
208
209 var oneofWrappers []reflect.Type
210 methods := make([]reflect.Method, 0, 2)
211 if m, ok := t.MethodByName("XXX_OneofFuncs"); ok {
212 methods = append(methods, m)
213 }
214 if m, ok := t.MethodByName("XXX_OneofWrappers"); ok {
215 methods = append(methods, m)
216 }
217 for _, fn := range methods {
218 for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) {
219 if vs, ok := v.Interface().([]interface{}); ok {
220 for _, v := range vs {
221 oneofWrappers = append(oneofWrappers, reflect.TypeOf(v))
222 }
223 }
224 }
225 }
226
227
228 if fn, ok := t.MethodByName("ExtensionRangeArray"); ok {
229 vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0]
230 for i := 0; i < vs.Len(); i++ {
231 v := vs.Index(i)
232 md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]protoreflect.FieldNumber{
233 protoreflect.FieldNumber(v.FieldByName("Start").Int()),
234 protoreflect.FieldNumber(v.FieldByName("End").Int() + 1),
235 })
236 md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil)
237 }
238 }
239
240
241 for i := 0; i < t.Elem().NumField(); i++ {
242 f := t.Elem().Field(i)
243 if tag := f.Tag.Get("protobuf"); tag != "" {
244 tagKey := f.Tag.Get("protobuf_key")
245 tagVal := f.Tag.Get("protobuf_val")
246 aberrantAppendField(md, f.Type, tag, tagKey, tagVal)
247 }
248 if tag := f.Tag.Get("protobuf_oneof"); tag != "" {
249 n := len(md.L2.Oneofs.List)
250 md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{})
251 od := &md.L2.Oneofs.List[n]
252 od.L0.FullName = md.FullName().Append(protoreflect.Name(tag))
253 od.L0.ParentFile = md.L0.ParentFile
254 od.L1.EditionFeatures = md.L1.EditionFeatures
255 od.L0.Parent = md
256 od.L0.Index = n
257
258 for _, t := range oneofWrappers {
259 if t.Implements(f.Type) {
260 f := t.Elem().Field(0)
261 if tag := f.Tag.Get("protobuf"); tag != "" {
262 aberrantAppendField(md, f.Type, tag, "", "")
263 fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1]
264 fd.L1.ContainingOneof = od
265 fd.L1.EditionFeatures = od.L1.EditionFeatures
266 od.L1.Fields.List = append(od.L1.Fields.List, fd)
267 }
268 }
269 }
270 }
271 }
272
273 return md
274 }
275
276 func aberrantDeriveMessageName(t reflect.Type, name protoreflect.FullName) protoreflect.FullName {
277 if name.IsValid() {
278 return name
279 }
280 func() {
281 defer func() { recover() }()
282 if m, ok := reflect.Zero(t).Interface().(interface{ XXX_MessageName() string }); ok {
283 name = protoreflect.FullName(m.XXX_MessageName())
284 }
285 }()
286 if name.IsValid() {
287 return name
288 }
289 if t.Kind() == reflect.Ptr {
290 t = t.Elem()
291 }
292 return AberrantDeriveFullName(t)
293 }
294
295 func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) {
296 t := goType
297 isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct
298 isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
299 if isOptional || isRepeated {
300 t = t.Elem()
301 }
302 fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field)
303
304
305 n := len(md.L2.Fields.List)
306 md.L2.Fields.List = append(md.L2.Fields.List, *fd)
307 fd = &md.L2.Fields.List[n]
308 fd.L0.FullName = md.FullName().Append(fd.Name())
309 fd.L0.ParentFile = md.L0.ParentFile
310 fd.L0.Parent = md
311 fd.L0.Index = n
312
313 if fd.L1.IsWeak || fd.L1.EditionFeatures.IsPacked {
314 fd.L1.Options = func() protoreflect.ProtoMessage {
315 opts := descopts.Field.ProtoReflect().New()
316 if fd.L1.IsWeak {
317 opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOfBool(true))
318 }
319 if fd.L1.EditionFeatures.IsPacked {
320 opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOfBool(fd.L1.EditionFeatures.IsPacked))
321 }
322 return opts.Interface()
323 }
324 }
325
326
327 if fd.Enum() == nil && fd.Kind() == protoreflect.EnumKind {
328 switch v := reflect.Zero(t).Interface().(type) {
329 case protoreflect.Enum:
330 fd.L1.Enum = v.Descriptor()
331 default:
332 fd.L1.Enum = LegacyLoadEnumDesc(t)
333 }
334 }
335 if fd.Message() == nil && (fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind) {
336 switch v := reflect.Zero(t).Interface().(type) {
337 case protoreflect.ProtoMessage:
338 fd.L1.Message = v.ProtoReflect().Descriptor()
339 case messageV1:
340 fd.L1.Message = LegacyLoadMessageDesc(t)
341 default:
342 if t.Kind() == reflect.Map {
343 n := len(md.L1.Messages.List)
344 md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)})
345 md2 := &md.L1.Messages.List[n]
346 md2.L0.FullName = md.FullName().Append(protoreflect.Name(strs.MapEntryName(string(fd.Name()))))
347 md2.L0.ParentFile = md.L0.ParentFile
348 md2.L0.Parent = md
349 md2.L0.Index = n
350 md2.L1.EditionFeatures = md.L1.EditionFeatures
351
352 md2.L1.IsMapEntry = true
353 md2.L2.Options = func() protoreflect.ProtoMessage {
354 opts := descopts.Message.ProtoReflect().New()
355 opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOfBool(true))
356 return opts.Interface()
357 }
358
359 aberrantAppendField(md2, t.Key(), tagKey, "", "")
360 aberrantAppendField(md2, t.Elem(), tagVal, "", "")
361
362 fd.L1.Message = md2
363 break
364 }
365 fd.L1.Message = aberrantLoadMessageDescReentrant(t, "")
366 }
367 }
368 }
369
370 type placeholderEnumValues struct {
371 protoreflect.EnumValueDescriptors
372 }
373
374 func (placeholderEnumValues) ByNumber(n protoreflect.EnumNumber) protoreflect.EnumValueDescriptor {
375 return filedesc.PlaceholderEnumValue(protoreflect.FullName(fmt.Sprintf("UNKNOWN_%d", n)))
376 }
377
378
379 type legacyMarshaler interface {
380 Marshal() ([]byte, error)
381 }
382
383
384 type legacyUnmarshaler interface {
385 Unmarshal([]byte) error
386 }
387
388
389 type legacyMerger interface {
390 Merge(protoiface.MessageV1)
391 }
392
393 var aberrantProtoMethods = &protoiface.Methods{
394 Marshal: legacyMarshal,
395 Unmarshal: legacyUnmarshal,
396 Merge: legacyMerge,
397
398
399
400
401
402 Flags: protoiface.SupportMarshalDeterministic,
403 }
404
405 func legacyMarshal(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) {
406 v := in.Message.(unwrapper).protoUnwrap()
407 marshaler, ok := v.(legacyMarshaler)
408 if !ok {
409 return protoiface.MarshalOutput{}, errors.New("%T does not implement Marshal", v)
410 }
411 out, err := marshaler.Marshal()
412 if in.Buf != nil {
413 out = append(in.Buf, out...)
414 }
415 return protoiface.MarshalOutput{
416 Buf: out,
417 }, err
418 }
419
420 func legacyUnmarshal(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) {
421 v := in.Message.(unwrapper).protoUnwrap()
422 unmarshaler, ok := v.(legacyUnmarshaler)
423 if !ok {
424 return protoiface.UnmarshalOutput{}, errors.New("%T does not implement Unmarshal", v)
425 }
426 return protoiface.UnmarshalOutput{}, unmarshaler.Unmarshal(in.Buf)
427 }
428
429 func legacyMerge(in protoiface.MergeInput) protoiface.MergeOutput {
430
431 dstv := in.Destination.(unwrapper).protoUnwrap()
432 merger, ok := dstv.(legacyMerger)
433 if ok {
434 merger.Merge(Export{}.ProtoMessageV1Of(in.Source))
435 return protoiface.MergeOutput{Flags: protoiface.MergeComplete}
436 }
437
438
439
440 srcv := in.Source.(unwrapper).protoUnwrap()
441 marshaler, ok := srcv.(legacyMarshaler)
442 if !ok {
443 return protoiface.MergeOutput{}
444 }
445 dstv = in.Destination.(unwrapper).protoUnwrap()
446 unmarshaler, ok := dstv.(legacyUnmarshaler)
447 if !ok {
448 return protoiface.MergeOutput{}
449 }
450 if !in.Source.IsValid() {
451
452
453
454
455 return protoiface.MergeOutput{Flags: protoiface.MergeComplete}
456 }
457 b, err := marshaler.Marshal()
458 if err != nil {
459 return protoiface.MergeOutput{}
460 }
461 err = unmarshaler.Unmarshal(b)
462 if err != nil {
463 return protoiface.MergeOutput{}
464 }
465 return protoiface.MergeOutput{Flags: protoiface.MergeComplete}
466 }
467
468
469 type aberrantMessageType struct {
470 t reflect.Type
471 }
472
473 func (mt aberrantMessageType) New() protoreflect.Message {
474 if mt.t.Kind() == reflect.Ptr {
475 return aberrantMessage{reflect.New(mt.t.Elem())}
476 }
477 return aberrantMessage{reflect.Zero(mt.t)}
478 }
479 func (mt aberrantMessageType) Zero() protoreflect.Message {
480 return aberrantMessage{reflect.Zero(mt.t)}
481 }
482 func (mt aberrantMessageType) GoType() reflect.Type {
483 return mt.t
484 }
485 func (mt aberrantMessageType) Descriptor() protoreflect.MessageDescriptor {
486 return LegacyLoadMessageDesc(mt.t)
487 }
488
489
490
491
492
493
494 type aberrantMessage struct {
495 v reflect.Value
496 }
497
498
499 func (m aberrantMessage) Reset() {
500 if mr, ok := m.v.Interface().(interface{ Reset() }); ok {
501 mr.Reset()
502 return
503 }
504 if m.v.Kind() == reflect.Ptr && !m.v.IsNil() {
505 m.v.Elem().Set(reflect.Zero(m.v.Type().Elem()))
506 }
507 }
508
509 func (m aberrantMessage) ProtoReflect() protoreflect.Message {
510 return m
511 }
512
513 func (m aberrantMessage) Descriptor() protoreflect.MessageDescriptor {
514 return LegacyLoadMessageDesc(m.v.Type())
515 }
516 func (m aberrantMessage) Type() protoreflect.MessageType {
517 return aberrantMessageType{m.v.Type()}
518 }
519 func (m aberrantMessage) New() protoreflect.Message {
520 if m.v.Type().Kind() == reflect.Ptr {
521 return aberrantMessage{reflect.New(m.v.Type().Elem())}
522 }
523 return aberrantMessage{reflect.Zero(m.v.Type())}
524 }
525 func (m aberrantMessage) Interface() protoreflect.ProtoMessage {
526 return m
527 }
528 func (m aberrantMessage) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
529 return
530 }
531 func (m aberrantMessage) Has(protoreflect.FieldDescriptor) bool {
532 return false
533 }
534 func (m aberrantMessage) Clear(protoreflect.FieldDescriptor) {
535 panic("invalid Message.Clear on " + string(m.Descriptor().FullName()))
536 }
537 func (m aberrantMessage) Get(fd protoreflect.FieldDescriptor) protoreflect.Value {
538 if fd.Default().IsValid() {
539 return fd.Default()
540 }
541 panic("invalid Message.Get on " + string(m.Descriptor().FullName()))
542 }
543 func (m aberrantMessage) Set(protoreflect.FieldDescriptor, protoreflect.Value) {
544 panic("invalid Message.Set on " + string(m.Descriptor().FullName()))
545 }
546 func (m aberrantMessage) Mutable(protoreflect.FieldDescriptor) protoreflect.Value {
547 panic("invalid Message.Mutable on " + string(m.Descriptor().FullName()))
548 }
549 func (m aberrantMessage) NewField(protoreflect.FieldDescriptor) protoreflect.Value {
550 panic("invalid Message.NewField on " + string(m.Descriptor().FullName()))
551 }
552 func (m aberrantMessage) WhichOneof(protoreflect.OneofDescriptor) protoreflect.FieldDescriptor {
553 panic("invalid Message.WhichOneof descriptor on " + string(m.Descriptor().FullName()))
554 }
555 func (m aberrantMessage) GetUnknown() protoreflect.RawFields {
556 return nil
557 }
558 func (m aberrantMessage) SetUnknown(protoreflect.RawFields) {
559
560 }
561 func (m aberrantMessage) IsValid() bool {
562 if m.v.Kind() == reflect.Ptr {
563 return !m.v.IsNil()
564 }
565 return false
566 }
567 func (m aberrantMessage) ProtoMethods() *protoiface.Methods {
568 return aberrantProtoMethods
569 }
570 func (m aberrantMessage) protoUnwrap() interface{} {
571 return m.v.Interface()
572 }
573
View as plain text