Imported Upstream version 3.8.0
[platform/upstream/protobuf.git] / ruby / ext / google / protobuf_c / encode_decode.c
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2014 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 #include "protobuf.h"
32
33 // This function is equivalent to rb_str_cat(), but unlike the real
34 // rb_str_cat(), it doesn't leak memory in some versions of Ruby.
35 // For more information, see:
36 //   https://bugs.ruby-lang.org/issues/11328
37 VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
38   char *p;
39   size_t oldlen = RSTRING_LEN(rb_str);
40   rb_str_modify_expand(rb_str, len);
41   p = RSTRING_PTR(rb_str);
42   memcpy(p + oldlen, str, len);
43   rb_str_set_len(rb_str, oldlen + len);
44   return rb_str;
45 }
46
47 // The code below also comes from upb's prototype Ruby binding, developed by
48 // haberman@.
49
50 /* stringsink *****************************************************************/
51
52 static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
53   stringsink *sink = _sink;
54   sink->len = 0;
55   return sink;
56 }
57
58 static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
59                                 size_t len, const upb_bufhandle *handle) {
60   stringsink *sink = _sink;
61   size_t new_size = sink->size;
62
63   UPB_UNUSED(hd);
64   UPB_UNUSED(handle);
65
66   while (sink->len + len > new_size) {
67     new_size *= 2;
68   }
69
70   if (new_size != sink->size) {
71     sink->ptr = realloc(sink->ptr, new_size);
72     sink->size = new_size;
73   }
74
75   memcpy(sink->ptr + sink->len, ptr, len);
76   sink->len += len;
77
78   return len;
79 }
80
81 void stringsink_init(stringsink *sink) {
82   upb_byteshandler_init(&sink->handler);
83   upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
84   upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
85
86   upb_bytessink_reset(&sink->sink, &sink->handler, sink);
87
88   sink->size = 32;
89   sink->ptr = malloc(sink->size);
90   sink->len = 0;
91 }
92
93 void stringsink_uninit(stringsink *sink) {
94   free(sink->ptr);
95 }
96
97 // -----------------------------------------------------------------------------
98 // Parsing.
99 // -----------------------------------------------------------------------------
100
101 #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
102
103 typedef struct {
104   size_t ofs;
105   int32_t hasbit;
106 } field_handlerdata_t;
107
108 // Creates a handlerdata that contains the offset and the hasbit for the field
109 static const void* newhandlerdata(upb_handlers* h, uint32_t ofs, int32_t hasbit) {
110   field_handlerdata_t *hd = ALLOC(field_handlerdata_t);
111   hd->ofs = ofs;
112   hd->hasbit = hasbit;
113   upb_handlers_addcleanup(h, hd, xfree);
114   return hd;
115 }
116
117 typedef struct {
118   size_t ofs;
119   int32_t hasbit;
120   const upb_msgdef *md;
121 } submsg_handlerdata_t;
122
123 // Creates a handlerdata that contains offset and submessage type information.
124 static const void *newsubmsghandlerdata(upb_handlers* h,
125                                         uint32_t ofs,
126                                         int32_t hasbit,
127                                         const upb_fielddef* f) {
128   submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
129   hd->ofs = ofs;
130   hd->hasbit = hasbit;
131   hd->md = upb_fielddef_msgsubdef(f);
132   upb_handlers_addcleanup(h, hd, xfree);
133   return hd;
134 }
135
136 typedef struct {
137   size_t ofs;              // union data slot
138   size_t case_ofs;         // oneof_case field
139   uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
140   const upb_msgdef *md;    // msgdef, for oneof submessage handler
141 } oneof_handlerdata_t;
142
143 static const void *newoneofhandlerdata(upb_handlers *h,
144                                        uint32_t ofs,
145                                        uint32_t case_ofs,
146                                        const upb_fielddef *f) {
147   oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
148   hd->ofs = ofs;
149   hd->case_ofs = case_ofs;
150   // We reuse the field tag number as a oneof union discriminant tag. Note that
151   // we don't expose these numbers to the user, so the only requirement is that
152   // we have some unique ID for each union case/possibility. The field tag
153   // numbers are already present and are easy to use so there's no reason to
154   // create a separate ID space. In addition, using the field tag number here
155   // lets us easily look up the field in the oneof accessor.
156   hd->oneof_case_num = upb_fielddef_number(f);
157   if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
158     hd->md = upb_fielddef_msgsubdef(f);
159   } else {
160     hd->md = NULL;
161   }
162   upb_handlers_addcleanup(h, hd, xfree);
163   return hd;
164 }
165
166 // A handler that starts a repeated field.  Gets the Repeated*Field instance for
167 // this field (such an instance always exists even in an empty message).
168 static void *startseq_handler(void* closure, const void* hd) {
169   MessageHeader* msg = closure;
170   const size_t *ofs = hd;
171   return (void*)DEREF(msg, *ofs, VALUE);
172 }
173
174 // Handlers that append primitive values to a repeated field.
175 #define DEFINE_APPEND_HANDLER(type, ctype)                 \
176   static bool append##type##_handler(void *closure, const void *hd, \
177                                      ctype val) {                   \
178     VALUE ary = (VALUE)closure;                                     \
179     RepeatedField_push_native(ary, &val);                           \
180     return true;                                                    \
181   }
182
183 DEFINE_APPEND_HANDLER(bool,   bool)
184 DEFINE_APPEND_HANDLER(int32,  int32_t)
185 DEFINE_APPEND_HANDLER(uint32, uint32_t)
186 DEFINE_APPEND_HANDLER(float,  float)
187 DEFINE_APPEND_HANDLER(int64,  int64_t)
188 DEFINE_APPEND_HANDLER(uint64, uint64_t)
189 DEFINE_APPEND_HANDLER(double, double)
190
191 // Appends a string to a repeated field.
192 static void* appendstr_handler(void *closure,
193                                const void *hd,
194                                size_t size_hint) {
195   VALUE ary = (VALUE)closure;
196   VALUE str = rb_str_new2("");
197   rb_enc_associate(str, kRubyStringUtf8Encoding);
198   RepeatedField_push_native(ary, &str);
199   return (void*)str;
200 }
201
202 static void set_hasbit(void *closure, int32_t hasbit) {
203   if (hasbit > 0) {
204     uint8_t* storage = closure;
205     storage[hasbit/8] |= 1 << (hasbit % 8);
206   }
207 }
208
209 // Appends a 'bytes' string to a repeated field.
210 static void* appendbytes_handler(void *closure,
211                                  const void *hd,
212                                  size_t size_hint) {
213   VALUE ary = (VALUE)closure;
214   VALUE str = rb_str_new2("");
215   rb_enc_associate(str, kRubyString8bitEncoding);
216   RepeatedField_push_native(ary, &str);
217   return (void*)str;
218 }
219
220 // Sets a non-repeated string field in a message.
221 static void* str_handler(void *closure,
222                          const void *hd,
223                          size_t size_hint) {
224   MessageHeader* msg = closure;
225   const field_handlerdata_t *fieldhandler = hd;
226
227   VALUE str = rb_str_new2("");
228   rb_enc_associate(str, kRubyStringUtf8Encoding);
229   DEREF(msg, fieldhandler->ofs, VALUE) = str;
230   set_hasbit(closure, fieldhandler->hasbit);
231   return (void*)str;
232 }
233
234 // Sets a non-repeated 'bytes' field in a message.
235 static void* bytes_handler(void *closure,
236                            const void *hd,
237                            size_t size_hint) {
238   MessageHeader* msg = closure;
239   const field_handlerdata_t *fieldhandler = hd;
240
241   VALUE str = rb_str_new2("");
242   rb_enc_associate(str, kRubyString8bitEncoding);
243   DEREF(msg, fieldhandler->ofs, VALUE) = str;
244   set_hasbit(closure, fieldhandler->hasbit);
245   return (void*)str;
246 }
247
248 static size_t stringdata_handler(void* closure, const void* hd,
249                                  const char* str, size_t len,
250                                  const upb_bufhandle* handle) {
251   VALUE rb_str = (VALUE)closure;
252   noleak_rb_str_cat(rb_str, str, len);
253   return len;
254 }
255
256 static bool stringdata_end_handler(void* closure, const void* hd) {
257   VALUE rb_str = closure;
258   rb_obj_freeze(rb_str);
259   return true;
260 }
261
262 static bool appendstring_end_handler(void* closure, const void* hd) {
263   VALUE rb_str = closure;
264   rb_obj_freeze(rb_str);
265   return true;
266 }
267
268 // Appends a submessage to a repeated field (a regular Ruby array for now).
269 static void *appendsubmsg_handler(void *closure, const void *hd) {
270   VALUE ary = (VALUE)closure;
271   const submsg_handlerdata_t *submsgdata = hd;
272   VALUE subdesc =
273       get_def_obj((void*)submsgdata->md);
274   VALUE subklass = Descriptor_msgclass(subdesc);
275   MessageHeader* submsg;
276
277   VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
278   RepeatedField_push(ary, submsg_rb);
279
280   TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
281   return submsg;
282 }
283
284 // Sets a non-repeated submessage field in a message.
285 static void *submsg_handler(void *closure, const void *hd) {
286   MessageHeader* msg = closure;
287   const submsg_handlerdata_t* submsgdata = hd;
288   VALUE subdesc =
289       get_def_obj((void*)submsgdata->md);
290   VALUE subklass = Descriptor_msgclass(subdesc);
291   VALUE submsg_rb;
292   MessageHeader* submsg;
293
294   if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
295     DEREF(msg, submsgdata->ofs, VALUE) =
296         rb_class_new_instance(0, NULL, subklass);
297   }
298
299   set_hasbit(closure, submsgdata->hasbit);
300
301   submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
302   TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
303
304   return submsg;
305 }
306
307 // Handler data for startmap/endmap handlers.
308 typedef struct {
309   size_t ofs;
310   upb_fieldtype_t key_field_type;
311   upb_fieldtype_t value_field_type;
312
313   // We know that we can hold this reference because the handlerdata has the
314   // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
315   // a reference to the upb_msgdef, which in turn has references to its subdefs.
316   const upb_def* value_field_subdef;
317 } map_handlerdata_t;
318
319 // Temporary frame for map parsing: at the beginning of a map entry message, a
320 // submsg handler allocates a frame to hold (i) a reference to the Map object
321 // into which this message will be inserted and (ii) storage slots to
322 // temporarily hold the key and value for this map entry until the end of the
323 // submessage. When the submessage ends, another handler is called to insert the
324 // value into the map.
325 typedef struct {
326   VALUE map;
327   const map_handlerdata_t* handlerdata;
328   char key_storage[NATIVE_SLOT_MAX_SIZE];
329   char value_storage[NATIVE_SLOT_MAX_SIZE];
330 } map_parse_frame_t;
331
332 static void MapParseFrame_mark(void* _self) {
333   map_parse_frame_t* frame = _self;
334
335   // This shouldn't strictly be necessary since this should be rooted by the
336   // message itself, but it can't hurt.
337   rb_gc_mark(frame->map);
338
339   native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
340   native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
341 }
342
343 void MapParseFrame_free(void* self) {
344   xfree(self);
345 }
346
347 rb_data_type_t MapParseFrame_type = {
348   "MapParseFrame",
349   { MapParseFrame_mark, MapParseFrame_free, NULL },
350 };
351
352 static map_parse_frame_t* map_push_frame(VALUE map,
353                                          const map_handlerdata_t* handlerdata) {
354   map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
355   frame->handlerdata = handlerdata;
356   frame->map = map;
357   native_slot_init(handlerdata->key_field_type, &frame->key_storage);
358   native_slot_init(handlerdata->value_field_type, &frame->value_storage);
359
360   Map_set_frame(map,
361               TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
362
363   return frame;
364 }
365
366 // Handler to begin a map entry: allocates a temporary frame. This is the
367 // 'startsubmsg' handler on the msgdef that contains the map field.
368 static void *startmapentry_handler(void *closure, const void *hd) {
369   MessageHeader* msg = closure;
370   const map_handlerdata_t* mapdata = hd;
371   VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
372
373   return map_push_frame(map_rb, mapdata);
374 }
375
376 // Handler to end a map entry: inserts the value defined during the message into
377 // the map. This is the 'endmsg' handler on the map entry msgdef.
378 static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
379   map_parse_frame_t* frame = closure;
380   const map_handlerdata_t* mapdata = hd;
381
382   VALUE key = native_slot_get(
383       mapdata->key_field_type, Qnil,
384       &frame->key_storage);
385
386   VALUE value_field_typeclass = Qnil;
387   VALUE value;
388
389   if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
390       mapdata->value_field_type == UPB_TYPE_ENUM) {
391     value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
392   }
393
394   value = native_slot_get(
395       mapdata->value_field_type, value_field_typeclass,
396       &frame->value_storage);
397
398   Map_index_set(frame->map, key, value);
399   Map_set_frame(frame->map, Qnil);
400
401   return true;
402 }
403
404 // Allocates a new map_handlerdata_t given the map entry message definition. If
405 // the offset of the field within the parent message is also given, that is
406 // added to the handler data as well. Note that this is called *twice* per map
407 // field: once in the parent message handler setup when setting the startsubmsg
408 // handler and once in the map entry message handler setup when setting the
409 // key/value and endmsg handlers. The reason is that there is no easy way to
410 // pass the handlerdata down to the sub-message handler setup.
411 static map_handlerdata_t* new_map_handlerdata(
412     size_t ofs,
413     const upb_msgdef* mapentry_def,
414     Descriptor* desc) {
415   const upb_fielddef* key_field;
416   const upb_fielddef* value_field;
417   map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
418   hd->ofs = ofs;
419   key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
420   assert(key_field != NULL);
421   hd->key_field_type = upb_fielddef_type(key_field);
422   value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
423   assert(value_field != NULL);
424   hd->value_field_type = upb_fielddef_type(value_field);
425   hd->value_field_subdef = upb_fielddef_subdef(value_field);
426
427   return hd;
428 }
429
430 // Handlers that set primitive values in oneofs.
431 #define DEFINE_ONEOF_HANDLER(type, ctype)                           \
432   static bool oneof##type##_handler(void *closure, const void *hd,  \
433                                      ctype val) {                   \
434     const oneof_handlerdata_t *oneofdata = hd;                      \
435     DEREF(closure, oneofdata->case_ofs, uint32_t) =                 \
436         oneofdata->oneof_case_num;                                  \
437     DEREF(closure, oneofdata->ofs, ctype) = val;                    \
438     return true;                                                    \
439   }
440
441 DEFINE_ONEOF_HANDLER(bool,   bool)
442 DEFINE_ONEOF_HANDLER(int32,  int32_t)
443 DEFINE_ONEOF_HANDLER(uint32, uint32_t)
444 DEFINE_ONEOF_HANDLER(float,  float)
445 DEFINE_ONEOF_HANDLER(int64,  int64_t)
446 DEFINE_ONEOF_HANDLER(uint64, uint64_t)
447 DEFINE_ONEOF_HANDLER(double, double)
448
449 #undef DEFINE_ONEOF_HANDLER
450
451 // Handlers for strings in a oneof.
452 static void *oneofstr_handler(void *closure,
453                               const void *hd,
454                               size_t size_hint) {
455   MessageHeader* msg = closure;
456   const oneof_handlerdata_t *oneofdata = hd;
457   VALUE str = rb_str_new2("");
458   rb_enc_associate(str, kRubyStringUtf8Encoding);
459   DEREF(msg, oneofdata->case_ofs, uint32_t) =
460       oneofdata->oneof_case_num;
461   DEREF(msg, oneofdata->ofs, VALUE) = str;
462   return (void*)str;
463 }
464
465 static void *oneofbytes_handler(void *closure,
466                                 const void *hd,
467                                 size_t size_hint) {
468   MessageHeader* msg = closure;
469   const oneof_handlerdata_t *oneofdata = hd;
470   VALUE str = rb_str_new2("");
471   rb_enc_associate(str, kRubyString8bitEncoding);
472   DEREF(msg, oneofdata->case_ofs, uint32_t) =
473       oneofdata->oneof_case_num;
474   DEREF(msg, oneofdata->ofs, VALUE) = str;
475   return (void*)str;
476 }
477
478 static bool oneofstring_end_handler(void* closure, const void* hd) {
479   VALUE rb_str = rb_str_new2("");
480   rb_obj_freeze(rb_str);
481   return true;
482 }
483
484 // Handler for a submessage field in a oneof.
485 static void *oneofsubmsg_handler(void *closure,
486                                  const void *hd) {
487   MessageHeader* msg = closure;
488   const oneof_handlerdata_t *oneofdata = hd;
489   uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
490
491   VALUE subdesc =
492       get_def_obj((void*)oneofdata->md);
493   VALUE subklass = Descriptor_msgclass(subdesc);
494   VALUE submsg_rb;
495   MessageHeader* submsg;
496
497   if (oldcase != oneofdata->oneof_case_num ||
498       DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
499     DEREF(msg, oneofdata->ofs, VALUE) =
500         rb_class_new_instance(0, NULL, subklass);
501   }
502   // Set the oneof case *after* allocating the new class instance -- otherwise,
503   // if the Ruby GC is invoked as part of a call into the VM, it might invoke
504   // our mark routines, and our mark routines might see the case value
505   // indicating a VALUE is present and expect a valid VALUE. See comment in
506   // layout_set() for more detail: basically, the change to the value and the
507   // case must be atomic w.r.t. the Ruby VM.
508   DEREF(msg, oneofdata->case_ofs, uint32_t) =
509       oneofdata->oneof_case_num;
510
511   submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
512   TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
513   return submsg;
514 }
515
516 // Set up handlers for a repeated field.
517 static void add_handlers_for_repeated_field(upb_handlers *h,
518                                             const upb_fielddef *f,
519                                             size_t offset) {
520   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
521   upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, -1));
522   upb_handlers_setstartseq(h, f, startseq_handler, &attr);
523   upb_handlerattr_uninit(&attr);
524
525   switch (upb_fielddef_type(f)) {
526
527 #define SET_HANDLER(utype, ltype)                                 \
528   case utype:                                                     \
529     upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
530     break;
531
532     SET_HANDLER(UPB_TYPE_BOOL,   bool);
533     SET_HANDLER(UPB_TYPE_INT32,  int32);
534     SET_HANDLER(UPB_TYPE_UINT32, uint32);
535     SET_HANDLER(UPB_TYPE_ENUM,   int32);
536     SET_HANDLER(UPB_TYPE_FLOAT,  float);
537     SET_HANDLER(UPB_TYPE_INT64,  int64);
538     SET_HANDLER(UPB_TYPE_UINT64, uint64);
539     SET_HANDLER(UPB_TYPE_DOUBLE, double);
540
541 #undef SET_HANDLER
542
543     case UPB_TYPE_STRING:
544     case UPB_TYPE_BYTES: {
545       bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
546       upb_handlers_setstartstr(h, f, is_bytes ?
547                                appendbytes_handler : appendstr_handler,
548                                NULL);
549       upb_handlers_setstring(h, f, stringdata_handler, NULL);
550       upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
551       break;
552     }
553     case UPB_TYPE_MESSAGE: {
554       upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
555       upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, -1, f));
556       upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
557       upb_handlerattr_uninit(&attr);
558       break;
559     }
560   }
561 }
562
563 // Set up handlers for a singular field.
564 static void add_handlers_for_singular_field(upb_handlers *h,
565                                             const upb_fielddef *f,
566                                             size_t offset,
567                                             size_t hasbit_off) {
568   // The offset we pass to UPB points to the start of the Message,
569   // rather than the start of where our data is stored.
570   int32_t hasbit = -1;
571   if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
572     hasbit = hasbit_off + sizeof(MessageHeader) * 8;
573   }
574
575   switch (upb_fielddef_type(f)) {
576     case UPB_TYPE_BOOL:
577     case UPB_TYPE_INT32:
578     case UPB_TYPE_UINT32:
579     case UPB_TYPE_ENUM:
580     case UPB_TYPE_FLOAT:
581     case UPB_TYPE_INT64:
582     case UPB_TYPE_UINT64:
583     case UPB_TYPE_DOUBLE:
584       upb_msg_setscalarhandler(h, f, offset, hasbit);
585       break;
586     case UPB_TYPE_STRING:
587     case UPB_TYPE_BYTES: {
588       bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
589       upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
590       upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, hasbit));
591       upb_handlers_setstartstr(h, f,
592                                is_bytes ? bytes_handler : str_handler,
593                                &attr);
594       upb_handlers_setstring(h, f, stringdata_handler, &attr);
595       upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
596       upb_handlerattr_uninit(&attr);
597       break;
598     }
599     case UPB_TYPE_MESSAGE: {
600       upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
601       upb_handlerattr_sethandlerdata(&attr,
602                                      newsubmsghandlerdata(h, offset,
603                                                           hasbit, f));
604       upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
605       upb_handlerattr_uninit(&attr);
606       break;
607     }
608   }
609 }
610
611 // Adds handlers to a map field.
612 static void add_handlers_for_mapfield(upb_handlers* h,
613                                       const upb_fielddef* fielddef,
614                                       size_t offset,
615                                       Descriptor* desc) {
616   const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
617   map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
618   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
619
620   upb_handlers_addcleanup(h, hd, xfree);
621   upb_handlerattr_sethandlerdata(&attr, hd);
622   upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
623   upb_handlerattr_uninit(&attr);
624 }
625
626 // Adds handlers to a map-entry msgdef.
627 static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
628                                       upb_handlers* h,
629                                       Descriptor* desc) {
630   const upb_fielddef* key_field = map_entry_key(msgdef);
631   const upb_fielddef* value_field = map_entry_value(msgdef);
632   map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
633   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
634
635   upb_handlers_addcleanup(h, hd, xfree);
636   upb_handlerattr_sethandlerdata(&attr, hd);
637   upb_handlers_setendmsg(h, endmap_handler, &attr);
638
639   add_handlers_for_singular_field(
640       h, key_field,
641       offsetof(map_parse_frame_t, key_storage),
642       MESSAGE_FIELD_NO_HASBIT);
643   add_handlers_for_singular_field(
644       h, value_field,
645       offsetof(map_parse_frame_t, value_storage),
646       MESSAGE_FIELD_NO_HASBIT);
647 }
648
649 // Set up handlers for a oneof field.
650 static void add_handlers_for_oneof_field(upb_handlers *h,
651                                          const upb_fielddef *f,
652                                          size_t offset,
653                                          size_t oneof_case_offset) {
654
655   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
656   upb_handlerattr_sethandlerdata(
657       &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
658
659   switch (upb_fielddef_type(f)) {
660
661 #define SET_HANDLER(utype, ltype)                                 \
662   case utype:                                                     \
663     upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
664     break;
665
666     SET_HANDLER(UPB_TYPE_BOOL,   bool);
667     SET_HANDLER(UPB_TYPE_INT32,  int32);
668     SET_HANDLER(UPB_TYPE_UINT32, uint32);
669     SET_HANDLER(UPB_TYPE_ENUM,   int32);
670     SET_HANDLER(UPB_TYPE_FLOAT,  float);
671     SET_HANDLER(UPB_TYPE_INT64,  int64);
672     SET_HANDLER(UPB_TYPE_UINT64, uint64);
673     SET_HANDLER(UPB_TYPE_DOUBLE, double);
674
675 #undef SET_HANDLER
676
677     case UPB_TYPE_STRING:
678     case UPB_TYPE_BYTES: {
679       bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
680       upb_handlers_setstartstr(h, f, is_bytes ?
681                                oneofbytes_handler : oneofstr_handler,
682                                &attr);
683       upb_handlers_setstring(h, f, stringdata_handler, NULL);
684       upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
685       break;
686     }
687     case UPB_TYPE_MESSAGE: {
688       upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
689       break;
690     }
691   }
692
693   upb_handlerattr_uninit(&attr);
694 }
695
696 static bool unknown_field_handler(void* closure, const void* hd,
697                                   const char* buf, size_t size) {
698   UPB_UNUSED(hd);
699
700   MessageHeader* msg = (MessageHeader*)closure;
701   if (msg->unknown_fields == NULL) {
702     msg->unknown_fields = malloc(sizeof(stringsink));
703     stringsink_init(msg->unknown_fields);
704   }
705
706   stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
707
708   return true;
709 }
710
711 static void add_handlers_for_message(const void *closure, upb_handlers *h) {
712   const upb_msgdef* msgdef = upb_handlers_msgdef(h);
713   Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
714   upb_msg_field_iter i;
715
716   // If this is a mapentry message type, set up a special set of handlers and
717   // bail out of the normal (user-defined) message type handling.
718   if (upb_msgdef_mapentry(msgdef)) {
719     add_handlers_for_mapentry(msgdef, h, desc);
720     return;
721   }
722
723   // Ensure layout exists. We may be invoked to create handlers for a given
724   // message if we are included as a submsg of another message type before our
725   // class is actually built, so to work around this, we just create the layout
726   // (and handlers, in the class-building function) on-demand.
727   if (desc->layout == NULL) {
728     desc->layout = create_layout(desc->msgdef);
729   }
730
731   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
732   upb_handlers_setunknown(h, unknown_field_handler, &attr);
733
734   for (upb_msg_field_begin(&i, desc->msgdef);
735        !upb_msg_field_done(&i);
736        upb_msg_field_next(&i)) {
737     const upb_fielddef *f = upb_msg_iter_field(&i);
738     size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
739         sizeof(MessageHeader);
740
741     if (upb_fielddef_containingoneof(f)) {
742       size_t oneof_case_offset =
743           desc->layout->fields[upb_fielddef_index(f)].case_offset +
744           sizeof(MessageHeader);
745       add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
746     } else if (is_map_field(f)) {
747       add_handlers_for_mapfield(h, f, offset, desc);
748     } else if (upb_fielddef_isseq(f)) {
749       add_handlers_for_repeated_field(h, f, offset);
750     } else {
751       add_handlers_for_singular_field(
752           h, f, offset, desc->layout->fields[upb_fielddef_index(f)].hasbit);
753     }
754   }
755 }
756
757 // Creates upb handlers for populating a message.
758 static const upb_handlers *new_fill_handlers(Descriptor* desc,
759                                              const void* owner) {
760   // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
761   // handlers, reuse subdef handlers so that e.g. if we already parse
762   // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
763   // parse A-with-field-of-type-B-with-field-of-type-C.
764   return upb_handlers_newfrozen(desc->msgdef, owner,
765                                 add_handlers_for_message, NULL);
766 }
767
768 // Constructs the handlers for filling a message's data into an in-memory
769 // object.
770 const upb_handlers* get_fill_handlers(Descriptor* desc) {
771   if (!desc->fill_handlers) {
772     desc->fill_handlers =
773         new_fill_handlers(desc, &desc->fill_handlers);
774   }
775   return desc->fill_handlers;
776 }
777
778 // Constructs the upb decoder method for parsing messages of this type.
779 // This is called from the message class creation code.
780 const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
781                                                      const void* owner) {
782   const upb_handlers* handlers = get_fill_handlers(desc);
783   upb_pbdecodermethodopts opts;
784   upb_pbdecodermethodopts_init(&opts, handlers);
785
786   return upb_pbdecodermethod_new(&opts, owner);
787 }
788
789 static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
790   if (desc->fill_method == NULL) {
791     desc->fill_method = new_fillmsg_decodermethod(
792         desc, &desc->fill_method);
793   }
794   return desc->fill_method;
795 }
796
797 static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
798   if (desc->json_fill_method == NULL) {
799     desc->json_fill_method =
800         upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
801   }
802   return desc->json_fill_method;
803 }
804
805
806 // Stack-allocated context during an encode/decode operation. Contains the upb
807 // environment and its stack-based allocator, an initial buffer for allocations
808 // to avoid malloc() when possible, and a template for Ruby exception messages
809 // if any error occurs.
810 #define STACK_ENV_STACKBYTES 4096
811 typedef struct {
812   upb_env env;
813   const char* ruby_error_template;
814   char allocbuf[STACK_ENV_STACKBYTES];
815 } stackenv;
816
817 static void stackenv_init(stackenv* se, const char* errmsg);
818 static void stackenv_uninit(stackenv* se);
819
820 // Callback invoked by upb if any error occurs during parsing or serialization.
821 static bool env_error_func(void* ud, const upb_status* status) {
822   stackenv* se = ud;
823   // Free the env -- rb_raise will longjmp up the stack past the encode/decode
824   // function so it would not otherwise have been freed.
825   stackenv_uninit(se);
826
827   // TODO(haberman): have a way to verify that this is actually a parse error,
828   // instead of just throwing "parse error" unconditionally.
829   rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
830   // Never reached: rb_raise() always longjmp()s up the stack, past all of our
831   // code, back to Ruby.
832   return false;
833 }
834
835 static void stackenv_init(stackenv* se, const char* errmsg) {
836   se->ruby_error_template = errmsg;
837   upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
838   upb_env_seterrorfunc(&se->env, env_error_func, se);
839 }
840
841 static void stackenv_uninit(stackenv* se) {
842   upb_env_uninit(&se->env);
843 }
844
845 /*
846  * call-seq:
847  *     MessageClass.decode(data) => message
848  *
849  * Decodes the given data (as a string containing bytes in protocol buffers wire
850  * format) under the interpretration given by this message class's definition
851  * and returns a message object with the corresponding field values.
852  */
853 VALUE Message_decode(VALUE klass, VALUE data) {
854   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
855   Descriptor* desc = ruby_to_Descriptor(descriptor);
856   VALUE msgklass = Descriptor_msgclass(descriptor);
857   VALUE msg_rb;
858   MessageHeader* msg;
859
860   if (TYPE(data) != T_STRING) {
861     rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
862   }
863
864   msg_rb = rb_class_new_instance(0, NULL, msgklass);
865   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
866
867   {
868     const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
869     const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
870     stackenv se;
871     upb_sink sink;
872     upb_pbdecoder* decoder;
873     stackenv_init(&se, "Error occurred during parsing: %s");
874
875     upb_sink_reset(&sink, h, msg);
876     decoder = upb_pbdecoder_create(&se.env, method, &sink);
877     upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
878                       upb_pbdecoder_input(decoder));
879
880     stackenv_uninit(&se);
881   }
882
883   return msg_rb;
884 }
885
886 /*
887  * call-seq:
888  *     MessageClass.decode_json(data, options = {}) => message
889  *
890  * Decodes the given data (as a string containing bytes in protocol buffers wire
891  * format) under the interpretration given by this message class's definition
892  * and returns a message object with the corresponding field values.
893  *
894  * @param options [Hash] options for the decoder
895  *   ignore_unknown_fields: set true to ignore unknown fields (default is to raise an error)
896  */
897 VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
898   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
899   Descriptor* desc = ruby_to_Descriptor(descriptor);
900   VALUE msgklass = Descriptor_msgclass(descriptor);
901   VALUE msg_rb;
902   VALUE data = argv[0];
903   VALUE ignore_unknown_fields = Qfalse;
904   MessageHeader* msg;
905
906   if (argc < 1 || argc > 2) {
907     rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
908   }
909
910   if (argc == 2) {
911     VALUE hash_args = argv[1];
912     if (TYPE(hash_args) != T_HASH) {
913       rb_raise(rb_eArgError, "Expected hash arguments.");
914     }
915
916     ignore_unknown_fields = rb_hash_lookup2(
917         hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
918   }
919
920   if (TYPE(data) != T_STRING) {
921     rb_raise(rb_eArgError, "Expected string for JSON data.");
922   }
923   // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
924   // convert, because string handlers pass data directly to message string
925   // fields.
926
927   msg_rb = rb_class_new_instance(0, NULL, msgklass);
928   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
929
930   {
931     const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
932     stackenv se;
933     upb_sink sink;
934     upb_json_parser* parser;
935     DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
936     stackenv_init(&se, "Error occurred during parsing: %s");
937
938     upb_sink_reset(&sink, get_fill_handlers(desc), msg);
939     parser = upb_json_parser_create(&se.env, method, pool->symtab,
940                                     &sink, ignore_unknown_fields);
941     upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
942                       upb_json_parser_input(parser));
943
944     stackenv_uninit(&se);
945   }
946
947   return msg_rb;
948 }
949
950 // -----------------------------------------------------------------------------
951 // Serializing.
952 // -----------------------------------------------------------------------------
953
954 /* msgvisitor *****************************************************************/
955
956 static void putmsg(VALUE msg, const Descriptor* desc,
957                    upb_sink *sink, int depth, bool emit_defaults,
958                    bool is_json, bool open_msg);
959
960 static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
961   upb_selector_t ret;
962   bool ok = upb_handlers_getselector(f, type, &ret);
963   UPB_ASSERT(ok);
964   return ret;
965 }
966
967 static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
968   upb_sink subsink;
969
970   if (str == Qnil) return;
971
972   assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
973
974   // We should be guaranteed that the string has the correct encoding because
975   // we ensured this at assignment time and then froze the string.
976   if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
977     assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
978   } else {
979     assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
980   }
981
982   upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
983                     &subsink);
984   upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
985                      RSTRING_LEN(str), NULL);
986   upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
987 }
988
989 static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
990                       int depth, bool emit_defaults, bool is_json) {
991   upb_sink subsink;
992   VALUE descriptor;
993   Descriptor* subdesc;
994
995   if (submsg == Qnil) return;
996
997   descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
998   subdesc = ruby_to_Descriptor(descriptor);
999
1000   upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
1001   putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults, is_json, true);
1002   upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1003 }
1004
1005 static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
1006                    int depth, bool emit_defaults, bool is_json) {
1007   upb_sink subsink;
1008   upb_fieldtype_t type = upb_fielddef_type(f);
1009   upb_selector_t sel = 0;
1010   int size;
1011
1012   if (ary == Qnil) return;
1013   if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
1014
1015   size = NUM2INT(RepeatedField_length(ary));
1016   if (size == 0 && !emit_defaults) return;
1017
1018   upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1019
1020   if (upb_fielddef_isprimitive(f)) {
1021     sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1022   }
1023
1024   for (int i = 0; i < size; i++) {
1025     void* memory = RepeatedField_index_native(ary, i);
1026     switch (type) {
1027 #define T(upbtypeconst, upbtype, ctype)                         \
1028   case upbtypeconst:                                            \
1029     upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory));   \
1030     break;
1031
1032       T(UPB_TYPE_FLOAT,  float,  float)
1033       T(UPB_TYPE_DOUBLE, double, double)
1034       T(UPB_TYPE_BOOL,   bool,   int8_t)
1035       case UPB_TYPE_ENUM:
1036       T(UPB_TYPE_INT32,  int32,  int32_t)
1037       T(UPB_TYPE_UINT32, uint32, uint32_t)
1038       T(UPB_TYPE_INT64,  int64,  int64_t)
1039       T(UPB_TYPE_UINT64, uint64, uint64_t)
1040
1041       case UPB_TYPE_STRING:
1042       case UPB_TYPE_BYTES:
1043         putstr(*((VALUE *)memory), f, &subsink);
1044         break;
1045       case UPB_TYPE_MESSAGE:
1046         putsubmsg(*((VALUE *)memory), f, &subsink, depth,
1047                   emit_defaults, is_json);
1048         break;
1049
1050 #undef T
1051
1052     }
1053   }
1054   upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1055 }
1056
1057 static void put_ruby_value(VALUE value,
1058                            const upb_fielddef *f,
1059                            VALUE type_class,
1060                            int depth,
1061                            upb_sink *sink,
1062                            bool emit_defaults,
1063                            bool is_json) {
1064   if (depth > ENCODE_MAX_NESTING) {
1065     rb_raise(rb_eRuntimeError,
1066              "Maximum recursion depth exceeded during encoding.");
1067   }
1068
1069   upb_selector_t sel = 0;
1070   if (upb_fielddef_isprimitive(f)) {
1071     sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1072   }
1073
1074   switch (upb_fielddef_type(f)) {
1075     case UPB_TYPE_INT32:
1076       upb_sink_putint32(sink, sel, NUM2INT(value));
1077       break;
1078     case UPB_TYPE_INT64:
1079       upb_sink_putint64(sink, sel, NUM2LL(value));
1080       break;
1081     case UPB_TYPE_UINT32:
1082       upb_sink_putuint32(sink, sel, NUM2UINT(value));
1083       break;
1084     case UPB_TYPE_UINT64:
1085       upb_sink_putuint64(sink, sel, NUM2ULL(value));
1086       break;
1087     case UPB_TYPE_FLOAT:
1088       upb_sink_putfloat(sink, sel, NUM2DBL(value));
1089       break;
1090     case UPB_TYPE_DOUBLE:
1091       upb_sink_putdouble(sink, sel, NUM2DBL(value));
1092       break;
1093     case UPB_TYPE_ENUM: {
1094       if (TYPE(value) == T_SYMBOL) {
1095         value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
1096       }
1097       upb_sink_putint32(sink, sel, NUM2INT(value));
1098       break;
1099     }
1100     case UPB_TYPE_BOOL:
1101       upb_sink_putbool(sink, sel, value == Qtrue);
1102       break;
1103     case UPB_TYPE_STRING:
1104     case UPB_TYPE_BYTES:
1105       putstr(value, f, sink);
1106       break;
1107     case UPB_TYPE_MESSAGE:
1108       putsubmsg(value, f, sink, depth, emit_defaults, is_json);
1109   }
1110 }
1111
1112 static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
1113                    int depth, bool emit_defaults, bool is_json) {
1114   Map* self;
1115   upb_sink subsink;
1116   const upb_fielddef* key_field;
1117   const upb_fielddef* value_field;
1118   Map_iter it;
1119
1120   if (map == Qnil) return;
1121   if (!emit_defaults && Map_length(map) == 0) return;
1122
1123   self = ruby_to_Map(map);
1124
1125   upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1126
1127   assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1128   key_field = map_field_key(f);
1129   value_field = map_field_value(f);
1130
1131   for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
1132     VALUE key = Map_iter_key(&it);
1133     VALUE value = Map_iter_value(&it);
1134     upb_status status;
1135
1136     upb_sink entry_sink;
1137     upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
1138                          &entry_sink);
1139     upb_sink_startmsg(&entry_sink);
1140
1141     put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink,
1142                    emit_defaults, is_json);
1143     put_ruby_value(value, value_field, self->value_type_class, depth + 1,
1144                    &entry_sink, emit_defaults, is_json);
1145
1146     upb_sink_endmsg(&entry_sink, &status);
1147     upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1148   }
1149
1150   upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1151 }
1152
1153 static const upb_handlers* msgdef_json_serialize_handlers(
1154     Descriptor* desc, bool preserve_proto_fieldnames);
1155
1156 static void putjsonany(VALUE msg_rb, const Descriptor* desc,
1157                        upb_sink* sink, int depth, bool emit_defaults) {
1158   upb_status status;
1159   MessageHeader* msg = NULL;
1160   const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
1161   const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
1162
1163   size_t type_url_offset;
1164   VALUE type_url_str_rb;
1165   const upb_msgdef *payload_type = NULL;
1166
1167   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1168
1169   upb_sink_startmsg(sink);
1170
1171   /* Handle type url */
1172   type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
1173   type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
1174   if (RSTRING_LEN(type_url_str_rb) > 0) {
1175     putstr(type_url_str_rb, type_field, sink);
1176   }
1177
1178   {
1179     const char* type_url_str = RSTRING_PTR(type_url_str_rb);
1180     size_t type_url_len = RSTRING_LEN(type_url_str_rb);
1181     DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
1182
1183     if (type_url_len <= 20 ||
1184         strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
1185       rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
1186       return;
1187     }
1188
1189     /* Resolve type url */
1190     type_url_str += 20;
1191     type_url_len -= 20;
1192
1193     payload_type = upb_symtab_lookupmsg2(
1194         pool->symtab, type_url_str, type_url_len);
1195     if (payload_type == NULL) {
1196       rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
1197       return;
1198     }
1199   }
1200
1201   {
1202     uint32_t value_offset;
1203     VALUE value_str_rb;
1204     const char* value_str;
1205     size_t value_len;
1206
1207     value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
1208     value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
1209     value_str = RSTRING_PTR(value_str_rb);
1210     value_len = RSTRING_LEN(value_str_rb);
1211
1212     if (value_len > 0) {
1213       VALUE payload_desc_rb = get_def_obj(payload_type);
1214       Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
1215       VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
1216       upb_sink subsink;
1217       bool is_wellknown;
1218
1219       VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
1220
1221       is_wellknown =
1222           upb_msgdef_wellknowntype(payload_desc->msgdef) !=
1223               UPB_WELLKNOWN_UNSPECIFIED;
1224       if (is_wellknown) {
1225         upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
1226                           &subsink);
1227       }
1228
1229       subsink.handlers =
1230           msgdef_json_serialize_handlers(payload_desc, true);
1231       subsink.closure = sink->closure;
1232       putmsg(payload_msg_rb, payload_desc, &subsink, depth, emit_defaults, true,
1233              is_wellknown);
1234     }
1235   }
1236
1237   upb_sink_endmsg(sink, &status);
1238 }
1239
1240 static void putjsonlistvalue(
1241     VALUE msg_rb, const Descriptor* desc,
1242     upb_sink* sink, int depth, bool emit_defaults) {
1243   upb_status status;
1244   upb_sink subsink;
1245   MessageHeader* msg = NULL;
1246   const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
1247   uint32_t offset =
1248       desc->layout->fields[upb_fielddef_index(f)].offset +
1249       sizeof(MessageHeader);
1250   VALUE ary;
1251
1252   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1253
1254   upb_sink_startmsg(sink);
1255
1256   ary = DEREF(msg, offset, VALUE);
1257
1258   if (ary == Qnil || RepeatedField_size(ary) == 0) {
1259     upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1260     upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1261   } else {
1262     putary(ary, f, sink, depth, emit_defaults, true);
1263   }
1264
1265   upb_sink_endmsg(sink, &status);
1266 }
1267
1268 static void putmsg(VALUE msg_rb, const Descriptor* desc,
1269                    upb_sink *sink, int depth, bool emit_defaults,
1270                    bool is_json, bool open_msg) {
1271   MessageHeader* msg;
1272   upb_msg_field_iter i;
1273   upb_status status;
1274
1275   if (is_json &&
1276       upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
1277     putjsonany(msg_rb, desc, sink, depth, emit_defaults);
1278     return;
1279   }
1280
1281   if (is_json &&
1282       upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
1283     putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
1284     return;
1285   }
1286
1287   if (open_msg) {
1288     upb_sink_startmsg(sink);
1289   }
1290
1291   // Protect against cycles (possible because users may freely reassign message
1292   // and repeated fields) by imposing a maximum recursion depth.
1293   if (depth > ENCODE_MAX_NESTING) {
1294     rb_raise(rb_eRuntimeError,
1295              "Maximum recursion depth exceeded during encoding.");
1296   }
1297
1298   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1299
1300   if (desc != msg->descriptor) {
1301     rb_raise(rb_eArgError,
1302              "The type of given msg is '%s', expect '%s'.",
1303              upb_msgdef_fullname(msg->descriptor->msgdef),
1304              upb_msgdef_fullname(desc->msgdef));
1305   }
1306
1307   for (upb_msg_field_begin(&i, desc->msgdef);
1308        !upb_msg_field_done(&i);
1309        upb_msg_field_next(&i)) {
1310     upb_fielddef *f = upb_msg_iter_field(&i);
1311     bool is_matching_oneof = false;
1312     uint32_t offset =
1313         desc->layout->fields[upb_fielddef_index(f)].offset +
1314         sizeof(MessageHeader);
1315
1316     if (upb_fielddef_containingoneof(f)) {
1317       uint32_t oneof_case_offset =
1318           desc->layout->fields[upb_fielddef_index(f)].case_offset +
1319           sizeof(MessageHeader);
1320       // For a oneof, check that this field is actually present -- skip all the
1321       // below if not.
1322       if (DEREF(msg, oneof_case_offset, uint32_t) !=
1323           upb_fielddef_number(f)) {
1324         continue;
1325       }
1326       // Otherwise, fall through to the appropriate singular-field handler
1327       // below.
1328       is_matching_oneof = true;
1329     }
1330
1331     if (is_map_field(f)) {
1332       VALUE map = DEREF(msg, offset, VALUE);
1333       if (map != Qnil || emit_defaults) {
1334         putmap(map, f, sink, depth, emit_defaults, is_json);
1335       }
1336     } else if (upb_fielddef_isseq(f)) {
1337       VALUE ary = DEREF(msg, offset, VALUE);
1338       if (ary != Qnil) {
1339         putary(ary, f, sink, depth, emit_defaults, is_json);
1340       }
1341     } else if (upb_fielddef_isstring(f)) {
1342       VALUE str = DEREF(msg, offset, VALUE);
1343       bool is_default = false;
1344
1345       if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
1346         is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
1347       } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
1348         is_default = RSTRING_LEN(str) == 0;
1349       }
1350
1351       if (is_matching_oneof || emit_defaults || !is_default) {
1352         putstr(str, f, sink);
1353       }
1354     } else if (upb_fielddef_issubmsg(f)) {
1355       putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth,
1356                 emit_defaults, is_json);
1357     } else {
1358       upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1359
1360 #define T(upbtypeconst, upbtype, ctype, default_value)                          \
1361   case upbtypeconst: {                                                          \
1362       ctype value = DEREF(msg, offset, ctype);                                  \
1363       bool is_default = false;                                                  \
1364       if (upb_fielddef_haspresence(f)) {                                        \
1365         is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;  \
1366       } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {        \
1367         is_default = default_value == value;                                    \
1368       }                                                                         \
1369       if (is_matching_oneof || emit_defaults || !is_default) {                  \
1370         upb_sink_put##upbtype(sink, sel, value);                                \
1371       }                                                                         \
1372     }                                                                           \
1373     break;
1374
1375       switch (upb_fielddef_type(f)) {
1376         T(UPB_TYPE_FLOAT,  float,  float, 0.0)
1377         T(UPB_TYPE_DOUBLE, double, double, 0.0)
1378         T(UPB_TYPE_BOOL,   bool,   uint8_t, 0)
1379         case UPB_TYPE_ENUM:
1380         T(UPB_TYPE_INT32,  int32,  int32_t, 0)
1381         T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
1382         T(UPB_TYPE_INT64,  int64,  int64_t, 0)
1383         T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
1384
1385         case UPB_TYPE_STRING:
1386         case UPB_TYPE_BYTES:
1387         case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
1388       }
1389
1390 #undef T
1391
1392     }
1393   }
1394
1395   stringsink* unknown = msg->unknown_fields;
1396   if (unknown != NULL) {
1397     upb_sink_putunknown(sink, unknown->ptr, unknown->len);
1398   }
1399
1400   if (open_msg) {
1401     upb_sink_endmsg(sink, &status);
1402   }
1403 }
1404
1405 static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
1406   if (desc->pb_serialize_handlers == NULL) {
1407     desc->pb_serialize_handlers =
1408         upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
1409   }
1410   return desc->pb_serialize_handlers;
1411 }
1412
1413 static const upb_handlers* msgdef_json_serialize_handlers(
1414     Descriptor* desc, bool preserve_proto_fieldnames) {
1415   if (preserve_proto_fieldnames) {
1416     if (desc->json_serialize_handlers == NULL) {
1417       desc->json_serialize_handlers =
1418           upb_json_printer_newhandlers(
1419               desc->msgdef, true, &desc->json_serialize_handlers);
1420     }
1421     return desc->json_serialize_handlers;
1422   } else {
1423     if (desc->json_serialize_handlers_preserve == NULL) {
1424       desc->json_serialize_handlers_preserve =
1425           upb_json_printer_newhandlers(
1426               desc->msgdef, false, &desc->json_serialize_handlers_preserve);
1427     }
1428     return desc->json_serialize_handlers_preserve;
1429   }
1430 }
1431
1432 /*
1433  * call-seq:
1434  *     MessageClass.encode(msg) => bytes
1435  *
1436  * Encodes the given message object to its serialized form in protocol buffers
1437  * wire format.
1438  */
1439 VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1440   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1441   Descriptor* desc = ruby_to_Descriptor(descriptor);
1442
1443   stringsink sink;
1444   stringsink_init(&sink);
1445
1446   {
1447     const upb_handlers* serialize_handlers =
1448         msgdef_pb_serialize_handlers(desc);
1449
1450     stackenv se;
1451     upb_pb_encoder* encoder;
1452     VALUE ret;
1453
1454     stackenv_init(&se, "Error occurred during encoding: %s");
1455     encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
1456
1457     putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
1458
1459     ret = rb_str_new(sink.ptr, sink.len);
1460
1461     stackenv_uninit(&se);
1462     stringsink_uninit(&sink);
1463
1464     return ret;
1465   }
1466 }
1467
1468 /*
1469  * call-seq:
1470  *     MessageClass.encode_json(msg, options = {}) => json_string
1471  *
1472  * Encodes the given message object into its serialized JSON representation.
1473  * @param options [Hash] options for the decoder
1474  *  preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
1475  *  emit_defaults: set true to emit 0/false values (default is to omit them)
1476  */
1477 VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1478   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1479   Descriptor* desc = ruby_to_Descriptor(descriptor);
1480   VALUE msg_rb;
1481   VALUE preserve_proto_fieldnames = Qfalse;
1482   VALUE emit_defaults = Qfalse;
1483   stringsink sink;
1484
1485   if (argc < 1 || argc > 2) {
1486     rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1487   }
1488
1489   msg_rb = argv[0];
1490
1491   if (argc == 2) {
1492     VALUE hash_args = argv[1];
1493     if (TYPE(hash_args) != T_HASH) {
1494       rb_raise(rb_eArgError, "Expected hash arguments.");
1495     }
1496     preserve_proto_fieldnames = rb_hash_lookup2(
1497         hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
1498
1499     emit_defaults = rb_hash_lookup2(
1500         hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
1501   }
1502
1503   stringsink_init(&sink);
1504
1505   {
1506     const upb_handlers* serialize_handlers =
1507         msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1508     upb_json_printer* printer;
1509     stackenv se;
1510     VALUE ret;
1511
1512     stackenv_init(&se, "Error occurred during encoding: %s");
1513     printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
1514
1515     putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
1516            RTEST(emit_defaults), true, true);
1517
1518     ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
1519
1520     stackenv_uninit(&se);
1521     stringsink_uninit(&sink);
1522
1523     return ret;
1524   }
1525 }
1526
1527 static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
1528   MessageHeader* msg;
1529   upb_msg_field_iter it;
1530
1531   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1532
1533   stringsink* unknown = msg->unknown_fields;
1534   if (unknown != NULL) {
1535     stringsink_uninit(unknown);
1536     msg->unknown_fields = NULL;
1537   }
1538
1539   for (upb_msg_field_begin(&it, desc->msgdef);
1540        !upb_msg_field_done(&it);
1541        upb_msg_field_next(&it)) {
1542     upb_fielddef *f = upb_msg_iter_field(&it);
1543     uint32_t offset =
1544         desc->layout->fields[upb_fielddef_index(f)].offset +
1545         sizeof(MessageHeader);
1546
1547     if (upb_fielddef_containingoneof(f)) {
1548       uint32_t oneof_case_offset =
1549           desc->layout->fields[upb_fielddef_index(f)].case_offset +
1550           sizeof(MessageHeader);
1551       // For a oneof, check that this field is actually present -- skip all the
1552       // below if not.
1553       if (DEREF(msg, oneof_case_offset, uint32_t) !=
1554           upb_fielddef_number(f)) {
1555         continue;
1556       }
1557       // Otherwise, fall through to the appropriate singular-field handler
1558       // below.
1559     }
1560
1561     if (!upb_fielddef_issubmsg(f)) {
1562       continue;
1563     }
1564
1565     if (is_map_field(f)) {
1566       if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
1567       VALUE map = DEREF(msg, offset, VALUE);
1568       if (map == Qnil) continue;
1569       Map_iter map_it;
1570       for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
1571         VALUE submsg = Map_iter_value(&map_it);
1572         VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1573         const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1574         discard_unknown(submsg, subdesc);
1575       }
1576     } else if (upb_fielddef_isseq(f)) {
1577       VALUE ary = DEREF(msg, offset, VALUE);
1578       if (ary == Qnil) continue;
1579       int size = NUM2INT(RepeatedField_length(ary));
1580       for (int i = 0; i < size; i++) {
1581         void* memory = RepeatedField_index_native(ary, i);
1582         VALUE submsg = *((VALUE *)memory);
1583         VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1584         const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1585         discard_unknown(submsg, subdesc);
1586       }
1587     } else {
1588       VALUE submsg = DEREF(msg, offset, VALUE);
1589       if (submsg == Qnil) continue;
1590       VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1591       const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1592       discard_unknown(submsg, subdesc);
1593     }
1594   }
1595 }
1596
1597 /*
1598  * call-seq:
1599  *     Google::Protobuf.discard_unknown(msg)
1600  *
1601  * Discard unknown fields in the given message object and recursively discard
1602  * unknown fields in submessages.
1603  */
1604 VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
1605   VALUE klass = CLASS_OF(msg_rb);
1606   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1607   Descriptor* desc = ruby_to_Descriptor(descriptor);
1608   if (klass == cRepeatedField || klass == cMap) {
1609     rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
1610   } else {
1611     discard_unknown(msg_rb, desc);
1612   }
1613   return Qnil;
1614 }