forked from hunter-packages/protobuf
-
Notifications
You must be signed in to change notification settings - Fork 9
/
GPBMessage.m
3395 lines (3139 loc) · 126 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.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#import "GPBMessage_PackagePrivate.h"
#import <objc/runtime.h>
#import <objc/message.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 "GPBUtilities_PackagePrivate.h"
// 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";
//
// 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
// readOnlySemaphore_.
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_;
// Message 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 semaphore.
// NOTE: OSSpinLock may seem like a good fit here but Apple engineers have
// pointed out that they are vulnerable to live locking on iOS in cases of
// priority inversion:
// http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/
// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html
// Use of readOnlySemaphore_ must be prefaced by a call to
// GPBPrepareReadOnlySemaphore to ensure it has been created. This allows
// readOnlySemaphore_ to be only created when actually needed.
_Atomic(dispatch_semaphore_t) readOnlySemaphore_;
}
@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));
#ifdef 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__)
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;
}
// Call this before using the readOnlySemaphore_. This ensures it is created only once.
void GPBPrepareReadOnlySemaphore(GPBMessage *self) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
// Create the semaphore on demand (rather than init) as developers might not cause them
// to be needed, and the heap usage can add up. The atomic swap is used to avoid needing
// another lock around creating it.
if (self->readOnlySemaphore_ == nil) {
dispatch_semaphore_t worker = dispatch_semaphore_create(1);
dispatch_semaphore_t expected = nil;
if (!atomic_compare_exchange_strong(&self->readOnlySemaphore_, &expected, worker)) {
dispatch_release(worker);
}
#if defined(__clang_analyzer__)
// The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked
// (doesn't seem to know about atomic_compare_exchange_strong); so just
// for the analyzer, let it think worker is also released in this case.
else { dispatch_release(worker); }
#endif
}
#pragma clang diagnostic pop
}
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) {
// Use a dummy file that marks it as proto2 syntax so when used generically
// it supports unknowns/etc.
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]));
}
return self;
}
- (instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr {
return [self initWithData:data extensionRegistry:nil error:errorPtr];
}
- (instancetype)initWithData:(NSData *)data
extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr {
if ((self = [self init])) {
@try {
[self mergeFromData:data extensionRegistry:extensionRegistry];
if (errorPtr) {
*errorPtr = nil;
}
}
@catch (NSException *exception) {
[self release];
self = nil;
if (errorPtr) {
*errorPtr = ErrorFromException(exception);
}
}
#ifdef DEBUG
if (self && !self.initialized) {
[self release];
self = nil;
if (errorPtr) {
*errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
}
}
#endif
}
return self;
}
- (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input
extensionRegistry:
(GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr {
if ((self = [self init])) {
@try {
[self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry];
if (errorPtr) {
*errorPtr = nil;
}
}
@catch (NSException *exception) {
[self release];
self = nil;
if (errorPtr) {
*errorPtr = ErrorFromException(exception);
}
}
#ifdef DEBUG
if (self && !self.initialized) {
[self release];
self = nil;
if (errorPtr) {
*errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil);
}
}
#endif
}
return self;
}
- (void)dealloc {
[self internalClear:NO];
NSCAssert(!autocreator_, @"Autocreator was not cleared before dealloc.");
if (readOnlySemaphore_) {
dispatch_release(readOnlySemaphore_);
}
[super dealloc];
}
- (void)copyFieldsInto:(GPBMessage *)message
zone:(NSZone *)zone
descriptor:(GPBDescriptor *)descriptor {
// Copy all the storage...
memcpy(message->messageStorage_, messageStorage_, descriptor->storageSize_);
// Loop over the fields doing fixup...
for (GPBFieldDescriptor *field in descriptor->fields_) {
if (GPBFieldIsMapOrArray(field)) {
id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field);
if (value) {
// We need to copy the array/map, but the catch is for message fields,
// we also need to ensure all the messages as those need copying also.
id newValue;
if (GPBFieldDataTypeIsMessage(field)) {
if (field.fieldType == GPBFieldTypeRepeated) {
NSArray *existingArray = (NSArray *)value;
NSMutableArray *newArray =
[[NSMutableArray alloc] initWithCapacity:existingArray.count];
newValue = newArray;
for (GPBMessage *msg in existingArray) {
GPBMessage *copiedMsg = [msg copyWithZone:zone];
[newArray addObject:copiedMsg];
[copiedMsg release];
}
} else {
if (field.mapKeyDataType == GPBDataTypeString) {
// Map is an NSDictionary.
NSDictionary *existingDict = value;
NSMutableDictionary *newDict = [[NSMutableDictionary alloc]
initWithCapacity:existingDict.count];
newValue = newDict;
[existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key,
GPBMessage *msg,
BOOL *stop) {
#pragma unused(stop)
GPBMessage *copiedMsg = [msg copyWithZone:zone];
[newDict setObject:copiedMsg forKey:key];
[copiedMsg release];
}];
} else {
// Is one of the GPB*ObjectDictionary classes. Type doesn't
// matter, just need one to invoke the selector.
GPBInt32ObjectDictionary *existingDict = value;
newValue = [existingDict deepCopyWithZone:zone];
}
}
} else {