forked from protocolbuffers/protobuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GPBMessage.m
3652 lines (3370 loc) · 139 KB
/
GPBMessage.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#import <Foundation/Foundation.h>
#import "GPBMessage_PackagePrivate.h"
#import <objc/message.h>
#import <objc/runtime.h>
#import <os/lock.h>
#import <stdatomic.h>
#import "GPBArray_PackagePrivate.h"
#import "GPBCodedInputStream_PackagePrivate.h"
#import "GPBCodedOutputStream_PackagePrivate.h"
#import "GPBDescriptor_PackagePrivate.h"
#import "GPBDictionary_PackagePrivate.h"
#import "GPBExtensionInternals.h"
#import "GPBExtensionRegistry.h"
#import "GPBRootObject_PackagePrivate.h"
#import "GPBUnknownFieldSet_PackagePrivate.h"
#import "GPBUnknownFields_PackagePrivate.h"
#import "GPBUtilities_PackagePrivate.h"
// Returns a new instance that was automatically created by |autocreator| for
// its field |field|.
static GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator,
GPBFieldDescriptor *field)
__attribute__((ns_returns_retained));
// Direct access is use for speed, to avoid even internally declaring things
// read/write, etc. The warning is enabled in the project to ensure code calling
// protos can turn on -Wdirect-ivar-access without issues.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
NSString *const GPBMessageErrorDomain = GPBNSStringifySymbol(GPBMessageErrorDomain);
NSString *const GPBErrorReasonKey = @"Reason";
static NSString *const kGPBDataCoderKey = @"GPBData";
// Length-delimited has a max size of 2GB, and thus messages do also.
// src/google/protobuf/message_lite also does this enforcement on the C++ side. Validation for
// parsing is done with GPBCodedInputStream; but for messages, it is less checks to do it within
// the message side since the input stream code calls these same bottlenecks.
// https://protobuf.dev/programming-guides/encoding/#cheat-sheet
static const size_t kMaximumMessageSize = 0x7fffffff;
NSString *const GPBMessageExceptionMessageTooLarge =
GPBNSStringifySymbol(GPBMessageExceptionMessageTooLarge);
//
// PLEASE REMEMBER:
//
// This is the base class for *all* messages generated, so any selector defined,
// *public* or *private* could end up colliding with a proto message field. So
// avoid using selectors that could match a property, use C functions to hide
// them, etc.
//
@interface GPBMessage () {
@package
GPBUnknownFieldSet *unknownFields_;
NSMutableDictionary *extensionMap_;
// Readonly access to autocreatedExtensionMap_ is protected via readOnlyLock_.
NSMutableDictionary *autocreatedExtensionMap_;
// If the object was autocreated, we remember the creator so that if we get
// mutated, we can inform the creator to make our field visible.
GPBMessage *autocreator_;
GPBFieldDescriptor *autocreatorField_;
GPBExtensionDescriptor *autocreatorExtension_;
// Messages can only be mutated from one thread. But some *readonly* operations modify internal
// state because they autocreate things. The autocreatedExtensionMap_ is one such structure.
// Access during readonly operations is protected via this lock.
//
// Long ago, this was an OSSpinLock, but then it came to light that there were issues for that on
// iOS:
// http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
// It was changed to a dispatch_semaphore_t, but that has potential for priority inversion issues.
// The minOS versions are now high enough that os_unfair_lock can be used, and should provide
// all the support we need. For more information in the concurrency/locking space see:
// https://gist.github.com/tclementdev/6af616354912b0347cdf6db159c37057
// https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html
// https://developer.apple.com/videos/play/wwdc2017/706/
os_unfair_lock readOnlyLock_;
}
@end
static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator)
__attribute__((ns_returns_retained));
static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator)
__attribute__((ns_returns_retained));
static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field);
static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone)
__attribute__((ns_returns_retained));
static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self);
#if defined(DEBUG) && DEBUG
static NSError *MessageError(NSInteger code, NSDictionary *userInfo) {
return [NSError errorWithDomain:GPBMessageErrorDomain code:code userInfo:userInfo];
}
#endif
static NSError *ErrorFromException(NSException *exception) {
NSError *error = nil;
if ([exception.name isEqual:GPBCodedInputStreamException]) {
NSDictionary *exceptionInfo = exception.userInfo;
error = exceptionInfo[GPBCodedInputStreamUnderlyingErrorKey];
}
if (!error) {
NSString *reason = exception.reason;
NSDictionary *userInfo = nil;
if ([reason length]) {
userInfo = @{GPBErrorReasonKey : reason};
}
error = [NSError errorWithDomain:GPBMessageErrorDomain
code:GPBMessageErrorCodeOther
userInfo:userInfo];
}
return error;
}
static void CheckExtension(GPBMessage *self, GPBExtensionDescriptor *extension) {
if (![self isKindOfClass:extension.containingMessageClass]) {
[NSException raise:NSInvalidArgumentException
format:@"Extension %@ used on wrong class (%@ instead of %@)",
extension.singletonName, [self class], extension.containingMessageClass];
}
}
static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) {
if (extensionMap.count == 0) {
return nil;
}
NSMutableDictionary *result =
[[NSMutableDictionary allocWithZone:zone] initWithCapacity:extensionMap.count];
for (GPBExtensionDescriptor *extension in extensionMap) {
id value = [extensionMap objectForKey:extension];
BOOL isMessageExtension = GPBExtensionIsMessage(extension);
if (extension.repeated) {
if (isMessageExtension) {
NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:[value count]];
for (GPBMessage *listValue in value) {
GPBMessage *copiedValue = [listValue copyWithZone:zone];
[list addObject:copiedValue];
[copiedValue release];
}
[result setObject:list forKey:extension];
[list release];
} else {
NSMutableArray *copiedValue = [value mutableCopyWithZone:zone];
[result setObject:copiedValue forKey:extension];
[copiedValue release];
}
} else {
if (isMessageExtension) {
GPBMessage *copiedValue = [value copyWithZone:zone];
[result setObject:copiedValue forKey:extension];
[copiedValue release];
} else {
[result setObject:value forKey:extension];
}
}
}
return result;
}
static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) {
id result;
GPBDataType fieldDataType = GPBGetFieldDataType(field);
switch (fieldDataType) {
case GPBDataTypeBool:
result = [[GPBBoolArray alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBUInt32Array alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBInt32Array alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBUInt64Array alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBInt64Array alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBFloatArray alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBDoubleArray alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBEnumArray alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeGroup:
case GPBDataTypeMessage:
case GPBDataTypeString:
if (autocreator) {
result = [[GPBAutocreatedArray alloc] init];
} else {
result = [[NSMutableArray alloc] init];
}
break;
}
if (autocreator) {
if (GPBDataTypeIsObject(fieldDataType)) {
GPBAutocreatedArray *autoArray = result;
autoArray->_autocreator = autocreator;
} else {
GPBInt32Array *gpbArray = result;
gpbArray->_autocreator = autocreator;
}
}
return result;
}
static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) {
id result;
GPBDataType keyDataType = field.mapKeyDataType;
GPBDataType valueDataType = GPBGetFieldDataType(field);
switch (keyDataType) {
case GPBDataTypeBool:
switch (valueDataType) {
case GPBDataTypeBool:
result = [[GPBBoolBoolDictionary alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBBoolUInt32Dictionary alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBBoolInt32Dictionary alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBBoolUInt64Dictionary alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBBoolInt64Dictionary alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBBoolFloatDictionary alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBBoolDoubleDictionary alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBBoolEnumDictionary alloc]
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeMessage:
case GPBDataTypeString:
result = [[GPBBoolObjectDictionary alloc] init];
break;
case GPBDataTypeGroup:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
switch (valueDataType) {
case GPBDataTypeBool:
result = [[GPBUInt32BoolDictionary alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBUInt32UInt32Dictionary alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBUInt32Int32Dictionary alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBUInt32UInt64Dictionary alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBUInt32Int64Dictionary alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBUInt32FloatDictionary alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBUInt32DoubleDictionary alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBUInt32EnumDictionary alloc]
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeMessage:
case GPBDataTypeString:
result = [[GPBUInt32ObjectDictionary alloc] init];
break;
case GPBDataTypeGroup:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
switch (valueDataType) {
case GPBDataTypeBool:
result = [[GPBInt32BoolDictionary alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBInt32UInt32Dictionary alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBInt32Int32Dictionary alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBInt32UInt64Dictionary alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBInt32Int64Dictionary alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBInt32FloatDictionary alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBInt32DoubleDictionary alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBInt32EnumDictionary alloc]
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeMessage:
case GPBDataTypeString:
result = [[GPBInt32ObjectDictionary alloc] init];
break;
case GPBDataTypeGroup:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
switch (valueDataType) {
case GPBDataTypeBool:
result = [[GPBUInt64BoolDictionary alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBUInt64UInt32Dictionary alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBUInt64Int32Dictionary alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBUInt64UInt64Dictionary alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBUInt64Int64Dictionary alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBUInt64FloatDictionary alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBUInt64DoubleDictionary alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBUInt64EnumDictionary alloc]
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeMessage:
case GPBDataTypeString:
result = [[GPBUInt64ObjectDictionary alloc] init];
break;
case GPBDataTypeGroup:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
switch (valueDataType) {
case GPBDataTypeBool:
result = [[GPBInt64BoolDictionary alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBInt64UInt32Dictionary alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBInt64Int32Dictionary alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBInt64UInt64Dictionary alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBInt64Int64Dictionary alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBInt64FloatDictionary alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBInt64DoubleDictionary alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBInt64EnumDictionary alloc]
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeMessage:
case GPBDataTypeString:
result = [[GPBInt64ObjectDictionary alloc] init];
break;
case GPBDataTypeGroup:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
break;
case GPBDataTypeString:
switch (valueDataType) {
case GPBDataTypeBool:
result = [[GPBStringBoolDictionary alloc] init];
break;
case GPBDataTypeFixed32:
case GPBDataTypeUInt32:
result = [[GPBStringUInt32Dictionary alloc] init];
break;
case GPBDataTypeInt32:
case GPBDataTypeSFixed32:
case GPBDataTypeSInt32:
result = [[GPBStringInt32Dictionary alloc] init];
break;
case GPBDataTypeFixed64:
case GPBDataTypeUInt64:
result = [[GPBStringUInt64Dictionary alloc] init];
break;
case GPBDataTypeInt64:
case GPBDataTypeSFixed64:
case GPBDataTypeSInt64:
result = [[GPBStringInt64Dictionary alloc] init];
break;
case GPBDataTypeFloat:
result = [[GPBStringFloatDictionary alloc] init];
break;
case GPBDataTypeDouble:
result = [[GPBStringDoubleDictionary alloc] init];
break;
case GPBDataTypeEnum:
result = [[GPBStringEnumDictionary alloc]
initWithValidationFunction:field.enumDescriptor.enumVerifier];
break;
case GPBDataTypeBytes:
case GPBDataTypeMessage:
case GPBDataTypeString:
if (autocreator) {
result = [[GPBAutocreatedDictionary alloc] init];
} else {
result = [[NSMutableDictionary alloc] init];
}
break;
case GPBDataTypeGroup:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
break;
case GPBDataTypeFloat:
case GPBDataTypeDouble:
case GPBDataTypeEnum:
case GPBDataTypeBytes:
case GPBDataTypeGroup:
case GPBDataTypeMessage:
NSCAssert(NO, @"shouldn't happen");
return nil;
}
if (autocreator) {
if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) {
GPBAutocreatedDictionary *autoDict = result;
autoDict->_autocreator = autocreator;
} else {
GPBInt32Int32Dictionary *gpbDict = result;
gpbDict->_autocreator = autocreator;
}
}
return result;
}
#if !defined(__clang_analyzer__)
// These functions are blocked from the analyzer because the analyzer sees the
// GPBSetRetainedObjectIvarWithFieldPrivate() call as consuming the array/map,
// so use of the array/map after the call returns is flagged as a use after
// free.
// But GPBSetRetainedObjectIvarWithFieldPrivate() is "consuming" the retain
// count be holding onto the object (it is transferring it), the object is
// still valid after returning from the call. The other way to avoid this
// would be to add a -retain/-autorelease, but that would force every
// repeated/map field parsed into the autorelease pool which is both a memory
// and performance hit.
static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (!array) {
// No lock needed, this is called from places expecting to mutate
// so no threading protection is needed.
array = CreateArrayForField(field, nil);
GPBSetRetainedObjectIvarWithFieldPrivate(self, field, array);
}
return array;
}
// This is like GPBGetObjectIvarWithField(), but for arrays, it should
// only be used to wire the method into the class.
static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
_Atomic(id) *typePtr = (_Atomic(id) *)&storage[field->description_->offset];
id array = atomic_load(typePtr);
if (array) {
return array;
}
id expected = nil;
id autocreated = CreateArrayForField(field, self);
if (atomic_compare_exchange_strong(typePtr, &expected, autocreated)) {
// Value was set, return it.
return autocreated;
}
// Some other thread set it, release the one created and return what got set.
if (GPBFieldDataTypeIsObject(field)) {
GPBAutocreatedArray *autoArray = autocreated;
autoArray->_autocreator = nil;
} else {
GPBInt32Array *gpbArray = autocreated;
gpbArray->_autocreator = nil;
}
[autocreated release];
return expected;
}
static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (!dict) {
// No lock needed, this is called from places expecting to mutate
// so no threading protection is needed.
dict = CreateMapForField(field, nil);
GPBSetRetainedObjectIvarWithFieldPrivate(self, field, dict);
}
return dict;
}
// This is like GPBGetObjectIvarWithField(), but for maps, it should
// only be used to wire the method into the class.
static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) {
uint8_t *storage = (uint8_t *)self->messageStorage_;
_Atomic(id) *typePtr = (_Atomic(id) *)&storage[field->description_->offset];
id dict = atomic_load(typePtr);
if (dict) {
return dict;
}
id expected = nil;
id autocreated = CreateMapForField(field, self);
if (atomic_compare_exchange_strong(typePtr, &expected, autocreated)) {
// Value was set, return it.
return autocreated;
}
// Some other thread set it, release the one created and return what got set.
if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
GPBAutocreatedDictionary *autoDict = autocreated;
autoDict->_autocreator = nil;
} else {
GPBInt32Int32Dictionary *gpbDict = autocreated;
gpbDict->_autocreator = nil;
}
[autocreated release];
return expected;
}
#endif // !defined(__clang_analyzer__)
static void DecodeSingleValueFromInputStream(GPBExtensionDescriptor *extension,
GPBMessage *messageToGetExtension,
GPBCodedInputStream *input,
id<GPBExtensionRegistry> extensionRegistry,
BOOL isRepeated, GPBMessage *targetMessage) {
GPBExtensionDescription *description = extension->description_;
#if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
if (GPBDataTypeIsMessage(description->dataType)) {
NSCAssert(targetMessage != nil, @"Internal error: must have a target message");
} else {
NSCAssert(targetMessage == nil, @"Internal error: should not have a target message");
}
#endif
GPBCodedInputStreamState *state = &input->state_;
id nsValue;
switch (description->dataType) {
case GPBDataTypeBool: {
BOOL value = GPBCodedInputStreamReadBool(state);
nsValue = [[NSNumber alloc] initWithBool:value];
break;
}
case GPBDataTypeFixed32: {
uint32_t value = GPBCodedInputStreamReadFixed32(state);
nsValue = [[NSNumber alloc] initWithUnsignedInt:value];
break;
}
case GPBDataTypeSFixed32: {
int32_t value = GPBCodedInputStreamReadSFixed32(state);
nsValue = [[NSNumber alloc] initWithInt:value];
break;
}
case GPBDataTypeFloat: {
float value = GPBCodedInputStreamReadFloat(state);
nsValue = [[NSNumber alloc] initWithFloat:value];
break;
}
case GPBDataTypeFixed64: {
uint64_t value = GPBCodedInputStreamReadFixed64(state);
nsValue = [[NSNumber alloc] initWithUnsignedLongLong:value];
break;
}
case GPBDataTypeSFixed64: {
int64_t value = GPBCodedInputStreamReadSFixed64(state);
nsValue = [[NSNumber alloc] initWithLongLong:value];
break;
}
case GPBDataTypeDouble: {
double value = GPBCodedInputStreamReadDouble(state);
nsValue = [[NSNumber alloc] initWithDouble:value];
break;
}
case GPBDataTypeInt32: {
int32_t value = GPBCodedInputStreamReadInt32(state);
nsValue = [[NSNumber alloc] initWithInt:value];
break;
}
case GPBDataTypeInt64: {
int64_t value = GPBCodedInputStreamReadInt64(state);
nsValue = [[NSNumber alloc] initWithLongLong:value];
break;
}
case GPBDataTypeSInt32: {
int32_t value = GPBCodedInputStreamReadSInt32(state);
nsValue = [[NSNumber alloc] initWithInt:value];
break;
}
case GPBDataTypeSInt64: {
int64_t value = GPBCodedInputStreamReadSInt64(state);
nsValue = [[NSNumber alloc] initWithLongLong:value];
break;
}
case GPBDataTypeUInt32: {
uint32_t value = GPBCodedInputStreamReadUInt32(state);
nsValue = [[NSNumber alloc] initWithUnsignedInt:value];
break;
}
case GPBDataTypeUInt64: {
uint64_t value = GPBCodedInputStreamReadUInt64(state);
nsValue = [[NSNumber alloc] initWithUnsignedLongLong:value];
break;
}
case GPBDataTypeBytes:
nsValue = GPBCodedInputStreamReadRetainedBytes(state);
break;
case GPBDataTypeString:
nsValue = GPBCodedInputStreamReadRetainedString(state);
break;
case GPBDataTypeEnum: {
int32_t val = GPBCodedInputStreamReadEnum(&input->state_);
GPBEnumDescriptor *enumDescriptor = extension.enumDescriptor;
// If run with source generated before the closed enum support, all enums
// will be considers not closed, so casing to the enum type for a switch
// could cause things to fall off the end of a switch.
if (!enumDescriptor.isClosed || enumDescriptor.enumVerifier(val)) {
nsValue = [[NSNumber alloc] initWithInt:val];
} else {
GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(messageToGetExtension);
[unknownFields mergeVarintField:extension->description_->fieldNumber value:val];
nsValue = nil;
}
break;
}
case GPBDataTypeGroup:
case GPBDataTypeMessage: {
if (description->dataType == GPBDataTypeGroup) {
[input readGroup:description->fieldNumber
message:targetMessage
extensionRegistry:extensionRegistry];
} else {
// description->dataType == GPBDataTypeMessage
if (GPBExtensionIsWireFormat(description)) {
// For MessageSet fields the message length will have already been
// read.
[targetMessage mergeFromCodedInputStream:input
extensionRegistry:extensionRegistry
endingTag:0];
} else {
[input readMessage:targetMessage extensionRegistry:extensionRegistry];
}
}
// Nothing to add below since the caller provided the message (and added it).
nsValue = nil;
break;
}
} // switch
if (nsValue) {
if (isRepeated) {
[messageToGetExtension addExtension:extension value:nsValue];
} else {
[messageToGetExtension setExtension:extension value:nsValue];
}
[nsValue release];
}
}
static void ExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream,
GPBCodedInputStream *input,
id<GPBExtensionRegistry> extensionRegistry,
GPBMessage *message) {
GPBExtensionDescription *description = extension->description_;
GPBCodedInputStreamState *state = &input->state_;
if (isPackedOnStream) {
#if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
NSCAssert(GPBExtensionIsRepeated(description), @"How was it packed if it isn't repeated?");
#endif
int32_t length = GPBCodedInputStreamReadInt32(state);
size_t limit = GPBCodedInputStreamPushLimit(state, length);
while (GPBCodedInputStreamBytesUntilLimit(state) > 0) {
DecodeSingleValueFromInputStream(extension, message, input, extensionRegistry,
/*isRepeated=*/YES, nil);
}
GPBCodedInputStreamPopLimit(state, limit);
} else {
BOOL isRepeated = GPBExtensionIsRepeated(description);
GPBMessage *targetMessage = nil;
if (GPBDataTypeIsMessage(description->dataType)) {
// For messages/groups create the targetMessage out here and add it to the objects graph in
// advance, that way if DecodeSingleValueFromInputStream() throw for a parsing issue, the
// object won't be leaked.
if (isRepeated) {
GPBDescriptor *descriptor = [extension.msgClass descriptor];
targetMessage = [[descriptor.messageClass alloc] init];
[message addExtension:extension value:targetMessage];
[targetMessage release];
} else {
targetMessage = [message getExistingExtension:extension];
if (!targetMessage) {
GPBDescriptor *descriptor = [extension.msgClass descriptor];
targetMessage = [[descriptor.messageClass alloc] init];
[message setExtension:extension value:targetMessage];
[targetMessage release];
}
}
}
DecodeSingleValueFromInputStream(extension, message, input, extensionRegistry, isRepeated,
targetMessage);
}
}
static GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator,
GPBFieldDescriptor *field) {
GPBMessage *message = [[msgClass alloc] init];
message->autocreator_ = autocreator;
message->autocreatorField_ = [field retain];
return message;
}
static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator,
GPBExtensionDescriptor *extension)
__attribute__((ns_returns_retained));
static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator,
GPBExtensionDescriptor *extension) {
GPBMessage *message = [[msgClass alloc] init];
message->autocreator_ = autocreator;
message->autocreatorExtension_ = [extension retain];
return message;
}
BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent) {
return (message->autocreator_ == parent);
}
void GPBBecomeVisibleToAutocreator(GPBMessage *self) {
// Message objects that are implicitly created by accessing a message field
// are initially not visible via the hasX selector. This method makes them
// visible.
if (self->autocreator_) {
// This will recursively make all parent messages visible until it reaches a
// super-creator that's visible.
if (self->autocreatorField_) {
GPBSetObjectIvarWithFieldPrivate(self->autocreator_, self->autocreatorField_, self);
} else {
[self->autocreator_ setExtension:self->autocreatorExtension_ value:self];
}
}
}
void GPBAutocreatedArrayModified(GPBMessage *self, id array) {
// When one of our autocreated arrays adds elements, make it visible.
GPBDescriptor *descriptor = [[self class] descriptor];
for (GPBFieldDescriptor *field in descriptor->fields_) {
if (field.fieldType == GPBFieldTypeRepeated) {
id curArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (curArray == array) {
if (GPBFieldDataTypeIsObject(field)) {
GPBAutocreatedArray *autoArray = array;
autoArray->_autocreator = nil;
} else {
GPBInt32Array *gpbArray = array;
gpbArray->_autocreator = nil;
}
GPBBecomeVisibleToAutocreator(self);
return;
}
}
}
NSCAssert(NO, @"Unknown autocreated %@ for %@.", [array class], self);
}
void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) {
// When one of our autocreated dicts adds elements, make it visible.
GPBDescriptor *descriptor = [[self class] descriptor];
for (GPBFieldDescriptor *field in descriptor->fields_) {
if (field.fieldType == GPBFieldTypeMap) {
id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (curDict == dictionary) {
if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) {
GPBAutocreatedDictionary *autoDict = dictionary;
autoDict->_autocreator = nil;
} else {
GPBInt32Int32Dictionary *gpbDict = dictionary;
gpbDict->_autocreator = nil;
}
GPBBecomeVisibleToAutocreator(self);
return;
}
}
}
NSCAssert(NO, @"Unknown autocreated %@ for %@.", [dictionary class], self);
}
void GPBClearMessageAutocreator(GPBMessage *self) {
if ((self == nil) || !self->autocreator_) {
return;
}
#if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
// Either the autocreator must have its "has" flag set to YES, or it must be
// NO and not equal to ourselves.
BOOL autocreatorHas =
(self->autocreatorField_ ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_)
: [self->autocreator_ hasExtension:self->autocreatorExtension_]);
GPBMessage *autocreatorFieldValue =
(self->autocreatorField_
? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, self->autocreatorField_)
: [self->autocreator_->autocreatedExtensionMap_
objectForKey:self->autocreatorExtension_]);
NSCAssert(autocreatorHas || autocreatorFieldValue != self,
@"Cannot clear autocreator because it still refers to self, self: %@.", self);
#endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS)
self->autocreator_ = nil;
[self->autocreatorField_ release];
self->autocreatorField_ = nil;
[self->autocreatorExtension_ release];
self->autocreatorExtension_ = nil;
}
static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) {
if (!self->unknownFields_) {
self->unknownFields_ = [[GPBUnknownFieldSet alloc] init];
GPBBecomeVisibleToAutocreator(self);
}
return self->unknownFields_;
}
@implementation GPBMessage
+ (void)initialize {
Class pbMessageClass = [GPBMessage class];
if ([self class] == pbMessageClass) {
// This is here to start up the "base" class descriptor.
[self descriptor];
// Message shares extension method resolving with GPBRootObject so insure
// it is started up at the same time.
(void)[GPBRootObject class];
} else if ([self superclass] == pbMessageClass) {
// This is here to start up all the "message" subclasses. Just needs to be
// done for the messages, not any of the subclasses.
// This must be done in initialize to enforce thread safety of start up of
// the protocol buffer library.
// Note: The generated code for -descriptor calls
// +[GPBDescriptor allocDescriptorForClass:...], passing the GPBRootObject
// subclass for the file. That call chain is what ensures that *Root class
// is started up to support extension resolution off the message class
// (+resolveClassMethod: below) in a thread safe manner.
[self descriptor];
}
}
+ (instancetype)allocWithZone:(NSZone *)zone {
// Override alloc to allocate our classes with the additional storage
// required for the instance variables.
GPBDescriptor *descriptor = [self descriptor];
return NSAllocateObject(self, descriptor->storageSize_, zone);
}
+ (instancetype)alloc {
return [self allocWithZone:nil];
}
+ (GPBDescriptor *)descriptor {
// This is thread safe because it is called from +initialize.
static GPBDescriptor *descriptor = NULL;
static GPBFileDescriptor *fileDescriptor = NULL;
if (!descriptor) {
fileDescriptor = [[GPBFileDescriptor alloc] initWithPackage:@"internal"
syntax:GPBFileSyntaxProto2];
descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class]
rootClass:Nil
file:fileDescriptor
fields:NULL
fieldCount:0
storageSize:0
flags:0];
}
return descriptor;
}
+ (instancetype)message {
return [[[self alloc] init] autorelease];
}
- (instancetype)init {
if ((self = [super init])) {
messageStorage_ =
(GPBMessage_StoragePtr)(((uint8_t *)self) + class_getInstanceSize([self class]));
readOnlyLock_ = OS_UNFAIR_LOCK_INIT;
}
return self;