blob: 6100663ec8378587265edf89d0fb344328e7a22e [file] [log] [blame]
Joe Tsaifa02f4e2018-09-12 16:20:37 -07001// 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 (
Joe Tsaic6b75612018-09-13 14:24:37 -07008 "fmt"
Joe Tsaifa02f4e2018-09-12 16:20:37 -07009 "reflect"
10 "strconv"
11 "strings"
Joe Tsaic6b75612018-09-13 14:24:37 -070012 "sync"
Damien Neilc37adef2019-04-01 13:49:56 -070013 "sync/atomic"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070014
Damien Neile89e6242019-05-13 23:55:40 -070015 pref "google.golang.org/protobuf/reflect/protoreflect"
16 piface "google.golang.org/protobuf/runtime/protoiface"
Joe Tsaifa02f4e2018-09-12 16:20:37 -070017)
18
Joe Tsai4fe96632019-05-22 05:12:36 -040019// MessageInfo provides protobuf related functionality for a given Go type
20// that represents a message. A given instance of MessageInfo is tied to
Joe Tsaic6b75612018-09-13 14:24:37 -070021// exactly one Go type, which must be a pointer to a struct type.
Joe Tsai4fe96632019-05-22 05:12:36 -040022type MessageInfo struct {
Damien Neil8012b442019-01-18 09:32:24 -080023 // GoType is the underlying message Go type and must be populated.
Joe Tsaic6b75612018-09-13 14:24:37 -070024 // Once set, this field must never be mutated.
Damien Neil8012b442019-01-18 09:32:24 -080025 GoType reflect.Type // pointer to struct
26
27 // PBType is the underlying message descriptor type and must be populated.
28 // Once set, this field must never be mutated.
29 PBType pref.MessageType
Joe Tsaic6b75612018-09-13 14:24:37 -070030
Joe Tsaic0e4bb22019-07-06 13:05:11 -070031 // Exporter must be provided in a purego environment in order to provide
32 // access to unexported fields.
33 Exporter exporter
34
Joe Tsai09912272019-07-08 10:38:11 -070035 // OneofWrappers is list of pointers to oneof wrapper struct types.
36 OneofWrappers []interface{}
37
Damien Neilc37adef2019-04-01 13:49:56 -070038 initMu sync.Mutex // protects all unexported fields
39 initDone uint32
Joe Tsaic6b75612018-09-13 14:24:37 -070040
Joe Tsai82760ce2019-06-20 03:09:57 -070041 reflectMessageInfo
Joe Tsai378c1322019-04-25 23:48:08 -070042
Damien Neil4ae30bb2019-06-20 10:12:23 -070043 // Information used by the fast-path methods.
Joe Tsai4a539f42019-06-17 12:30:25 -070044 methods piface.Methods
Damien Neil4ae30bb2019-06-20 10:12:23 -070045 coderMessageInfo
Damien Neilc37adef2019-04-01 13:49:56 -070046
Damien Neilc37adef2019-04-01 13:49:56 -070047 extensionFieldInfosMu sync.RWMutex
Joe Tsai89d49632019-06-04 16:20:00 -070048 extensionFieldInfos map[pref.ExtensionType]*extensionFieldInfo
Damien Neilc37adef2019-04-01 13:49:56 -070049}
50
Joe Tsai82760ce2019-06-20 03:09:57 -070051type reflectMessageInfo struct {
52 fields map[pref.FieldNumber]*fieldInfo
53 oneofs map[pref.Name]*oneofInfo
54
55 getUnknown func(pointer) pref.RawFields
56 setUnknown func(pointer, pref.RawFields)
57 extensionMap func(pointer) *extensionMap
58
59 nilMessage atomicNilMessage
60}
61
Joe Tsaic0e4bb22019-07-06 13:05:11 -070062// exporter is a function that returns a reference to the ith field of v,
63// where v is a pointer to a struct. It returns nil if it does not support
64// exporting the requested field (e.g., already exported).
65type exporter func(v interface{}, i int) interface{}
66
Joe Tsai070c1012019-07-26 23:45:58 -070067// getMessageInfo returns the MessageInfo for any message type that
68// is generated by our implementation of protoc-gen-go (for v2 and on).
69// If it is unable to obtain a MessageInfo, it returns nil.
70func getMessageInfo(mt reflect.Type) *MessageInfo {
71 m, ok := reflect.Zero(mt).Interface().(pref.ProtoMessage)
Damien Neilc37adef2019-04-01 13:49:56 -070072 if !ok {
Joe Tsai070c1012019-07-26 23:45:58 -070073 return nil
Damien Neilc37adef2019-04-01 13:49:56 -070074 }
Joe Tsai070c1012019-07-26 23:45:58 -070075 mr, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *MessageInfo })
Damien Neilc37adef2019-04-01 13:49:56 -070076 if !ok {
Joe Tsai070c1012019-07-26 23:45:58 -070077 return nil
Damien Neilc37adef2019-04-01 13:49:56 -070078 }
Joe Tsai070c1012019-07-26 23:45:58 -070079 return mr.ProtoMessageInfo()
Joe Tsaifa02f4e2018-09-12 16:20:37 -070080}
81
Joe Tsai4fe96632019-05-22 05:12:36 -040082func (mi *MessageInfo) init() {
Damien Neilc37adef2019-04-01 13:49:56 -070083 // This function is called in the hot path. Inline the sync.Once
84 // logic, since allocating a closure for Once.Do is expensive.
85 // Keep init small to ensure that it can be inlined.
Joe Tsai82760ce2019-06-20 03:09:57 -070086 if atomic.LoadUint32(&mi.initDone) == 0 {
87 mi.initOnce()
Damien Neilc37adef2019-04-01 13:49:56 -070088 }
Damien Neilc37adef2019-04-01 13:49:56 -070089}
Joe Tsaic6b75612018-09-13 14:24:37 -070090
Joe Tsai4fe96632019-05-22 05:12:36 -040091func (mi *MessageInfo) initOnce() {
Damien Neilc37adef2019-04-01 13:49:56 -070092 mi.initMu.Lock()
93 defer mi.initMu.Unlock()
94 if mi.initDone == 1 {
95 return
96 }
97
98 t := mi.GoType
99 if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct {
100 panic(fmt.Sprintf("got %v, want *struct kind", t))
101 }
102
103 si := mi.makeStructInfo(t.Elem())
104 mi.makeKnownFieldsFunc(si)
Joe Tsai93fd9682019-07-06 13:02:14 -0700105 mi.makeUnknownFieldsFunc(t.Elem(), si)
106 mi.makeExtensionFieldsFunc(t.Elem(), si)
Damien Neil4ae30bb2019-06-20 10:12:23 -0700107 mi.makeMethods(t.Elem(), si)
Damien Neilc37adef2019-04-01 13:49:56 -0700108
109 atomic.StoreUint32(&mi.initDone, 1)
110}
111
Joe Tsai378c1322019-04-25 23:48:08 -0700112type (
113 SizeCache = int32
Joe Tsai3d8e3692019-04-08 13:52:14 -0700114 WeakFields = map[int32]piface.MessageV1
Joe Tsai378c1322019-04-25 23:48:08 -0700115 UnknownFields = []byte
116 ExtensionFields = map[int32]ExtensionField
117)
118
119var (
120 sizecacheType = reflect.TypeOf(SizeCache(0))
Joe Tsai3d8e3692019-04-08 13:52:14 -0700121 weakFieldsType = reflect.TypeOf(WeakFields(nil))
Joe Tsai378c1322019-04-25 23:48:08 -0700122 unknownFieldsType = reflect.TypeOf(UnknownFields(nil))
123 extensionFieldsType = reflect.TypeOf(ExtensionFields(nil))
124)
Damien Neilc37adef2019-04-01 13:49:56 -0700125
Damien Neil3eaddf02019-05-09 11:33:55 -0700126type structInfo struct {
Joe Tsai93fd9682019-07-06 13:02:14 -0700127 sizecacheOffset offset
Joe Tsai3d8e3692019-04-08 13:52:14 -0700128 weakOffset offset
Joe Tsai93fd9682019-07-06 13:02:14 -0700129 unknownOffset offset
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700130 extensionOffset offset
Joe Tsai93fd9682019-07-06 13:02:14 -0700131
Damien Neil3eaddf02019-05-09 11:33:55 -0700132 fieldsByNumber map[pref.FieldNumber]reflect.StructField
133 oneofsByName map[pref.Name]reflect.StructField
134 oneofWrappersByType map[reflect.Type]pref.FieldNumber
135 oneofWrappersByNumber map[pref.FieldNumber]reflect.Type
136}
137
Joe Tsai4fe96632019-05-22 05:12:36 -0400138func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo {
Damien Neil3eaddf02019-05-09 11:33:55 -0700139 si := structInfo{
Joe Tsai93fd9682019-07-06 13:02:14 -0700140 sizecacheOffset: invalidOffset,
Joe Tsai3d8e3692019-04-08 13:52:14 -0700141 weakOffset: invalidOffset,
Joe Tsai93fd9682019-07-06 13:02:14 -0700142 unknownOffset: invalidOffset,
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700143 extensionOffset: invalidOffset,
Joe Tsai93fd9682019-07-06 13:02:14 -0700144
Damien Neil3eaddf02019-05-09 11:33:55 -0700145 fieldsByNumber: map[pref.FieldNumber]reflect.StructField{},
146 oneofsByName: map[pref.Name]reflect.StructField{},
147 oneofWrappersByType: map[reflect.Type]pref.FieldNumber{},
148 oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{},
149 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700150
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700151 if f, _ := t.FieldByName("sizeCache"); f.Type == sizecacheType {
152 si.sizecacheOffset = offsetOf(f, mi.Exporter)
153 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700154 if f, _ := t.FieldByName("XXX_sizecache"); f.Type == sizecacheType {
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700155 si.sizecacheOffset = offsetOf(f, mi.Exporter)
Joe Tsai93fd9682019-07-06 13:02:14 -0700156 }
Joe Tsai3d8e3692019-04-08 13:52:14 -0700157 if f, _ := t.FieldByName("XXX_weak"); f.Type == weakFieldsType {
158 si.weakOffset = offsetOf(f, mi.Exporter)
159 }
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700160 if f, _ := t.FieldByName("unknownFields"); f.Type == unknownFieldsType {
161 si.unknownOffset = offsetOf(f, mi.Exporter)
Joe Tsai93fd9682019-07-06 13:02:14 -0700162 }
163 if f, _ := t.FieldByName("XXX_unrecognized"); f.Type == unknownFieldsType {
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700164 si.unknownOffset = offsetOf(f, mi.Exporter)
165 }
166 if f, _ := t.FieldByName("extensionFields"); f.Type == extensionFieldsType {
167 si.extensionOffset = offsetOf(f, mi.Exporter)
168 }
169 if f, _ := t.FieldByName("XXX_InternalExtensions"); f.Type == extensionFieldsType {
170 si.extensionOffset = offsetOf(f, mi.Exporter)
171 }
172 if f, _ := t.FieldByName("XXX_extensions"); f.Type == extensionFieldsType {
173 si.extensionOffset = offsetOf(f, mi.Exporter)
Joe Tsai93fd9682019-07-06 13:02:14 -0700174 }
175
176 // Generate a mapping of field numbers and names to Go struct field or type.
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700177fieldLoop:
178 for i := 0; i < t.NumField(); i++ {
179 f := t.Field(i)
180 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
181 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
182 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -0700183 si.fieldsByNumber[pref.FieldNumber(n)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700184 continue fieldLoop
185 }
186 }
187 if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 {
Damien Neil3eaddf02019-05-09 11:33:55 -0700188 si.oneofsByName[pref.Name(s)] = f
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700189 continue fieldLoop
190 }
191 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700192
193 // Derive a mapping of oneof wrappers to fields.
Joe Tsai09912272019-07-08 10:38:11 -0700194 oneofWrappers := mi.OneofWrappers
Joe Tsai2c870bb2018-10-17 11:46:52 -0700195 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok {
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800196 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{})
197 }
198 if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok {
199 oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{})
200 }
201 for _, v := range oneofWrappers {
202 tf := reflect.TypeOf(v).Elem()
203 f := tf.Field(0)
204 for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") {
205 if len(s) > 0 && strings.Trim(s, "0123456789") == "" {
206 n, _ := strconv.ParseUint(s, 10, 64)
Damien Neil3eaddf02019-05-09 11:33:55 -0700207 si.oneofWrappersByType[tf] = pref.FieldNumber(n)
208 si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf
Joe Tsaid7e97bc2018-11-26 12:57:27 -0800209 break
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700210 }
211 }
212 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700213
Damien Neil3eaddf02019-05-09 11:33:55 -0700214 return si
215}
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700216
Damien Neil3eaddf02019-05-09 11:33:55 -0700217// makeKnownFieldsFunc generates functions for operations that can be performed
218// on each protobuf message field. It takes in a reflect.Type representing the
219// Go struct and matches message fields with struct fields.
220//
221// This code assumes that the struct is well-formed and panics if there are
222// any discrepancies.
Joe Tsai4fe96632019-05-22 05:12:36 -0400223func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) {
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700224 mi.fields = map[pref.FieldNumber]*fieldInfo{}
Damien Neil92f76182019-08-02 16:58:08 -0700225 md := mi.PBType.Descriptor()
226 for i := 0; i < md.Fields().Len(); i++ {
227 fd := md.Fields().Get(i)
Damien Neil3eaddf02019-05-09 11:33:55 -0700228 fs := si.fieldsByNumber[fd.Number()]
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700229 var fi fieldInfo
230 switch {
Joe Tsaiac31a352019-05-13 14:32:56 -0700231 case fd.ContainingOneof() != nil:
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700232 fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()])
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700233 case fd.IsMap():
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700234 fi = fieldInfoForMap(fd, fs, mi.Exporter)
Joe Tsaiac31a352019-05-13 14:32:56 -0700235 case fd.IsList():
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700236 fi = fieldInfoForList(fd, fs, mi.Exporter)
Joe Tsai3d8e3692019-04-08 13:52:14 -0700237 case fd.IsWeak():
238 fi = fieldInfoForWeakMessage(fd, si.weakOffset)
Joe Tsaic6b75612018-09-13 14:24:37 -0700239 case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind:
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700240 fi = fieldInfoForMessage(fd, fs, mi.Exporter)
Joe Tsaic6b75612018-09-13 14:24:37 -0700241 default:
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700242 fi = fieldInfoForScalar(fd, fs, mi.Exporter)
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700243 }
244 mi.fields[fd.Number()] = &fi
245 }
Joe Tsai4ec39c72019-04-03 13:40:53 -0700246
247 mi.oneofs = map[pref.Name]*oneofInfo{}
Damien Neil92f76182019-08-02 16:58:08 -0700248 for i := 0; i < md.Oneofs().Len(); i++ {
249 od := md.Oneofs().Get(i)
Joe Tsaic0e4bb22019-07-06 13:05:11 -0700250 mi.oneofs[od.Name()] = makeOneofInfo(od, si.oneofsByName[od.Name()], mi.Exporter, si.oneofWrappersByType)
Joe Tsai4ec39c72019-04-03 13:40:53 -0700251 }
Joe Tsaifa02f4e2018-09-12 16:20:37 -0700252}
Joe Tsaic6b75612018-09-13 14:24:37 -0700253
Joe Tsai93fd9682019-07-06 13:02:14 -0700254func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) {
Joe Tsai378c1322019-04-25 23:48:08 -0700255 mi.getUnknown = func(pointer) pref.RawFields { return nil }
256 mi.setUnknown = func(pointer, pref.RawFields) { return }
Joe Tsai93fd9682019-07-06 13:02:14 -0700257 if si.unknownOffset.IsValid() {
Joe Tsai378c1322019-04-25 23:48:08 -0700258 mi.getUnknown = func(p pointer) pref.RawFields {
259 if p.IsNil() {
260 return nil
261 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700262 rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
Joe Tsai378c1322019-04-25 23:48:08 -0700263 return pref.RawFields(*rv.Interface().(*[]byte))
264 }
265 mi.setUnknown = func(p pointer, b pref.RawFields) {
266 if p.IsNil() {
267 panic("invalid SetUnknown on nil Message")
268 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700269 rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType)
Joe Tsai378c1322019-04-25 23:48:08 -0700270 *rv.Interface().(*[]byte) = []byte(b)
271 }
272 } else {
273 mi.getUnknown = func(pointer) pref.RawFields {
274 return nil
275 }
276 mi.setUnknown = func(p pointer, _ pref.RawFields) {
277 if p.IsNil() {
278 panic("invalid SetUnknown on nil Message")
279 }
280 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700281 }
282}
283
Joe Tsai93fd9682019-07-06 13:02:14 -0700284func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) {
285 if si.extensionOffset.IsValid() {
Joe Tsai378c1322019-04-25 23:48:08 -0700286 mi.extensionMap = func(p pointer) *extensionMap {
Joe Tsaid8881392019-06-06 13:01:53 -0700287 if p.IsNil() {
288 return (*extensionMap)(nil)
289 }
Joe Tsai93fd9682019-07-06 13:02:14 -0700290 v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType)
Joe Tsai378c1322019-04-25 23:48:08 -0700291 return (*extensionMap)(v.Interface().(*map[int32]ExtensionField))
292 }
293 } else {
294 mi.extensionMap = func(pointer) *extensionMap {
295 return (*extensionMap)(nil)
296 }
Joe Tsaibe5348c2018-10-23 18:31:18 -0700297 }
298}