-
Notifications
You must be signed in to change notification settings - Fork 15.6k
/
Copy pathmessage.cc
3124 lines (2830 loc) · 105 KB
/
message.cc
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.
// Author: anuraag@google.com (Anuraag Agrawal)
// Author: tibell@google.com (Johan Tibell)
#include <google/protobuf/pyext/message.h>
#include <structmember.h> // A Python header file.
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <google/protobuf/stubs/strutil.h>
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
#endif
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/extension_dict.h>
#include <google/protobuf/pyext/field.h>
#include <google/protobuf/pyext/map_container.h>
#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/repeated_composite_container.h>
#include <google/protobuf/pyext/repeated_scalar_container.h>
#include <google/protobuf/pyext/safe_numerics.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#include <google/protobuf/pyext/unknown_fields.h>
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/io/strtod.h>
#include <google/protobuf/stubs/map_util.h>
// clang-format off
#include <google/protobuf/port_def.inc>
// clang-format on
#if PY_MAJOR_VERSION >= 3
#define PyInt_AsLong PyLong_AsLong
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyString_Check PyUnicode_Check
#define PyString_FromString PyUnicode_FromString
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
#define PyString_FromFormat PyUnicode_FromFormat
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#else
#define PyString_AsString(ob) \
(PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AsString(ob))
#define PyString_AsStringAndSize(ob, charpp, sizep) \
(PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \
PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \
? -1 \
: 0) \
: PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
#endif
#endif
namespace google {
namespace protobuf {
namespace python {
class MessageReflectionFriend {
public:
static void UnsafeShallowSwapFields(
Message* lhs, Message* rhs,
const std::vector<const FieldDescriptor*>& fields) {
lhs->GetReflection()->UnsafeShallowSwapFields(lhs, rhs, fields);
}
};
static PyObject* kDESCRIPTOR;
PyObject* EnumTypeWrapper_class;
static PyObject* PythonMessage_class;
static PyObject* kEmptyWeakref;
static PyObject* WKT_classes = NULL;
namespace message_meta {
static int InsertEmptyWeakref(PyTypeObject* base);
namespace {
// Copied over from internal 'google/protobuf/stubs/strutil.h'.
inline void LowerString(std::string* s) {
std::string::iterator end = s->end();
for (std::string::iterator i = s->begin(); i != end; ++i) {
// tolower() changes based on locale. We don't want this!
if ('A' <= *i && *i <= 'Z') *i += 'a' - 'A';
}
}
} // namespace
// Finalize the creation of the Message class.
static int AddDescriptors(PyObject* cls, const Descriptor* descriptor) {
// For each field set: cls.<field>_FIELD_NUMBER = <number>
for (int i = 0; i < descriptor->field_count(); ++i) {
const FieldDescriptor* field_descriptor = descriptor->field(i);
ScopedPyObjectPtr property(NewFieldProperty(field_descriptor));
if (property == NULL) {
return -1;
}
if (PyObject_SetAttrString(cls, field_descriptor->name().c_str(),
property.get()) < 0) {
return -1;
}
}
// For each enum set cls.<enum name> = EnumTypeWrapper(<enum descriptor>).
for (int i = 0; i < descriptor->enum_type_count(); ++i) {
const EnumDescriptor* enum_descriptor = descriptor->enum_type(i);
ScopedPyObjectPtr enum_type(
PyEnumDescriptor_FromDescriptor(enum_descriptor));
if (enum_type == NULL) {
return -1;
}
// Add wrapped enum type to message class.
ScopedPyObjectPtr wrapped(PyObject_CallFunctionObjArgs(
EnumTypeWrapper_class, enum_type.get(), NULL));
if (wrapped == NULL) {
return -1;
}
if (PyObject_SetAttrString(
cls, enum_descriptor->name().c_str(), wrapped.get()) == -1) {
return -1;
}
// For each enum value add cls.<name> = <number>
for (int j = 0; j < enum_descriptor->value_count(); ++j) {
const EnumValueDescriptor* enum_value_descriptor =
enum_descriptor->value(j);
ScopedPyObjectPtr value_number(PyInt_FromLong(
enum_value_descriptor->number()));
if (value_number == NULL) {
return -1;
}
if (PyObject_SetAttrString(cls, enum_value_descriptor->name().c_str(),
value_number.get()) == -1) {
return -1;
}
}
}
// For each extension set cls.<extension name> = <extension descriptor>.
//
// Extension descriptors come from
// <message descriptor>.extensions_by_name[name]
// which was defined previously.
for (int i = 0; i < descriptor->extension_count(); ++i) {
const google::protobuf::FieldDescriptor* field = descriptor->extension(i);
ScopedPyObjectPtr extension_field(PyFieldDescriptor_FromDescriptor(field));
if (extension_field == NULL) {
return -1;
}
// Add the extension field to the message class.
if (PyObject_SetAttrString(
cls, field->name().c_str(), extension_field.get()) == -1) {
return -1;
}
}
return 0;
}
static PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
static const char* kwlist[] = {"name", "bases", "dict", 0};
PyObject *bases, *dict;
const char* name;
// Check arguments: (name, bases, dict)
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "sO!O!:type", const_cast<char**>(kwlist), &name,
&PyTuple_Type, &bases, &PyDict_Type, &dict)) {
return NULL;
}
// Check bases: only (), or (message.Message,) are allowed
if (!(PyTuple_GET_SIZE(bases) == 0 ||
(PyTuple_GET_SIZE(bases) == 1 &&
PyTuple_GET_ITEM(bases, 0) == PythonMessage_class))) {
PyErr_SetString(PyExc_TypeError,
"A Message class can only inherit from Message");
return NULL;
}
// Check dict['DESCRIPTOR']
PyObject* py_descriptor = PyDict_GetItem(dict, kDESCRIPTOR);
if (py_descriptor == nullptr) {
PyErr_SetString(PyExc_TypeError, "Message class has no DESCRIPTOR");
return nullptr;
}
if (!PyObject_TypeCheck(py_descriptor, &PyMessageDescriptor_Type)) {
PyErr_Format(PyExc_TypeError, "Expected a message Descriptor, got %s",
py_descriptor->ob_type->tp_name);
return nullptr;
}
const Descriptor* message_descriptor =
PyMessageDescriptor_AsDescriptor(py_descriptor);
if (message_descriptor == nullptr) {
return nullptr;
}
// Messages have no __dict__
ScopedPyObjectPtr slots(PyTuple_New(0));
if (PyDict_SetItemString(dict, "__slots__", slots.get()) < 0) {
return NULL;
}
// Build the arguments to the base metaclass.
// We change the __bases__ classes.
ScopedPyObjectPtr new_args;
if (WKT_classes == NULL) {
ScopedPyObjectPtr well_known_types(PyImport_ImportModule(
"google.protobuf.internal.well_known_types"));
GOOGLE_DCHECK(well_known_types != NULL);
WKT_classes = PyObject_GetAttrString(well_known_types.get(), "WKTBASES");
GOOGLE_DCHECK(WKT_classes != NULL);
}
PyObject* well_known_class = PyDict_GetItemString(
WKT_classes, message_descriptor->full_name().c_str());
if (well_known_class == NULL) {
new_args.reset(Py_BuildValue("s(OO)O", name, CMessage_Type,
PythonMessage_class, dict));
} else {
new_args.reset(Py_BuildValue("s(OOO)O", name, CMessage_Type,
PythonMessage_class, well_known_class, dict));
}
if (new_args == NULL) {
return NULL;
}
// Call the base metaclass.
ScopedPyObjectPtr result(PyType_Type.tp_new(type, new_args.get(), NULL));
if (result == NULL) {
return NULL;
}
CMessageClass* newtype = reinterpret_cast<CMessageClass*>(result.get());
// Insert the empty weakref into the base classes.
if (InsertEmptyWeakref(
reinterpret_cast<PyTypeObject*>(PythonMessage_class)) < 0 ||
InsertEmptyWeakref(CMessage_Type) < 0) {
return NULL;
}
// Cache the descriptor, both as Python object and as C++ pointer.
const Descriptor* descriptor =
PyMessageDescriptor_AsDescriptor(py_descriptor);
if (descriptor == NULL) {
return NULL;
}
Py_INCREF(py_descriptor);
newtype->py_message_descriptor = py_descriptor;
newtype->message_descriptor = descriptor;
// TODO(amauryfa): Don't always use the canonical pool of the descriptor,
// use the MessageFactory optionally passed in the class dict.
PyDescriptorPool* py_descriptor_pool =
GetDescriptorPool_FromPool(descriptor->file()->pool());
if (py_descriptor_pool == NULL) {
return NULL;
}
newtype->py_message_factory = py_descriptor_pool->py_message_factory;
Py_INCREF(newtype->py_message_factory);
// Register the message in the MessageFactory.
// TODO(amauryfa): Move this call to MessageFactory.GetPrototype() when the
// MessageFactory is fully implemented in C++.
if (message_factory::RegisterMessageClass(newtype->py_message_factory,
descriptor, newtype) < 0) {
return NULL;
}
// Continue with type initialization: add other descriptors, enum values...
if (AddDescriptors(result.get(), descriptor) < 0) {
return NULL;
}
return result.release();
}
static void Dealloc(PyObject* pself) {
CMessageClass* self = reinterpret_cast<CMessageClass*>(pself);
Py_XDECREF(self->py_message_descriptor);
Py_XDECREF(self->py_message_factory);
return PyType_Type.tp_dealloc(pself);
}
static int GcTraverse(PyObject* pself, visitproc visit, void* arg) {
CMessageClass* self = reinterpret_cast<CMessageClass*>(pself);
Py_VISIT(self->py_message_descriptor);
Py_VISIT(self->py_message_factory);
return PyType_Type.tp_traverse(pself, visit, arg);
}
static int GcClear(PyObject* pself) {
// It's important to keep the descriptor and factory alive, until the
// C++ message is fully destructed.
return PyType_Type.tp_clear(pself);
}
// This function inserts and empty weakref at the end of the list of
// subclasses for the main protocol buffer Message class.
//
// This eliminates a O(n^2) behaviour in the internal add_subclass
// routine.
static int InsertEmptyWeakref(PyTypeObject *base_type) {
#if PY_MAJOR_VERSION >= 3
// Python 3.4 has already included the fix for the issue that this
// hack addresses. For further background and the fix please see
// https://bugs.python.org/issue17936.
return 0;
#else
#ifdef Py_DEBUG
// The code below causes all new subclasses to append an entry, which is never
// cleared. This is a small memory leak, which we disable in Py_DEBUG mode
// to have stable refcounting checks.
#else
PyObject *subclasses = base_type->tp_subclasses;
if (subclasses && PyList_CheckExact(subclasses)) {
return PyList_Append(subclasses, kEmptyWeakref);
}
#endif // !Py_DEBUG
return 0;
#endif // PY_MAJOR_VERSION >= 3
}
// The _extensions_by_name dictionary is built on every access.
// TODO(amauryfa): Migrate all users to pool.FindAllExtensions()
static PyObject* GetExtensionsByName(CMessageClass *self, void *closure) {
if (self->message_descriptor == NULL) {
// This is the base Message object, simply raise AttributeError.
PyErr_SetString(PyExc_AttributeError,
"Base Message class has no DESCRIPTOR");
return NULL;
}
const PyDescriptorPool* pool = self->py_message_factory->pool;
std::vector<const FieldDescriptor*> extensions;
pool->pool->FindAllExtensions(self->message_descriptor, &extensions);
ScopedPyObjectPtr result(PyDict_New());
for (int i = 0; i < extensions.size(); i++) {
ScopedPyObjectPtr extension(
PyFieldDescriptor_FromDescriptor(extensions[i]));
if (extension == NULL) {
return NULL;
}
if (PyDict_SetItemString(result.get(), extensions[i]->full_name().c_str(),
extension.get()) < 0) {
return NULL;
}
}
return result.release();
}
// The _extensions_by_number dictionary is built on every access.
// TODO(amauryfa): Migrate all users to pool.FindExtensionByNumber()
static PyObject* GetExtensionsByNumber(CMessageClass *self, void *closure) {
if (self->message_descriptor == NULL) {
// This is the base Message object, simply raise AttributeError.
PyErr_SetString(PyExc_AttributeError,
"Base Message class has no DESCRIPTOR");
return NULL;
}
const PyDescriptorPool* pool = self->py_message_factory->pool;
std::vector<const FieldDescriptor*> extensions;
pool->pool->FindAllExtensions(self->message_descriptor, &extensions);
ScopedPyObjectPtr result(PyDict_New());
for (int i = 0; i < extensions.size(); i++) {
ScopedPyObjectPtr extension(
PyFieldDescriptor_FromDescriptor(extensions[i]));
if (extension == NULL) {
return NULL;
}
ScopedPyObjectPtr number(PyInt_FromLong(extensions[i]->number()));
if (number == NULL) {
return NULL;
}
if (PyDict_SetItem(result.get(), number.get(), extension.get()) < 0) {
return NULL;
}
}
return result.release();
}
static PyGetSetDef Getters[] = {
{"_extensions_by_name", (getter)GetExtensionsByName, NULL},
{"_extensions_by_number", (getter)GetExtensionsByNumber, NULL},
{NULL}
};
// Compute some class attributes on the fly:
// - All the _FIELD_NUMBER attributes, for all fields and nested extensions.
// Returns a new reference, or NULL with an exception set.
static PyObject* GetClassAttribute(CMessageClass *self, PyObject* name) {
char* attr;
Py_ssize_t attr_size;
static const char kSuffix[] = "_FIELD_NUMBER";
if (PyString_AsStringAndSize(name, &attr, &attr_size) >= 0 &&
HasSuffixString(StringPiece(attr, attr_size), kSuffix)) {
std::string field_name(attr, attr_size - sizeof(kSuffix) + 1);
LowerString(&field_name);
// Try to find a field with the given name, without the suffix.
const FieldDescriptor* field =
self->message_descriptor->FindFieldByLowercaseName(field_name);
if (!field) {
// Search nested extensions as well.
field =
self->message_descriptor->FindExtensionByLowercaseName(field_name);
}
if (field) {
return PyInt_FromLong(field->number());
}
}
PyErr_SetObject(PyExc_AttributeError, name);
return NULL;
}
static PyObject* GetAttr(CMessageClass* self, PyObject* name) {
PyObject* result = CMessageClass_Type->tp_base->tp_getattro(
reinterpret_cast<PyObject*>(self), name);
if (result != NULL) {
return result;
}
if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
return NULL;
}
PyErr_Clear();
return GetClassAttribute(self, name);
}
} // namespace message_meta
static PyTypeObject _CMessageClass_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
".MessageMeta", // tp_name
sizeof(CMessageClass), // tp_basicsize
0, // tp_itemsize
message_meta::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
(getattrofunc)message_meta::GetAttr, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, // tp_flags
"The metaclass of ProtocolMessages", // tp_doc
message_meta::GcTraverse, // tp_traverse
message_meta::GcClear, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
message_meta::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
message_meta::New, // tp_new
};
PyTypeObject* CMessageClass_Type = &_CMessageClass_Type;
static CMessageClass* CheckMessageClass(PyTypeObject* cls) {
if (!PyObject_TypeCheck(cls, CMessageClass_Type)) {
PyErr_Format(PyExc_TypeError, "Class %s is not a Message", cls->tp_name);
return NULL;
}
return reinterpret_cast<CMessageClass*>(cls);
}
static const Descriptor* GetMessageDescriptor(PyTypeObject* cls) {
CMessageClass* type = CheckMessageClass(cls);
if (type == NULL) {
return NULL;
}
return type->message_descriptor;
}
// Forward declarations
namespace cmessage {
int InternalReleaseFieldByDescriptor(
CMessage* self,
const FieldDescriptor* field_descriptor);
} // namespace cmessage
// ---------------------------------------------------------------------
PyObject* EncodeError_class;
PyObject* DecodeError_class;
PyObject* PickleError_class;
// Format an error message for unexpected types.
// Always return with an exception set.
void FormatTypeError(PyObject* arg, const char* expected_types) {
// This function is often called with an exception set.
// Clear it to call PyObject_Repr() in good conditions.
PyErr_Clear();
PyObject* repr = PyObject_Repr(arg);
if (repr) {
PyErr_Format(PyExc_TypeError,
"%.100s has type %.100s, but expected one of: %s",
PyString_AsString(repr),
Py_TYPE(arg)->tp_name,
expected_types);
Py_DECREF(repr);
}
}
void OutOfRangeError(PyObject* arg) {
PyObject *s = PyObject_Str(arg);
if (s) {
PyErr_Format(PyExc_ValueError,
"Value out of range: %s",
PyString_AsString(s));
Py_DECREF(s);
}
}
template<class RangeType, class ValueType>
bool VerifyIntegerCastAndRange(PyObject* arg, ValueType value) {
if (PROTOBUF_PREDICT_FALSE(value == -1 && PyErr_Occurred())) {
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
// Replace it with the same ValueError as pure python protos instead of
// the default one.
PyErr_Clear();
OutOfRangeError(arg);
} // Otherwise propagate existing error.
return false;
}
if (PROTOBUF_PREDICT_FALSE(!IsValidNumericCast<RangeType>(value))) {
OutOfRangeError(arg);
return false;
}
return true;
}
template <class T>
bool CheckAndGetInteger(PyObject* arg, T* value) {
// The fast path.
#if PY_MAJOR_VERSION < 3
// For the typical case, offer a fast path.
if (PROTOBUF_PREDICT_TRUE(PyInt_Check(arg))) {
long int_result = PyInt_AsLong(arg);
if (PROTOBUF_PREDICT_TRUE(IsValidNumericCast<T>(int_result))) {
*value = static_cast<T>(int_result);
return true;
} else {
OutOfRangeError(arg);
return false;
}
}
#endif
// This effectively defines an integer as "an object that can be cast as
// an integer and can be used as an ordinal number".
// This definition includes everything that implements numbers.Integral
// and shouldn't cast the net too wide.
if (PROTOBUF_PREDICT_FALSE(!PyIndex_Check(arg))) {
FormatTypeError(arg, "int, long");
return false;
}
// Now we have an integral number so we can safely use PyLong_ functions.
// We need to treat the signed and unsigned cases differently in case arg is
// holding a value above the maximum for signed longs.
if (std::numeric_limits<T>::min() == 0) {
// Unsigned case.
unsigned PY_LONG_LONG ulong_result;
if (PyLong_Check(arg)) {
ulong_result = PyLong_AsUnsignedLongLong(arg);
} else {
// Unlike PyLong_AsLongLong, PyLong_AsUnsignedLongLong is very
// picky about the exact type.
PyObject* casted = PyNumber_Long(arg);
if (PROTOBUF_PREDICT_FALSE(casted == nullptr)) {
// Propagate existing error.
return false;
}
ulong_result = PyLong_AsUnsignedLongLong(casted);
Py_DECREF(casted);
}
if (VerifyIntegerCastAndRange<T, unsigned PY_LONG_LONG>(arg,
ulong_result)) {
*value = static_cast<T>(ulong_result);
} else {
return false;
}
} else {
// Signed case.
PY_LONG_LONG long_result;
PyNumberMethods *nb;
if ((nb = arg->ob_type->tp_as_number) != NULL && nb->nb_int != NULL) {
// PyLong_AsLongLong requires it to be a long or to have an __int__()
// method.
long_result = PyLong_AsLongLong(arg);
} else {
// Valid subclasses of numbers.Integral should have a __long__() method
// so fall back to that.
PyObject* casted = PyNumber_Long(arg);
if (PROTOBUF_PREDICT_FALSE(casted == nullptr)) {
// Propagate existing error.
return false;
}
long_result = PyLong_AsLongLong(casted);
Py_DECREF(casted);
}
if (VerifyIntegerCastAndRange<T, PY_LONG_LONG>(arg, long_result)) {
*value = static_cast<T>(long_result);
} else {
return false;
}
}
return true;
}
// These are referenced by repeated_scalar_container, and must
// be explicitly instantiated.
template bool CheckAndGetInteger<int32>(PyObject*, int32*);
template bool CheckAndGetInteger<int64>(PyObject*, int64*);
template bool CheckAndGetInteger<uint32>(PyObject*, uint32*);
template bool CheckAndGetInteger<uint64>(PyObject*, uint64*);
bool CheckAndGetDouble(PyObject* arg, double* value) {
*value = PyFloat_AsDouble(arg);
if (PROTOBUF_PREDICT_FALSE(*value == -1 && PyErr_Occurred())) {
FormatTypeError(arg, "int, long, float");
return false;
}
return true;
}
bool CheckAndGetFloat(PyObject* arg, float* value) {
double double_value;
if (!CheckAndGetDouble(arg, &double_value)) {
return false;
}
*value = io::SafeDoubleToFloat(double_value);
return true;
}
bool CheckAndGetBool(PyObject* arg, bool* value) {
long long_value = PyInt_AsLong(arg);
if (long_value == -1 && PyErr_Occurred()) {
FormatTypeError(arg, "int, long, bool");
return false;
}
*value = static_cast<bool>(long_value);
return true;
}
// Checks whether the given object (which must be "bytes" or "unicode") contains
// valid UTF-8.
bool IsValidUTF8(PyObject* obj) {
if (PyBytes_Check(obj)) {
PyObject* unicode = PyUnicode_FromEncodedObject(obj, "utf-8", NULL);
// Clear the error indicator; we report our own error when desired.
PyErr_Clear();
if (unicode) {
Py_DECREF(unicode);
return true;
} else {
return false;
}
} else {
// Unicode object, known to be valid UTF-8.
return true;
}
}
bool AllowInvalidUTF8(const FieldDescriptor* field) { return false; }
PyObject* CheckString(PyObject* arg, const FieldDescriptor* descriptor) {
GOOGLE_DCHECK(descriptor->type() == FieldDescriptor::TYPE_STRING ||
descriptor->type() == FieldDescriptor::TYPE_BYTES);
if (descriptor->type() == FieldDescriptor::TYPE_STRING) {
if (!PyBytes_Check(arg) && !PyUnicode_Check(arg)) {
FormatTypeError(arg, "bytes, unicode");
return NULL;
}
if (!IsValidUTF8(arg) && !AllowInvalidUTF8(descriptor)) {
PyObject* repr = PyObject_Repr(arg);
PyErr_Format(PyExc_ValueError,
"%s has type str, but isn't valid UTF-8 "
"encoding. Non-UTF-8 strings must be converted to "
"unicode objects before being added.",
PyString_AsString(repr));
Py_DECREF(repr);
return NULL;
}
} else if (!PyBytes_Check(arg)) {
FormatTypeError(arg, "bytes");
return NULL;
}
PyObject* encoded_string = NULL;
if (descriptor->type() == FieldDescriptor::TYPE_STRING) {
if (PyBytes_Check(arg)) {
// The bytes were already validated as correctly encoded UTF-8 above.
encoded_string = arg; // Already encoded.
Py_INCREF(encoded_string);
} else {
encoded_string = PyUnicode_AsEncodedString(arg, "utf-8", NULL);
}
} else {
// In this case field type is "bytes".
encoded_string = arg;
Py_INCREF(encoded_string);
}
return encoded_string;
}
bool CheckAndSetString(
PyObject* arg, Message* message,
const FieldDescriptor* descriptor,
const Reflection* reflection,
bool append,
int index) {
ScopedPyObjectPtr encoded_string(CheckString(arg, descriptor));
if (encoded_string.get() == NULL) {
return false;
}
char* value;
Py_ssize_t value_len;
if (PyBytes_AsStringAndSize(encoded_string.get(), &value, &value_len) < 0) {
return false;
}
std::string value_string(value, value_len);
if (append) {
reflection->AddString(message, descriptor, std::move(value_string));
} else if (index < 0) {
reflection->SetString(message, descriptor, std::move(value_string));
} else {
reflection->SetRepeatedString(message, descriptor, index,
std::move(value_string));
}
return true;
}
PyObject* ToStringObject(const FieldDescriptor* descriptor,
const std::string& value) {
if (descriptor->type() != FieldDescriptor::TYPE_STRING) {
return PyBytes_FromStringAndSize(value.c_str(), value.length());
}
PyObject* result = PyUnicode_DecodeUTF8(value.c_str(), value.length(), NULL);
// If the string can't be decoded in UTF-8, just return a string object that
// contains the raw bytes. This can't happen if the value was assigned using
// the members of the Python message object, but can happen if the values were
// parsed from the wire (binary).
if (result == NULL) {
PyErr_Clear();
result = PyBytes_FromStringAndSize(value.c_str(), value.length());
}
return result;
}
bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
const Message* message) {
if (message->GetDescriptor() == field_descriptor->containing_type()) {
return true;
}
PyErr_Format(PyExc_KeyError, "Field '%s' does not belong to message '%s'",
field_descriptor->full_name().c_str(),
message->GetDescriptor()->full_name().c_str());
return false;
}
namespace cmessage {
PyMessageFactory* GetFactoryForMessage(CMessage* message) {
GOOGLE_DCHECK(PyObject_TypeCheck(message, CMessage_Type));
return reinterpret_cast<CMessageClass*>(Py_TYPE(message))->py_message_factory;
}
static int MaybeReleaseOverlappingOneofField(
CMessage* cmessage,
const FieldDescriptor* field) {
#ifdef GOOGLE_PROTOBUF_HAS_ONEOF
Message* message = cmessage->message;
const Reflection* reflection = message->GetReflection();
if (!field->containing_oneof() ||
!reflection->HasOneof(*message, field->containing_oneof()) ||
reflection->HasField(*message, field)) {
// No other field in this oneof, no need to release.
return 0;
}
const OneofDescriptor* oneof = field->containing_oneof();
const FieldDescriptor* existing_field =
reflection->GetOneofFieldDescriptor(*message, oneof);
if (existing_field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
// Non-message fields don't need to be released.
return 0;
}
if (InternalReleaseFieldByDescriptor(cmessage, existing_field) < 0) {
return -1;
}
#endif
return 0;
}
// After a Merge, visit every sub-message that was read-only, and
// eventually update their pointer if the Merge operation modified them.
int FixupMessageAfterMerge(CMessage* self) {
if (!self->composite_fields) {
return 0;
}
for (const auto& item : *self->composite_fields) {
const FieldDescriptor* descriptor = item.first;
if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!descriptor->is_repeated()) {
CMessage* cmsg = reinterpret_cast<CMessage*>(item.second);
if (cmsg->read_only == false) {
return 0;
}
Message* message = self->message;
const Reflection* reflection = message->GetReflection();
if (reflection->HasField(*message, descriptor)) {
// Message used to be read_only, but is no longer. Get the new pointer
// and record it.
Message* mutable_message =
reflection->MutableMessage(message, descriptor, nullptr);
cmsg->message = mutable_message;
cmsg->read_only = false;
if (FixupMessageAfterMerge(cmsg) < 0) {
return -1;
}
}
}
}
return 0;
}
// ---------------------------------------------------------------------
// Making a message writable
int AssureWritable(CMessage* self) {
if (self == NULL || !self->read_only) {
return 0;
}
// Toplevel messages are always mutable.
GOOGLE_DCHECK(self->parent);
if (AssureWritable(self->parent) == -1) {
return -1;
}
// If this message is part of a oneof, there might be a field to release in
// the parent.
if (MaybeReleaseOverlappingOneofField(self->parent,
self->parent_field_descriptor) < 0) {
return -1;
}
// Make self->message writable.
Message* parent_message = self->parent->message;
const Reflection* reflection = parent_message->GetReflection();
Message* mutable_message = reflection->MutableMessage(
parent_message, self->parent_field_descriptor,
GetFactoryForMessage(self->parent)->message_factory);
if (mutable_message == NULL) {
return -1;
}
self->message = mutable_message;
self->read_only = false;
return 0;
}
// --- Globals:
// Retrieve a C++ FieldDescriptor for an extension handle.
const FieldDescriptor* GetExtensionDescriptor(PyObject* extension) {
ScopedPyObjectPtr cdescriptor;
if (!PyObject_TypeCheck(extension, &PyFieldDescriptor_Type)) {
// Most callers consider extensions as a plain dictionary. We should
// allow input which is not a field descriptor, and simply pretend it does
// not exist.
PyErr_SetObject(PyExc_KeyError, extension);
return NULL;
}
return PyFieldDescriptor_AsDescriptor(extension);
}
// If value is a string, convert it into an enum value based on the labels in
// descriptor, otherwise simply return value. Always returns a new reference.
static PyObject* GetIntegerEnumValue(const FieldDescriptor& descriptor,
PyObject* value) {
if (PyString_Check(value) || PyUnicode_Check(value)) {
const EnumDescriptor* enum_descriptor = descriptor.enum_type();
if (enum_descriptor == NULL) {
PyErr_SetString(PyExc_TypeError, "not an enum field");
return NULL;
}
char* enum_label;
Py_ssize_t size;
if (PyString_AsStringAndSize(value, &enum_label, &size) < 0) {
return NULL;
}
const EnumValueDescriptor* enum_value_descriptor =
enum_descriptor->FindValueByName(StringParam(enum_label, size));
if (enum_value_descriptor == NULL) {
PyErr_Format(PyExc_ValueError, "unknown enum label \"%s\"", enum_label);
return NULL;
}
return PyInt_FromLong(enum_value_descriptor->number());
}
Py_INCREF(value);
return value;
}
// Delete a slice from a repeated field.
// The only way to remove items in C++ protos is to delete the last one,
// so we swap items to move the deleted ones at the end, and then strip the
// sequence.
int DeleteRepeatedField(
CMessage* self,
const FieldDescriptor* field_descriptor,
PyObject* slice) {
Py_ssize_t length, from, to, step, slice_length;
Message* message = self->message;
const Reflection* reflection = message->GetReflection();
int min, max;
length = reflection->FieldSize(*message, field_descriptor);
if (PySlice_Check(slice)) {
from = to = step = slice_length = 0;