message.go

  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
  5package impl
  6
  7import (
  8	"fmt"
  9	"reflect"
 10	"strconv"
 11	"strings"
 12	"sync"
 13	"sync/atomic"
 14
 15	"google.golang.org/protobuf/internal/genid"
 16	"google.golang.org/protobuf/reflect/protoreflect"
 17)
 18
 19// MessageInfo provides protobuf related functionality for a given Go type
 20// that represents a message. A given instance of MessageInfo is tied to
 21// exactly one Go type, which must be a pointer to a struct type.
 22//
 23// The exported fields must be populated before any methods are called
 24// and cannot be mutated after set.
 25type MessageInfo struct {
 26	// GoReflectType is the underlying message Go type and must be populated.
 27	GoReflectType reflect.Type // pointer to struct
 28
 29	// Desc is the underlying message descriptor type and must be populated.
 30	Desc protoreflect.MessageDescriptor
 31
 32	// Deprecated: Exporter will be removed the next time we bump
 33	// protoimpl.GenVersion. See https://github.com/golang/protobuf/issues/1640
 34	Exporter exporter
 35
 36	// OneofWrappers is list of pointers to oneof wrapper struct types.
 37	OneofWrappers []any
 38
 39	initMu   sync.Mutex // protects all unexported fields
 40	initDone uint32
 41
 42	reflectMessageInfo // for reflection implementation
 43	coderMessageInfo   // for fast-path method implementations
 44}
 45
 46// exporter is a function that returns a reference to the ith field of v,
 47// where v is a pointer to a struct. It returns nil if it does not support
 48// exporting the requested field (e.g., already exported).
 49type exporter func(v any, i int) any
 50
 51// getMessageInfo returns the MessageInfo for any message type that
 52// is generated by our implementation of protoc-gen-go (for v2 and on).
 53// If it is unable to obtain a MessageInfo, it returns nil.
 54func getMessageInfo(mt reflect.Type) *MessageInfo {
 55	m, ok := reflect.Zero(mt).Interface().(protoreflect.ProtoMessage)
 56	if !ok {
 57		return nil
 58	}
 59	mr, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *MessageInfo })
 60	if !ok {
 61		return nil
 62	}
 63	return mr.ProtoMessageInfo()
 64}
 65
 66func (mi *MessageInfo) init() {
 67	// This function is called in the hot path. Inline the sync.Once logic,
 68	// since allocating a closure for Once.Do is expensive.
 69	// Keep init small to ensure that it can be inlined.
 70	if atomic.LoadUint32(&mi.initDone) == 0 {
 71		mi.initOnce()
 72	}
 73}
 74
 75func (mi *MessageInfo) initOnce() {
 76	mi.initMu.Lock()
 77	defer mi.initMu.Unlock()
 78	if mi.initDone == 1 {
 79		return
 80	}
 81	if opaqueInitHook(mi) {
 82		return
 83	}
 84
 85	t := mi.GoReflectType
 86	if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
 87		panic(fmt.Sprintf("got %v, want *struct kind", t))
 88	}
 89	t = t.Elem()
 90
 91	si := mi.makeStructInfo(t)
 92	mi.makeReflectFuncs(t, si)
 93	mi.makeCoderMethods(t, si)
 94
 95	atomic.StoreUint32(&mi.initDone, 1)
 96}
 97
 98// getPointer returns the pointer for a message, which should be of
 99// the type of the MessageInfo. If the message is of a different type,
