/
message.c
1378 lines (1181 loc) · 39.6 KB
/
message.c
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 2014 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.
#include "message.h"
#include <inttypes.h>
#include <php.h>
#include <stdlib.h>
// This is not self-contained: it must be after other Zend includes.
#include <Zend/zend_exceptions.h>
#include <Zend/zend_inheritance.h>
#include "arena.h"
#include "array.h"
#include "convert.h"
#include "def.h"
#include "map.h"
#include "php-upb.h"
#include "protobuf.h"
// -----------------------------------------------------------------------------
// Message
// -----------------------------------------------------------------------------
typedef struct {
zend_object std;
zval arena;
const Descriptor* desc;
upb_msg *msg;
} Message;
zend_class_entry *message_ce;
static zend_object_handlers message_object_handlers;
static void Message_SuppressDefaultProperties(zend_class_entry *class_type) {
// We suppress all default properties, because all our properties are handled
// by our read_property handler.
//
// This also allows us to put our zend_object member at the beginning of our
// struct -- instead of putting it at the end with pointer fixups to access
// our own data, as recommended in the docs -- because Zend won't add any of
// its own storage directly after the zend_object if default_properties_count
// == 0.
//
// This is not officially supported, but since it simplifies the code, we'll
// do it for as long as it works in practice.
class_type->default_properties_count = 0;
}
// PHP Object Handlers /////////////////////////////////////////////////////////
/**
* Message_create()
*
* PHP class entry function to allocate and initialize a new Message object.
*/
static zend_object* Message_create(zend_class_entry *class_type) {
Message *intern = emalloc(sizeof(Message));
Message_SuppressDefaultProperties(class_type);
zend_object_std_init(&intern->std, class_type);
intern->std.handlers = &message_object_handlers;
Arena_Init(&intern->arena);
return &intern->std;
}
/**
* Message_dtor()
*
* Object handler to destroy a Message. This releases all resources associated
* with the message. Note that it is possible to access a destroyed object from
* PHP in rare cases.
*/
static void Message_dtor(zend_object* obj) {
Message* intern = (Message*)obj;
ObjCache_Delete(intern->msg);
zval_dtor(&intern->arena);
zend_object_std_dtor(&intern->std);
}
/**
* get_field()
*
* Helper function to look up a field given a member name (as a string).
*/
static const upb_fielddef *get_field(Message *msg, PROTO_STR *member) {
const upb_msgdef *m = msg->desc->msgdef;
const upb_fielddef *f =
upb_msgdef_ntof(m, PROTO_STRVAL_P(member), PROTO_STRLEN_P(member));
if (!f) {
zend_throw_exception_ex(NULL, 0, "No such property %s.",
ZSTR_VAL(msg->desc->class_entry->name));
}
return f;
}
static void Message_get(Message *intern, const upb_fielddef *f, zval *rv) {
upb_arena *arena = Arena_Get(&intern->arena);
if (upb_fielddef_ismap(f)) {
upb_mutmsgval msgval = upb_msg_mutable(intern->msg, f, arena);
MapField_GetPhpWrapper(rv, msgval.map, MapType_Get(f), &intern->arena);
} else if (upb_fielddef_isseq(f)) {
upb_mutmsgval msgval = upb_msg_mutable(intern->msg, f, arena);
RepeatedField_GetPhpWrapper(rv, msgval.array, TypeInfo_Get(f),
&intern->arena);
} else {
upb_msgval msgval = upb_msg_get(intern->msg, f);
Convert_UpbToPhp(msgval, rv, TypeInfo_Get(f), &intern->arena);
}
}
static bool Message_set(Message *intern, const upb_fielddef *f, zval *val) {
upb_arena *arena = Arena_Get(&intern->arena);
upb_msgval msgval;
if (upb_fielddef_ismap(f)) {
msgval.map_val = MapField_GetUpbMap(val, MapType_Get(f), arena);
if (!msgval.map_val) return false;
} else if (upb_fielddef_isseq(f)) {
msgval.array_val = RepeatedField_GetUpbArray(val, TypeInfo_Get(f), arena);
if (!msgval.array_val) return false;
} else {
if (!Convert_PhpToUpb(val, &msgval, TypeInfo_Get(f), arena)) return false;
}
upb_msg_set(intern->msg, f, msgval, arena);
return true;
}
static bool MessageEq(const upb_msg *m1, const upb_msg *m2, const upb_msgdef *m);
/**
* ValueEq()
*/
bool ValueEq(upb_msgval val1, upb_msgval val2, TypeInfo type) {
switch (type.type) {
case UPB_TYPE_BOOL:
return val1.bool_val == val2.bool_val;
case UPB_TYPE_INT32:
case UPB_TYPE_UINT32:
case UPB_TYPE_ENUM:
return val1.int32_val == val2.int32_val;
case UPB_TYPE_INT64:
case UPB_TYPE_UINT64:
return val1.int64_val == val2.int64_val;
case UPB_TYPE_FLOAT:
return val1.float_val == val2.float_val;
case UPB_TYPE_DOUBLE:
return val1.double_val == val2.double_val;
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES:
return val1.str_val.size == val2.str_val.size &&
memcmp(val1.str_val.data, val2.str_val.data, val1.str_val.size) == 0;
case UPB_TYPE_MESSAGE:
return MessageEq(val1.msg_val, val2.msg_val, type.desc->msgdef);
default:
return false;
}
}
/**
* MessageEq()
*/
static bool MessageEq(const upb_msg *m1, const upb_msg *m2, const upb_msgdef *m) {
upb_msg_field_iter i;
for(upb_msg_field_begin(&i, m);
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
const upb_fielddef *f = upb_msg_iter_field(&i);
upb_msgval val1 = upb_msg_get(m1, f);
upb_msgval val2 = upb_msg_get(m2, f);
if (upb_fielddef_haspresence(f)) {
if (upb_msg_has(m1, f) != upb_msg_has(m2, f)) {
return false;
}
if (!upb_msg_has(m1, f)) continue;
}
if (upb_fielddef_ismap(f)) {
if (!MapEq(val1.map_val, val2.map_val, MapType_Get(f))) return false;
} else if (upb_fielddef_isseq(f)) {
if (!ArrayEq(val1.array_val, val2.array_val, TypeInfo_Get(f))) return false;
} else {
if (!ValueEq(val1, val2, TypeInfo_Get(f))) return false;
}
}
return true;
}
/**
* Message_compare_objects()
*
* Object handler for comparing two message objects. Called whenever PHP code
* does:
*
* $m1 == $m2
*/
static int Message_compare_objects(zval *m1, zval *m2) {
Message* intern1 = (Message*)Z_OBJ_P(m1);
Message* intern2 = (Message*)Z_OBJ_P(m2);
const upb_msgdef *m = intern1->desc->msgdef;
if (intern2->desc->msgdef != m) return 1;
return MessageEq(intern1->msg, intern2->msg, m) ? 0 : 1;
}
/**
* Message_has_property()
*
* Object handler for testing whether a property exists. Called when PHP code
* does any of:
*
* isset($message->foobar);
* property_exists($message->foobar);
*
* Note that all properties of generated messages are private, so this should
* only be possible to invoke from generated code, which has accessors like this
* (if the field has presence):
*
* public function hasOptionalInt32()
* {
* return isset($this->optional_int32);
* }
*/
static int Message_has_property(PROTO_VAL *obj, PROTO_STR *member,
int has_set_exists,
void **cache_slot) {
Message* intern = PROTO_VAL_P(obj);
const upb_fielddef *f = get_field(intern, member);
if (!f) return 0;
if (!upb_fielddef_haspresence(f)) {
zend_throw_exception_ex(
NULL, 0,
"Cannot call isset() on field %s which does not have presence.",
ZSTR_VAL(intern->desc->class_entry->name));
return 0;
}
return upb_msg_has(intern->msg, f);
}
/**
* Message_unset_property()
*
* Object handler for unsetting a property. Called when PHP code calls:
* does any of:
*
* unset($message->foobar);
*
* Note that all properties of generated messages are private, so this should
* only be possible to invoke from generated code, which has accessors like this
* (if the field has presence):
*
* public function clearOptionalInt32()
* {
* unset($this->optional_int32);
* }
*/
static void Message_unset_property(PROTO_VAL *obj, PROTO_STR *member,
void **cache_slot) {
Message* intern = PROTO_VAL_P(obj);
const upb_fielddef *f = get_field(intern, member);
if (!f) return;
if (!upb_fielddef_haspresence(f)) {
zend_throw_exception_ex(
NULL, 0,
"Cannot call unset() on field %s which does not have presence.",
ZSTR_VAL(intern->desc->class_entry->name));
return;
}
upb_msg_clearfield(intern->msg, f);
}
/**
* Message_read_property()
*
* Object handler for reading a property in PHP. Called when PHP code does:
*
* $x = $message->foobar;
*
* Note that all properties of generated messages are private, so this should
* only be possible to invoke from generated code, which has accessors like:
*
* public function getOptionalInt32()
* {
* return $this->optional_int32;
* }
*
* We lookup the field and return the scalar, RepeatedField, or MapField for
* this field.
*/
static zval *Message_read_property(PROTO_VAL *obj, PROTO_STR *member,
int type, void **cache_slot, zval *rv) {
Message* intern = PROTO_VAL_P(obj);
const upb_fielddef *f = get_field(intern, member);
if (!f) return &EG(uninitialized_zval);
Message_get(intern, f, rv);
return rv;
}
/**
* Message_write_property()
*
* Object handler for writing a property in PHP. Called when PHP code does:
*
* $message->foobar = $x;
*
* Note that all properties of generated messages are private, so this should
* only be possible to invoke from generated code, which has accessors like:
*
* public function setOptionalInt32($var)
* {
* GPBUtil::checkInt32($var);
* $this->optional_int32 = $var;
*
* return $this;
* }
*
* The C extension version of checkInt32() doesn't actually check anything, so
* we perform all checking and conversion in this function.
*/
static PROTO_RETURN_VAL Message_write_property(
PROTO_VAL *obj, PROTO_STR *member, zval *val, void **cache_slot) {
Message* intern = PROTO_VAL_P(obj);
const upb_fielddef *f = get_field(intern, member);
if (f && Message_set(intern, f, val)) {
#if PHP_VERSION_ID < 70400
return;
#else
return val;
#endif
} else {
#if PHP_VERSION_ID < 70400
return;
#else
return &EG(error_zval);
#endif
}
}
/**
* Message_get_property_ptr_ptr()
*
* Object handler for the get_property_ptr_ptr event in PHP. This returns a
* reference to our internal properties. We don't support this, so we return
* NULL.
*/
static zval *Message_get_property_ptr_ptr(PROTO_VAL *object, PROTO_STR *member,
int type,
void **cache_slot) {
return NULL; // We do not have a properties table.
}
/**
* Message_clone_obj()
*
* Object handler for cloning an object in PHP. Called when PHP code does:
*
* $msg2 = clone $msg;
*/
static zend_object *Message_clone_obj(PROTO_VAL *object) {
Message* intern = PROTO_VAL_P(object);
upb_msg *clone = upb_msg_new(intern->desc->msgdef, Arena_Get(&intern->arena));
// TODO: copy unknown fields?
// TODO: use official upb msg copy function
memcpy(clone, intern->msg, upb_msgdef_layout(intern->desc->msgdef)->size);
zval ret;
Message_GetPhpWrapper(&ret, intern->desc, clone, &intern->arena);
return Z_OBJ_P(&ret);
}
/**
* Message_get_properties()
*
* Object handler for the get_properties event in PHP. This returns a HashTable
* of our internal properties. We don't support this, so we return NULL.
*/
static HashTable *Message_get_properties(PROTO_VAL *object) {
return NULL; // We don't offer direct references to our properties.
}
// C Functions from message.h. /////////////////////////////////////////////////
// These are documented in the header file.
void Message_GetPhpWrapper(zval *val, const Descriptor *desc, upb_msg *msg,
zval *arena) {
if (!msg) {
ZVAL_NULL(val);
return;
}
if (!ObjCache_Get(msg, val)) {
Message *intern = emalloc(sizeof(Message));
Message_SuppressDefaultProperties(desc->class_entry);
zend_object_std_init(&intern->std, desc->class_entry);
intern->std.handlers = &message_object_handlers;
ZVAL_COPY(&intern->arena, arena);
intern->desc = desc;
intern->msg = msg;
ZVAL_OBJ(val, &intern->std);
ObjCache_Add(intern->msg, &intern->std);
}
}
bool Message_GetUpbMessage(zval *val, const Descriptor *desc, upb_arena *arena,
upb_msg **msg) {
PBPHP_ASSERT(desc);
if (Z_ISREF_P(val)) {
ZVAL_DEREF(val);
}
if (Z_TYPE_P(val) == IS_NULL) {
*msg = NULL;
return true;
}
if (Z_TYPE_P(val) == IS_OBJECT &&
instanceof_function(Z_OBJCE_P(val), desc->class_entry)) {
Message *intern = (Message*)Z_OBJ_P(val);
upb_arena_fuse(arena, Arena_Get(&intern->arena));
*msg = intern->msg;
return true;
} else {
zend_throw_exception_ex(NULL, 0, "Given value is not an instance of %s.",
ZSTR_VAL(desc->class_entry->name));
return false;
}
}
// Message PHP methods /////////////////////////////////////////////////////////
/**
* Message_InitFromPhp()
*
* Helper method to handle the initialization of a message from a PHP value, eg.
*
* $m = new TestMessage([
* 'optional_int32' => -42,
* 'optional_bool' => true,
* 'optional_string' => 'a',
* 'optional_enum' => TestEnum::ONE,
* 'optional_message' => new Sub([
* 'a' => 33
* ]),
* 'repeated_int32' => [-42, -52],
* 'repeated_enum' => [TestEnum::ZERO, TestEnum::ONE],
* 'repeated_message' => [new Sub(['a' => 34]),
* new Sub(['a' => 35])],
* 'map_int32_int32' => [-62 => -62],
* 'map_int32_enum' => [1 => TestEnum::ONE],
* 'map_int32_message' => [1 => new Sub(['a' => 36])],
* ]);
*
* The initializer must be an array.
*/
bool Message_InitFromPhp(upb_msg *msg, const upb_msgdef *m, zval *init,
upb_arena *arena) {
HashTable* table = HASH_OF(init);
HashPosition pos;
if (Z_ISREF_P(init)) {
ZVAL_DEREF(init);
}
if (Z_TYPE_P(init) != IS_ARRAY) {
zend_throw_exception_ex(NULL, 0,
"Initializer for a message %s must be an array.",
upb_msgdef_fullname(m));
return false;
}
zend_hash_internal_pointer_reset_ex(table, &pos);
while (true) { // Iterate over key/value pairs.
zval key;
zval *val;
const upb_fielddef *f;
upb_msgval msgval;
zend_hash_get_current_key_zval_ex(table, &key, &pos);
val = zend_hash_get_current_data_ex(table, &pos);
if (!val) return true; // Finished iteration.
if (Z_ISREF_P(val)) {
ZVAL_DEREF(val);
}
f = upb_msgdef_ntof(m, Z_STRVAL_P(&key), Z_STRLEN_P(&key));
if (!f) {
zend_throw_exception_ex(NULL, 0,
"No such field %s", Z_STRVAL_P(&key));
return false;
}
if (upb_fielddef_ismap(f)) {
msgval.map_val = MapField_GetUpbMap(val, MapType_Get(f), arena);
if (!msgval.map_val) return false;
} else if (upb_fielddef_isseq(f)) {
msgval.array_val = RepeatedField_GetUpbArray(val, TypeInfo_Get(f), arena);
if (!msgval.array_val) return false;
} else {
if (!Convert_PhpToUpbAutoWrap(val, &msgval, TypeInfo_Get(f), arena)) {
return false;
}
}
upb_msg_set(msg, f, msgval, arena);
zend_hash_move_forward_ex(table, &pos);
zval_dtor(&key);
}
}
static void Message_Initialize(Message *intern, const Descriptor *desc) {
intern->desc = desc;
intern->msg = upb_msg_new(desc->msgdef, Arena_Get(&intern->arena));
ObjCache_Add(intern->msg, &intern->std);
}
/**
* Message::__construct()
*
* Constructor for Message.
* @param array Map of initial values ['k' = val]
*/
PHP_METHOD(Message, __construct) {
Message* intern = (Message*)Z_OBJ_P(getThis());
const Descriptor* desc;
zend_class_entry *ce = Z_OBJCE_P(getThis());
upb_arena *arena = Arena_Get(&intern->arena);
zval *init_arr = NULL;
// This descriptor should always be available, as the generated __construct
// method calls initOnce() to load the descriptor prior to calling us.
//
// However, if the user created their own class derived from Message, this
// will trigger an infinite construction loop and blow the stack. We
// temporarily clear create_object to break this loop (see check in
// NameMap_GetMessage()).
PBPHP_ASSERT(ce->create_object == Message_create);
ce->create_object = NULL;
desc = Descriptor_GetFromClassEntry(ce);
ce->create_object = Message_create;
if (!desc) {
zend_throw_exception_ex(
NULL, 0,
"Couldn't find descriptor. Note only generated code may derive from "
"\\Google\\Protobuf\\Internal\\Message");
return;
}
Message_Initialize(intern, desc);
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!", &init_arr) == FAILURE) {
return;
}
if (init_arr) {
Message_InitFromPhp(intern->msg, desc->msgdef, init_arr, arena);
}
}
/**
* Message::discardUnknownFields()
*
* Discards any unknown fields for this message or any submessages.
*/
PHP_METHOD(Message, discardUnknownFields) {
Message* intern = (Message*)Z_OBJ_P(getThis());
upb_msg_discardunknown(intern->msg, intern->desc->msgdef, 64);
}
/**
* Message::clear()
*
* Clears all fields of this message.
*/
PHP_METHOD(Message, clear) {
Message* intern = (Message*)Z_OBJ_P(getThis());
upb_msg_clear(intern->msg, intern->desc->msgdef);
}
/**
* Message::mergeFrom()
*
* Merges from the given message, which must be of the same class as us.
* @param object Message to merge from.
*/
PHP_METHOD(Message, mergeFrom) {
Message* intern = (Message*)Z_OBJ_P(getThis());
Message* from;
upb_arena *arena = Arena_Get(&intern->arena);
const upb_msglayout *l = upb_msgdef_layout(intern->desc->msgdef);
zval* value;
char *pb;
size_t size;
bool ok;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &value,
intern->desc->class_entry) == FAILURE) {
return;
}
from = (Message*)Z_OBJ_P(value);
// Should be guaranteed since we passed the class type to
// zend_parse_parameters().
PBPHP_ASSERT(from->desc == intern->desc);
// TODO(haberman): use a temp arena for this once we can make upb_decode()
// copy strings.
pb = upb_encode(from->msg, l, arena, &size);
if (!pb) {
zend_throw_exception_ex(NULL, 0, "Max nesting exceeded");
return;
}
ok = upb_decode(pb, size, intern->msg, l, arena);
PBPHP_ASSERT(ok);
}
/**
* Message::mergeFromString()
*
* Merges from the given string.
* @param string Binary protobuf data to merge.
*/
PHP_METHOD(Message, mergeFromString) {
Message* intern = (Message*)Z_OBJ_P(getThis());
char *data = NULL;
char *data_copy = NULL;
zend_long data_len;
const upb_msglayout *l = upb_msgdef_layout(intern->desc->msgdef);
upb_arena *arena = Arena_Get(&intern->arena);
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &data, &data_len) ==
FAILURE) {
return;
}
// TODO(haberman): avoid this copy when we can make the decoder copy.
data_copy = upb_arena_malloc(arena, data_len);
memcpy(data_copy, data, data_len);
if (!upb_decode(data_copy, data_len, intern->msg, l, arena)) {
zend_throw_exception_ex(NULL, 0, "Error occurred during parsing");
return;
}
}
/**
* Message::serializeToString()
*
* Serializes this message instance to protobuf data.
* @return string Serialized protobuf data.
*/
PHP_METHOD(Message, serializeToString) {
Message* intern = (Message*)Z_OBJ_P(getThis());
const upb_msglayout *l = upb_msgdef_layout(intern->desc->msgdef);
upb_arena *tmp_arena = upb_arena_new();
char *data;
size_t size;
data = upb_encode(intern->msg, l, tmp_arena, &size);
if (!data) {
zend_throw_exception_ex(NULL, 0, "Error occurred during serialization");
upb_arena_free(tmp_arena);
return;
}
RETVAL_STRINGL(data, size);
upb_arena_free(tmp_arena);
}
/**
* Message::mergeFromJsonString()
*
* Merges the JSON data parsed from the given string.
* @param string Serialized JSON data.
*/
PHP_METHOD(Message, mergeFromJsonString) {
Message* intern = (Message*)Z_OBJ_P(getThis());
char *data = NULL;
char *data_copy = NULL;
zend_long data_len;
upb_arena *arena = Arena_Get(&intern->arena);
upb_status status;
zend_bool ignore_json_unknown = false;
int options = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|b", &data, &data_len,
&ignore_json_unknown) == FAILURE) {
return;
}
// TODO(haberman): avoid this copy when we can make the decoder copy.
data_copy = upb_arena_malloc(arena, data_len + 1);
memcpy(data_copy, data, data_len);
data_copy[data_len] = '\0';
if (ignore_json_unknown) {
options |= UPB_JSONDEC_IGNOREUNKNOWN;
}
upb_status_clear(&status);
if (!upb_json_decode(data_copy, data_len, intern->msg, intern->desc->msgdef,
DescriptorPool_GetSymbolTable(), options, arena,
&status)) {
zend_throw_exception_ex(NULL, 0, "Error occurred during parsing: %s",
upb_status_errmsg(&status));
return;
}
}
/**
* Message::serializeToJsonString()
*
* Serializes this object to JSON.
* @return string Serialized JSON data.
*/
PHP_METHOD(Message, serializeToJsonString) {
Message* intern = (Message*)Z_OBJ_P(getThis());
size_t size;
int options = 0;
char buf[1024];
zend_bool preserve_proto_fieldnames = false;
upb_status status;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b",
&preserve_proto_fieldnames) == FAILURE) {
return;
}
if (preserve_proto_fieldnames) {
options |= UPB_JSONENC_PROTONAMES;
}
upb_status_clear(&status);
size = upb_json_encode(intern->msg, intern->desc->msgdef,
DescriptorPool_GetSymbolTable(), options, buf,
sizeof(buf), &status);
if (!upb_ok(&status)) {
zend_throw_exception_ex(NULL, 0,
"Error occurred during JSON serialization: %s",
upb_status_errmsg(&status));
return;
}
if (size >= sizeof(buf)) {
char *buf2 = malloc(size + 1);
upb_json_encode(intern->msg, intern->desc->msgdef,
DescriptorPool_GetSymbolTable(), options, buf2, size + 1,
&status);
RETVAL_STRINGL(buf2, size);
free(buf2);
} else {
RETVAL_STRINGL(buf, size);
}
}
/**
* Message::readWrapperValue()
*
* Returns an unboxed value for the given field. This is called from generated
* methods for wrapper fields, eg.
*
* public function getDoubleValueUnwrapped()
* {
* return $this->readWrapperValue("double_value");
* }
*
* @return Unwrapped field value or null.
*/
PHP_METHOD(Message, readWrapperValue) {
Message* intern = (Message*)Z_OBJ_P(getThis());
char* member;
const upb_fielddef *f;
zend_long size;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &member, &size) == FAILURE) {
return;
}
f = upb_msgdef_ntof(intern->desc->msgdef, member, size);
if (!f || !upb_msgdef_iswrapper(upb_fielddef_msgsubdef(f))) {
zend_throw_exception_ex(NULL, 0, "Message %s has no field %s",
upb_msgdef_fullname(intern->desc->msgdef), member);
return;
}
if (upb_msg_has(intern->msg, f)) {
const upb_msg *wrapper = upb_msg_get(intern->msg, f).msg_val;
const upb_msgdef *m = upb_fielddef_msgsubdef(f);
const upb_fielddef *val_f = upb_msgdef_itof(m, 1);
upb_msgval msgval = upb_msg_get(wrapper, val_f);
zval ret;
Convert_UpbToPhp(msgval, &ret, TypeInfo_Get(val_f), &intern->arena);
RETURN_ZVAL(&ret, 1, 0);
} else {
RETURN_NULL();
}
}
/**
* Message::writeWrapperValue()
*
* Sets the given wrapper field to the given unboxed value. This is called from
* generated methods for wrapper fields, eg.
*
*
* public function setDoubleValueUnwrapped($var)
* {
* $this->writeWrapperValue("double_value", $var);
* return $this;
* }
*
* @param Unwrapped field value or null.
*/
PHP_METHOD(Message, writeWrapperValue) {
Message* intern = (Message*)Z_OBJ_P(getThis());
upb_arena *arena = Arena_Get(&intern->arena);
char* member;
const upb_fielddef *f;
upb_msgval msgval;
zend_long size;
zval* val;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &member, &size, &val) ==
FAILURE) {
return;
}
f = upb_msgdef_ntof(intern->desc->msgdef, member, size);
if (!f || !upb_msgdef_iswrapper(upb_fielddef_msgsubdef(f))) {
zend_throw_exception_ex(NULL, 0, "Message %s has no field %s",
upb_msgdef_fullname(intern->desc->msgdef), member);
return;
}
if (Z_ISREF_P(val)) {
ZVAL_DEREF(val);
}
if (Z_TYPE_P(val) == IS_NULL) {
upb_msg_clearfield(intern->msg, f);
} else {
const upb_msgdef *m = upb_fielddef_msgsubdef(f);
const upb_fielddef *val_f = upb_msgdef_itof(m, 1);
upb_msg *wrapper;
if (!Convert_PhpToUpb(val, &msgval, TypeInfo_Get(val_f), arena)) {
return; // Error is already set.
}
wrapper = upb_msg_mutable(intern->msg, f, arena).msg;
upb_msg_set(wrapper, val_f, msgval, arena);
}
}
/**
* Message::whichOneof()
*
* Given a oneof name, returns the name of the field that is set for this oneof,
* or otherwise the empty string.
*
* @return string The field name in this oneof that is currently set.
*/
PHP_METHOD(Message, whichOneof) {
Message* intern = (Message*)Z_OBJ_P(getThis());
const upb_oneofdef* oneof;
const upb_fielddef* field;
char* name;
zend_long len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, &len) == FAILURE) {
return;
}
oneof = upb_msgdef_ntoo(intern->desc->msgdef, name, len);
if (!oneof) {
zend_throw_exception_ex(NULL, 0, "Message %s has no oneof %s",
upb_msgdef_fullname(intern->desc->msgdef), name);
return;
}
field = upb_msg_whichoneof(intern->msg, oneof);
RETURN_STRING(field ? upb_fielddef_name(field) : "");
}
/**
* Message::hasOneof()
*
* Returns the presence of the given oneof field, given a field number. Called
* from generated code methods such as:
*
* public function hasDoubleValueOneof()
* {
* return $this->hasOneof(10);
* }
*
* @return boolean
*/
PHP_METHOD(Message, hasOneof) {
Message* intern = (Message*)Z_OBJ_P(getThis());
zend_long field_num;
const upb_fielddef* f;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &field_num) == FAILURE) {
return;
}
f = upb_msgdef_itof(intern->desc->msgdef, field_num);
if (!f || !upb_fielddef_realcontainingoneof(f)) {
php_error_docref(NULL, E_USER_ERROR,
"Internal error, no such oneof field %d\n",
(int)field_num);
}
RETVAL_BOOL(upb_msg_has(intern->msg, f));
}
/**
* Message::readOneof()
*
* Returns the contents of the given oneof field, given a field number. Called
* from generated code methods such as:
*
* public function getDoubleValueOneof()
* {
* return $this->readOneof(10);
* }
*
* @return object The oneof's field value.
*/
PHP_METHOD(Message, readOneof) {
Message* intern = (Message*)Z_OBJ_P(getThis());
zend_long field_num;
const upb_fielddef* f;
zval ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &field_num) == FAILURE) {
return;
}
f = upb_msgdef_itof(intern->desc->msgdef, field_num);