100// it returns ok==false.
101func (mi *MessageInfo) getPointer(m protoreflect.Message) (p pointer, ok bool) {
102	switch m := m.(type) {
103	case *messageState:
104		return m.pointer(), m.messageInfo() == mi
105	case *messageReflectWrapper:
106		return m.pointer(), m.messageInfo() == mi
107	}
108	return pointer{}, false
109}
110
111type (
112	SizeCache       = int32
113	WeakFields      = map[int32]protoreflect.ProtoMessage
114	UnknownFields   = unknownFieldsA // TODO: switch to unknownFieldsB
115	unknownFieldsA  = []byte
116	unknownFieldsB  = *[]byte
117	ExtensionFields = map[int32]ExtensionField
118)
119
120var (
121	sizecacheType       = reflect.TypeOf(SizeCache(0))
122	unknownFieldsAType  = reflect.TypeOf(unknownFieldsA(nil))
123	unknownFieldsBType  = reflect.TypeOf(unknownFieldsB(nil))
124	extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
125)
126
127type structInfo struct {
128	sizecacheOffset offset
129	sizecacheType   reflect.Type
130	unknownOffset   offset
131	unknownType     reflect.Type
132	extensionOffset offset
133	extensionType   reflect.Type
134
135	lazyOffset     offset
136	presenceOffset offset
137
138	fieldsByNumber        map[protoreflect.FieldNumber]reflect.StructField
139	oneofsByName          map[protoreflect.Name]reflect.StructField
140	oneofWrappersByType   map[reflect.Type]protoreflect.FieldNumber
141	oneofWrappersByNumber map[protoreflect.FieldNumber]reflect.Type
142}
143
144func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
145	si := structInfo{
146		sizecacheOffset: invalidOffset,
147		unknownOffset:   invalidOffset,
148		extensionOffset: invalidOffset,
149		lazyOffset:      invalidOffset,
150		presenceOffset:  invalidOffset,
151
152		fieldsByNumber:        map[protoreflect.FieldNumber]reflect.StructField{},
153		oneofsByName:          map[protoreflect.Name]reflect.StructField{},
154		oneofWrappersByType:   map[reflect.Type]protoreflect.FieldNumber{},
155		oneofWrappersByNumber: map[protoreflect.FieldNumber]reflect.Type{},
156	}
157
158fieldLoop:
159	for i := 0; i < t.NumField(); i++ {
160		switch f := t.Field(i); f.Name {
161		case genid.SizeCache_goname, genid.SizeCacheA_goname:
162			if f.Type == sizecacheType {
163				si.sizecacheOffset = offsetOf(f)
164				si.sizecacheType = f.Type
165			}
166		case genid.UnknownFields_goname, genid.UnknownFieldsA_goname:
167			if f.Type == unknownFieldsAType || f.Type == unknownFieldsBType {
168				si.unknownOffset = offsetOf(f)
169				si.unknownType = f.Type
170			}
171		case genid.ExtensionFields_goname, genid.ExtensionFieldsA_goname, genid.ExtensionFieldsB_goname:
172			if f.Type == extensionFieldsType {
173				si.extensionOffset = offsetOf(f)
174				si.extensionType = f.Type
175			}
176		case "lazyFields", "XXX_lazyUnmarshalInfo":
177			si.lazyOffset = offsetOf(f)
178		case "XXX_presence":
179			si.presenceOffset = offsetOf(f)
180		default:
181			for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
182				if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
183					n, _ := strconv.ParseUint(s, 10, 64)
184					si.fieldsByNumber[protoreflect.FieldNumber(n)] = f
185					continue fieldLoop
186				}
187			}
188			if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
189				si.oneofsByName[protoreflect.Name(s)] = f
190				continue fieldLoop
191			}
192		}
193	}
194
195	// Derive a mapping of oneof wrappers to fields.
196	oneofWrappers := mi.OneofWrappers
197	methods := make([]reflect.Method, 0, 2)
198	if m, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
199		methods = append(methods, m)
200	}
201	if m, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
202		methods = append(methods, m)
203	}
204	for _, fn := range methods {
205		for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) {
206			if vs, ok := v.Interface().([]any); ok {
207				oneofWrappers = vs
208			}
209		}
210	}
211	for _, v := range oneofWrappers {
212		tf := reflect.TypeOf(v).Elem()
213		f := tf.Field(0)
214		for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
215			if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
216				n, _ := strconv.ParseUint(s, 10, 64)
217				si.oneofWrappersByType[tf] = protoreflect.FieldNumber(n)
218				si.oneofWrappersByNumber[protoreflect.FieldNumber(n)] = tf
219				break
220			}
221		}
222	}
223
224	return si
225}
226
227func (mi *MessageInfo) New() protoreflect.Message {
228	m := reflect.New(mi.GoReflectType.Elem()).Interface()
229	if r, ok := m.(protoreflect.ProtoMessage); ok {
230		return r.ProtoReflect()
231	}
232	return mi.MessageOf(m)
233}
234func (mi *MessageInfo) Zero() protoreflect.Message {
235	return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface())
236}
237func (mi *MessageInfo) Descriptor() protoreflect.MessageDescriptor {
238	return mi.Desc
239}
240func (mi *MessageInfo) Enum(i int) protoreflect.EnumType {
241	mi.init()
242	fd := mi.Desc.Fields().Get(i)
243	return Export{}.EnumTypeOf(mi.fieldTypes[fd.Number()])
244}
245func (mi *MessageInfo) Message(i int) protoreflect.MessageType {
246	mi.init()
247	fd := mi.Desc.Fields().Get(i)
248	switch {
249	case fd.IsMap():
250		return mapEntryType{fd.Message(), mi.fieldTypes[fd.Number()]}
251	default:
252		return Export{}.MessageTypeOf(mi.fieldTypes[fd.Number()])
253	}
254}
255
256type mapEntryType struct {
257	desc    protoreflect.MessageDescriptor
258	valType any // zero value of enum or message type
259}
260
261func (mt mapEntryType) New() protoreflect.Message {
262	return nil
263}
264func (mt mapEntryType) Zero() protoreflect.Message {
265	return nil
266}
267func (mt mapEntryType) Descriptor() protoreflect.MessageDescriptor {
268	return mt.desc
269}
270func (mt mapEntryType) Enum(i int) protoreflect.EnumType {
271	fd := mt.desc.Fields().Get(i)
272	if fd.Enum() == nil {
273		return nil
274	}
275	return Export{}.EnumTypeOf(mt.valType)
276}
277func (mt mapEntryType) Message(i int) protoreflect.MessageType {
278	fd := mt.desc.Fields().Get(i)
279	if fd.Message() == nil {
280		return nil
281	}
282	return Export{}.MessageTypeOf(mt.valType)
283}