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
noleak_rb_str_cat(VALUE rb_str,const char * str,long len)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 
stringsink_start(void * _sink,const void * hd,size_t size_hint)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 
stringsink_string(void * _sink,const void * hd,const char * ptr,size_t len,const upb_bufhandle * handle)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 
stringsink_init(stringsink * sink)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 
stringsink_uninit(stringsink * sink)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
newhandlerdata(upb_handlers * h,uint32_t ofs,int32_t hasbit)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.
newsubmsghandlerdata(upb_handlers * h,uint32_t ofs,int32_t hasbit,const upb_fielddef * f)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 
newoneofhandlerdata(upb_handlers * h,uint32_t ofs,uint32_t case_ofs,const upb_fielddef * f)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).
startseq_handler(void * closure,const void * hd)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 
DEFINE_APPEND_HANDLER(bool,bool)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 
set_hasbit(void * closure,int32_t hasbit)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.
appendbytes_handler(void * closure,const void * hd,size_t size_hint)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.
str_handler(void * closure,const void * hd,size_t size_hint)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.
bytes_handler(void * closure,const void * hd,size_t size_hint)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 
stringdata_handler(void * closure,const void * hd,const char * str,size_t len,const upb_bufhandle * handle)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 
stringdata_end_handler(void * closure,const void * hd)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 
appendstring_end_handler(void * closure,const void * hd)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).
appendsubmsg_handler(void * closure,const void * hd)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.
submsg_handler(void * closure,const void * hd)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 
MapParseFrame_mark(void * _self)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 
MapParseFrame_free(void * self)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 
map_push_frame(VALUE map,const map_handlerdata_t * handlerdata)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.
startmapentry_handler(void * closure,const void * hd)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.
endmap_handler(void * closure,const void * hd,upb_status * s)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     if (mapdata->value_field_type == UPB_TYPE_ENUM) {
393       value_field_typeclass = EnumDescriptor_enummodule(value_field_typeclass);
394     }
395   }
396 
397   value = native_slot_get(
398       mapdata->value_field_type, value_field_typeclass,
399       &frame->value_storage);
400 
401   Map_index_set(frame->map, key, value);
402   Map_set_frame(frame->map, Qnil);
403 
404   return true;
405 }
406 
407 // Allocates a new map_handlerdata_t given the map entry message definition. If
408 // the offset of the field within the parent message is also given, that is
409 // added to the handler data as well. Note that this is called *twice* per map
410 // field: once in the parent message handler setup when setting the startsubmsg
411 // handler and once in the map entry message handler setup when setting the
412 // key/value and endmsg handlers. The reason is that there is no easy way to
413 // pass the handlerdata down to the sub-message handler setup.
new_map_handlerdata(size_t ofs,const upb_msgdef * mapentry_def,Descriptor * desc)414 static map_handlerdata_t* new_map_handlerdata(
415     size_t ofs,
416     const upb_msgdef* mapentry_def,
417     Descriptor* desc) {
418   const upb_fielddef* key_field;
419   const upb_fielddef* value_field;
420   map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
421   hd->ofs = ofs;
422   key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
423   assert(key_field != NULL);
424   hd->key_field_type = upb_fielddef_type(key_field);
425   value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
426   assert(value_field != NULL);
427   hd->value_field_type = upb_fielddef_type(value_field);
428   hd->value_field_subdef = upb_fielddef_subdef(value_field);
429 
430   return hd;
431 }
432 
433 // Handlers that set primitive values in oneofs.
434 #define DEFINE_ONEOF_HANDLER(type, ctype)                           \
435   static bool oneof##type##_handler(void *closure, const void *hd,  \
436                                      ctype val) {                   \
437     const oneof_handlerdata_t *oneofdata = hd;                      \
438     DEREF(closure, oneofdata->case_ofs, uint32_t) =                 \
439         oneofdata->oneof_case_num;                                  \
440     DEREF(closure, oneofdata->ofs, ctype) = val;                    \
441     return true;                                                    \
442   }
443 
DEFINE_ONEOF_HANDLER(bool,bool)444 DEFINE_ONEOF_HANDLER(bool,   bool)
445 DEFINE_ONEOF_HANDLER(int32,  int32_t)
446 DEFINE_ONEOF_HANDLER(uint32, uint32_t)
447 DEFINE_ONEOF_HANDLER(float,  float)
448 DEFINE_ONEOF_HANDLER(int64,  int64_t)
449 DEFINE_ONEOF_HANDLER(uint64, uint64_t)
450 DEFINE_ONEOF_HANDLER(double, double)
451 
452 #undef DEFINE_ONEOF_HANDLER
453 
454 // Handlers for strings in a oneof.
455 static void *oneofstr_handler(void *closure,
456                               const void *hd,
457                               size_t size_hint) {
458   MessageHeader* msg = closure;
459   const oneof_handlerdata_t *oneofdata = hd;
460   VALUE str = rb_str_new2("");
461   rb_enc_associate(str, kRubyStringUtf8Encoding);
462   DEREF(msg, oneofdata->case_ofs, uint32_t) =
463       oneofdata->oneof_case_num;
464   DEREF(msg, oneofdata->ofs, VALUE) = str;
465   return (void*)str;
466 }
467 
oneofbytes_handler(void * closure,const void * hd,size_t size_hint)468 static void *oneofbytes_handler(void *closure,
469                                 const void *hd,
470                                 size_t size_hint) {
471   MessageHeader* msg = closure;
472   const oneof_handlerdata_t *oneofdata = hd;
473   VALUE str = rb_str_new2("");
474   rb_enc_associate(str, kRubyString8bitEncoding);
475   DEREF(msg, oneofdata->case_ofs, uint32_t) =
476       oneofdata->oneof_case_num;
477   DEREF(msg, oneofdata->ofs, VALUE) = str;
478   return (void*)str;
479 }
480 
oneofstring_end_handler(void * closure,const void * hd)481 static bool oneofstring_end_handler(void* closure, const void* hd) {
482   VALUE rb_str = rb_str_new2("");
483   rb_obj_freeze(rb_str);
484   return true;
485 }
486 
487 // Handler for a submessage field in a oneof.
oneofsubmsg_handler(void * closure,const void * hd)488 static void *oneofsubmsg_handler(void *closure,
489                                  const void *hd) {
490   MessageHeader* msg = closure;
491   const oneof_handlerdata_t *oneofdata = hd;
492   uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
493 
494   VALUE subdesc =
495       get_def_obj((void*)oneofdata->md);
496   VALUE subklass = Descriptor_msgclass(subdesc);
497   VALUE submsg_rb;
498   MessageHeader* submsg;
499 
500   if (oldcase != oneofdata->oneof_case_num ||
501       DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
502     DEREF(msg, oneofdata->ofs, VALUE) =
503         rb_class_new_instance(0, NULL, subklass);
504   }
505   // Set the oneof case *after* allocating the new class instance -- otherwise,
506   // if the Ruby GC is invoked as part of a call into the VM, it might invoke
507   // our mark routines, and our mark routines might see the case value
508   // indicating a VALUE is present and expect a valid VALUE. See comment in
509   // layout_set() for more detail: basically, the change to the value and the
510   // case must be atomic w.r.t. the Ruby VM.
511   DEREF(msg, oneofdata->case_ofs, uint32_t) =
512       oneofdata->oneof_case_num;
513 
514   submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
515   TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
516   return submsg;
517 }
518 
519 // Set up handlers for a repeated field.
add_handlers_for_repeated_field(upb_handlers * h,const upb_fielddef * f,size_t offset)520 static void add_handlers_for_repeated_field(upb_handlers *h,
521                                             const upb_fielddef *f,
522                                             size_t offset) {
523   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
524   upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, -1));
525   upb_handlers_setstartseq(h, f, startseq_handler, &attr);
526   upb_handlerattr_uninit(&attr);
527 
528   switch (upb_fielddef_type(f)) {
529 
530 #define SET_HANDLER(utype, ltype)                                 \
531   case utype:                                                     \
532     upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
533     break;
534 
535     SET_HANDLER(UPB_TYPE_BOOL,   bool);
536     SET_HANDLER(UPB_TYPE_INT32,  int32);
537     SET_HANDLER(UPB_TYPE_UINT32, uint32);
538     SET_HANDLER(UPB_TYPE_ENUM,   int32);
539     SET_HANDLER(UPB_TYPE_FLOAT,  float);
540     SET_HANDLER(UPB_TYPE_INT64,  int64);
541     SET_HANDLER(UPB_TYPE_UINT64, uint64);
542     SET_HANDLER(UPB_TYPE_DOUBLE, double);
543 
544 #undef SET_HANDLER
545 
546     case UPB_TYPE_STRING:
547     case UPB_TYPE_BYTES: {
548       bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
549       upb_handlers_setstartstr(h, f, is_bytes ?
550                                appendbytes_handler : appendstr_handler,
551                                NULL);
552       upb_handlers_setstring(h, f, stringdata_handler, NULL);
553       upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
554       break;
555     }
556     case UPB_TYPE_MESSAGE: {
557       upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
558       upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, -1, f));
559       upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
560       upb_handlerattr_uninit(&attr);
561       break;
562     }
563   }
564 }
565 
566 // Set up handlers for a singular field.
add_handlers_for_singular_field(upb_handlers * h,const upb_fielddef * f,size_t offset,size_t hasbit_off)567 static void add_handlers_for_singular_field(upb_handlers *h,
568                                             const upb_fielddef *f,
569                                             size_t offset,
570                                             size_t hasbit_off) {
571   // The offset we pass to UPB points to the start of the Message,
572   // rather than the start of where our data is stored.
573   int32_t hasbit = -1;
574   if (hasbit_off != MESSAGE_FIELD_NO_HASBIT) {
575     hasbit = hasbit_off + sizeof(MessageHeader) * 8;
576   }
577 
578   switch (upb_fielddef_type(f)) {
579     case UPB_TYPE_BOOL:
580     case UPB_TYPE_INT32:
581     case UPB_TYPE_UINT32:
582     case UPB_TYPE_ENUM:
583     case UPB_TYPE_FLOAT:
584     case UPB_TYPE_INT64:
585     case UPB_TYPE_UINT64:
586     case UPB_TYPE_DOUBLE:
587       upb_msg_setscalarhandler(h, f, offset, hasbit);
588       break;
589     case UPB_TYPE_STRING:
590     case UPB_TYPE_BYTES: {
591       bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
592       upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
593       upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset, hasbit));
594       upb_handlers_setstartstr(h, f,
595                                is_bytes ? bytes_handler : str_handler,
596                                &attr);
597       upb_handlers_setstring(h, f, stringdata_handler, &attr);
598       upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
599       upb_handlerattr_uninit(&attr);
600       break;
601     }
602     case UPB_TYPE_MESSAGE: {
603       upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
604       upb_handlerattr_sethandlerdata(&attr,
605 				     newsubmsghandlerdata(h, offset,
606 							  hasbit, f));
607       upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
608       upb_handlerattr_uninit(&attr);
609       break;
610     }
611   }
612 }
613 
614 // Adds handlers to a map field.
add_handlers_for_mapfield(upb_handlers * h,const upb_fielddef * fielddef,size_t offset,Descriptor * desc)615 static void add_handlers_for_mapfield(upb_handlers* h,
616                                       const upb_fielddef* fielddef,
617                                       size_t offset,
618                                       Descriptor* desc) {
619   const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
620   map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
621   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
622 
623   upb_handlers_addcleanup(h, hd, xfree);
624   upb_handlerattr_sethandlerdata(&attr, hd);
625   upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
626   upb_handlerattr_uninit(&attr);
627 }
628 
629 // Adds handlers to a map-entry msgdef.
add_handlers_for_mapentry(const upb_msgdef * msgdef,upb_handlers * h,Descriptor * desc)630 static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
631                                       upb_handlers* h,
632                                       Descriptor* desc) {
633   const upb_fielddef* key_field = map_entry_key(msgdef);
634   const upb_fielddef* value_field = map_entry_value(msgdef);
635   map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
636   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
637 
638   upb_handlers_addcleanup(h, hd, xfree);
639   upb_handlerattr_sethandlerdata(&attr, hd);
640   upb_handlers_setendmsg(h, endmap_handler, &attr);
641 
642   add_handlers_for_singular_field(
643       h, key_field,
644       offsetof(map_parse_frame_t, key_storage),
645       MESSAGE_FIELD_NO_HASBIT);
646   add_handlers_for_singular_field(
647       h, value_field,
648       offsetof(map_parse_frame_t, value_storage),
649       MESSAGE_FIELD_NO_HASBIT);
650 }
651 
652 // Set up handlers for a oneof field.
add_handlers_for_oneof_field(upb_handlers * h,const upb_fielddef * f,size_t offset,size_t oneof_case_offset)653 static void add_handlers_for_oneof_field(upb_handlers *h,
654                                          const upb_fielddef *f,
655                                          size_t offset,
656                                          size_t oneof_case_offset) {
657 
658   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
659   upb_handlerattr_sethandlerdata(
660       &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
661 
662   switch (upb_fielddef_type(f)) {
663 
664 #define SET_HANDLER(utype, ltype)                                 \
665   case utype:                                                     \
666     upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
667     break;
668 
669     SET_HANDLER(UPB_TYPE_BOOL,   bool);
670     SET_HANDLER(UPB_TYPE_INT32,  int32);
671     SET_HANDLER(UPB_TYPE_UINT32, uint32);
672     SET_HANDLER(UPB_TYPE_ENUM,   int32);
673     SET_HANDLER(UPB_TYPE_FLOAT,  float);
674     SET_HANDLER(UPB_TYPE_INT64,  int64);
675     SET_HANDLER(UPB_TYPE_UINT64, uint64);
676     SET_HANDLER(UPB_TYPE_DOUBLE, double);
677 
678 #undef SET_HANDLER
679 
680     case UPB_TYPE_STRING:
681     case UPB_TYPE_BYTES: {
682       bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
683       upb_handlers_setstartstr(h, f, is_bytes ?
684                                oneofbytes_handler : oneofstr_handler,
685                                &attr);
686       upb_handlers_setstring(h, f, stringdata_handler, NULL);
687       upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
688       break;
689     }
690     case UPB_TYPE_MESSAGE: {
691       upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
692       break;
693     }
694   }
695 
696   upb_handlerattr_uninit(&attr);
697 }
698 
unknown_field_handler(void * closure,const void * hd,const char * buf,size_t size)699 static bool unknown_field_handler(void* closure, const void* hd,
700                                   const char* buf, size_t size) {
701   UPB_UNUSED(hd);
702 
703   MessageHeader* msg = (MessageHeader*)closure;
704   if (msg->unknown_fields == NULL) {
705     msg->unknown_fields = malloc(sizeof(stringsink));
706     stringsink_init(msg->unknown_fields);
707   }
708 
709   stringsink_string(msg->unknown_fields, NULL, buf, size, NULL);
710 
711   return true;
712 }
713 
add_handlers_for_message(const void * closure,upb_handlers * h)714 static void add_handlers_for_message(const void *closure, upb_handlers *h) {
715   const upb_msgdef* msgdef = upb_handlers_msgdef(h);
716   Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
717   upb_msg_field_iter i;
718 
719   // If this is a mapentry message type, set up a special set of handlers and
720   // bail out of the normal (user-defined) message type handling.
721   if (upb_msgdef_mapentry(msgdef)) {
722     add_handlers_for_mapentry(msgdef, h, desc);
723     return;
724   }
725 
726   // Ensure layout exists. We may be invoked to create handlers for a given
727   // message if we are included as a submsg of another message type before our
728   // class is actually built, so to work around this, we just create the layout
729   // (and handlers, in the class-building function) on-demand.
730   if (desc->layout == NULL) {
731     desc->layout = create_layout(desc->msgdef);
732   }
733 
734   upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
735   upb_handlers_setunknown(h, unknown_field_handler, &attr);
736 
737   for (upb_msg_field_begin(&i, desc->msgdef);
738        !upb_msg_field_done(&i);
739        upb_msg_field_next(&i)) {
740     const upb_fielddef *f = upb_msg_iter_field(&i);
741     size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
742         sizeof(MessageHeader);
743 
744     if (upb_fielddef_containingoneof(f)) {
745       size_t oneof_case_offset =
746           desc->layout->fields[upb_fielddef_index(f)].case_offset +
747           sizeof(MessageHeader);
748       add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
749     } else if (is_map_field(f)) {
750       add_handlers_for_mapfield(h, f, offset, desc);
751     } else if (upb_fielddef_isseq(f)) {
752       add_handlers_for_repeated_field(h, f, offset);
753     } else {
754       add_handlers_for_singular_field(
755           h, f, offset, desc->layout->fields[upb_fielddef_index(f)].hasbit);
756     }
757   }
758 }
759 
760 // Creates upb handlers for populating a message.
new_fill_handlers(Descriptor * desc,const void * owner)761 static const upb_handlers *new_fill_handlers(Descriptor* desc,
762                                              const void* owner) {
763   // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
764   // handlers, reuse subdef handlers so that e.g. if we already parse
765   // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
766   // parse A-with-field-of-type-B-with-field-of-type-C.
767   return upb_handlers_newfrozen(desc->msgdef, owner,
768                                 add_handlers_for_message, NULL);
769 }
770 
771 // Constructs the handlers for filling a message's data into an in-memory
772 // object.
get_fill_handlers(Descriptor * desc)773 const upb_handlers* get_fill_handlers(Descriptor* desc) {
774   if (!desc->fill_handlers) {
775     desc->fill_handlers =
776         new_fill_handlers(desc, &desc->fill_handlers);
777   }
778   return desc->fill_handlers;
779 }
780 
781 // Constructs the upb decoder method for parsing messages of this type.
782 // This is called from the message class creation code.
new_fillmsg_decodermethod(Descriptor * desc,const void * owner)783 const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
784                                                      const void* owner) {
785   const upb_handlers* handlers = get_fill_handlers(desc);
786   upb_pbdecodermethodopts opts;
787   upb_pbdecodermethodopts_init(&opts, handlers);
788 
789   return upb_pbdecodermethod_new(&opts, owner);
790 }
791 
msgdef_decodermethod(Descriptor * desc)792 static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
793   if (desc->fill_method == NULL) {
794     desc->fill_method = new_fillmsg_decodermethod(
795         desc, &desc->fill_method);
796   }
797   return desc->fill_method;
798 }
799 
msgdef_jsonparsermethod(Descriptor * desc)800 static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
801   if (desc->json_fill_method == NULL) {
802     desc->json_fill_method =
803         upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
804   }
805   return desc->json_fill_method;
806 }
807 
808 
809 // Stack-allocated context during an encode/decode operation. Contains the upb
810 // environment and its stack-based allocator, an initial buffer for allocations
811 // to avoid malloc() when possible, and a template for Ruby exception messages
812 // if any error occurs.
813 #define STACK_ENV_STACKBYTES 4096
814 typedef struct {
815   upb_env env;
816   const char* ruby_error_template;
817   char allocbuf[STACK_ENV_STACKBYTES];
818 } stackenv;
819 
820 static void stackenv_init(stackenv* se, const char* errmsg);
821 static void stackenv_uninit(stackenv* se);
822 
823 // Callback invoked by upb if any error occurs during parsing or serialization.
env_error_func(void * ud,const upb_status * status)824 static bool env_error_func(void* ud, const upb_status* status) {
825   stackenv* se = ud;
826   // Free the env -- rb_raise will longjmp up the stack past the encode/decode
827   // function so it would not otherwise have been freed.
828   stackenv_uninit(se);
829 
830   // TODO(haberman): have a way to verify that this is actually a parse error,
831   // instead of just throwing "parse error" unconditionally.
832   rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
833   // Never reached: rb_raise() always longjmp()s up the stack, past all of our
834   // code, back to Ruby.
835   return false;
836 }
837 
stackenv_init(stackenv * se,const char * errmsg)838 static void stackenv_init(stackenv* se, const char* errmsg) {
839   se->ruby_error_template = errmsg;
840   upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
841   upb_env_seterrorfunc(&se->env, env_error_func, se);
842 }
843 
stackenv_uninit(stackenv * se)844 static void stackenv_uninit(stackenv* se) {
845   upb_env_uninit(&se->env);
846 }
847 
848 /*
849  * call-seq:
850  *     MessageClass.decode(data) => message
851  *
852  * Decodes the given data (as a string containing bytes in protocol buffers wire
853  * format) under the interpretration given by this message class's definition
854  * and returns a message object with the corresponding field values.
855  */
Message_decode(VALUE klass,VALUE data)856 VALUE Message_decode(VALUE klass, VALUE data) {
857   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
858   Descriptor* desc = ruby_to_Descriptor(descriptor);
859   VALUE msgklass = Descriptor_msgclass(descriptor);
860   VALUE msg_rb;
861   MessageHeader* msg;
862 
863   if (TYPE(data) != T_STRING) {
864     rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
865   }
866 
867   msg_rb = rb_class_new_instance(0, NULL, msgklass);
868   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
869 
870   {
871     const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
872     const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
873     stackenv se;
874     upb_sink sink;
875     upb_pbdecoder* decoder;
876     stackenv_init(&se, "Error occurred during parsing: %s");
877 
878     upb_sink_reset(&sink, h, msg);
879     decoder = upb_pbdecoder_create(&se.env, method, &sink);
880     upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
881                       upb_pbdecoder_input(decoder));
882 
883     stackenv_uninit(&se);
884   }
885 
886   return msg_rb;
887 }
888 
889 /*
890  * call-seq:
891  *     MessageClass.decode_json(data, options = {}) => message
892  *
893  * Decodes the given data (as a string containing bytes in protocol buffers wire
894  * format) under the interpretration given by this message class's definition
895  * and returns a message object with the corresponding field values.
896  *
897  * @param options [Hash] options for the decoder
898  *   ignore_unknown_fields: set true to ignore unknown fields (default is to raise an error)
899  */
Message_decode_json(int argc,VALUE * argv,VALUE klass)900 VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass) {
901   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
902   Descriptor* desc = ruby_to_Descriptor(descriptor);
903   VALUE msgklass = Descriptor_msgclass(descriptor);
904   VALUE msg_rb;
905   VALUE data = argv[0];
906   VALUE ignore_unknown_fields = Qfalse;
907   MessageHeader* msg;
908 
909   if (argc < 1 || argc > 2) {
910     rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
911   }
912 
913   if (argc == 2) {
914     VALUE hash_args = argv[1];
915     if (TYPE(hash_args) != T_HASH) {
916       rb_raise(rb_eArgError, "Expected hash arguments.");
917     }
918 
919     ignore_unknown_fields = rb_hash_lookup2(
920         hash_args, ID2SYM(rb_intern("ignore_unknown_fields")), Qfalse);
921   }
922 
923   if (TYPE(data) != T_STRING) {
924     rb_raise(rb_eArgError, "Expected string for JSON data.");
925   }
926   // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
927   // convert, because string handlers pass data directly to message string
928   // fields.
929 
930   msg_rb = rb_class_new_instance(0, NULL, msgklass);
931   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
932 
933   {
934     const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
935     stackenv se;
936     upb_sink sink;
937     upb_json_parser* parser;
938     DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
939     stackenv_init(&se, "Error occurred during parsing: %s");
940 
941     upb_sink_reset(&sink, get_fill_handlers(desc), msg);
942     parser = upb_json_parser_create(&se.env, method, pool->symtab,
943                                     &sink, ignore_unknown_fields);
944     upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
945                       upb_json_parser_input(parser));
946 
947     stackenv_uninit(&se);
948   }
949 
950   return msg_rb;
951 }
952 
953 // -----------------------------------------------------------------------------
954 // Serializing.
955 // -----------------------------------------------------------------------------
956 
957 /* msgvisitor *****************************************************************/
958 
959 static void putmsg(VALUE msg, const Descriptor* desc,
960                    upb_sink *sink, int depth, bool emit_defaults,
961                    bool is_json, bool open_msg);
962 
getsel(const upb_fielddef * f,upb_handlertype_t type)963 static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
964   upb_selector_t ret;
965   bool ok = upb_handlers_getselector(f, type, &ret);
966   UPB_ASSERT(ok);
967   return ret;
968 }
969 
putstr(VALUE str,const upb_fielddef * f,upb_sink * sink)970 static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
971   upb_sink subsink;
972 
973   if (str == Qnil) return;
974 
975   assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
976 
977   // We should be guaranteed that the string has the correct encoding because
978   // we ensured this at assignment time and then froze the string.
979   if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
980     assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
981   } else {
982     assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
983   }
984 
985   upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
986                     &subsink);
987   upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
988                      RSTRING_LEN(str), NULL);
989   upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
990 }
991 
putsubmsg(VALUE submsg,const upb_fielddef * f,upb_sink * sink,int depth,bool emit_defaults,bool is_json)992 static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
993                       int depth, bool emit_defaults, bool is_json) {
994   upb_sink subsink;
995   VALUE descriptor;
996   Descriptor* subdesc;
997 
998   if (submsg == Qnil) return;
999 
1000   descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1001   subdesc = ruby_to_Descriptor(descriptor);
1002 
1003   upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
1004   putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults, is_json, true);
1005   upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1006 }
1007 
putary(VALUE ary,const upb_fielddef * f,upb_sink * sink,int depth,bool emit_defaults,bool is_json)1008 static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
1009                    int depth, bool emit_defaults, bool is_json) {
1010   upb_sink subsink;
1011   upb_fieldtype_t type = upb_fielddef_type(f);
1012   upb_selector_t sel = 0;
1013   int size;
1014 
1015   if (ary == Qnil) return;
1016   if (!emit_defaults && NUM2INT(RepeatedField_length(ary)) == 0) return;
1017 
1018   size = NUM2INT(RepeatedField_length(ary));
1019   if (size == 0 && !emit_defaults) return;
1020 
1021   upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1022 
1023   if (upb_fielddef_isprimitive(f)) {
1024     sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1025   }
1026 
1027   for (int i = 0; i < size; i++) {
1028     void* memory = RepeatedField_index_native(ary, i);
1029     switch (type) {
1030 #define T(upbtypeconst, upbtype, ctype)                         \
1031   case upbtypeconst:                                            \
1032     upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory));   \
1033     break;
1034 
1035       T(UPB_TYPE_FLOAT,  float,  float)
1036       T(UPB_TYPE_DOUBLE, double, double)
1037       T(UPB_TYPE_BOOL,   bool,   int8_t)
1038       case UPB_TYPE_ENUM:
1039       T(UPB_TYPE_INT32,  int32,  int32_t)
1040       T(UPB_TYPE_UINT32, uint32, uint32_t)
1041       T(UPB_TYPE_INT64,  int64,  int64_t)
1042       T(UPB_TYPE_UINT64, uint64, uint64_t)
1043 
1044       case UPB_TYPE_STRING:
1045       case UPB_TYPE_BYTES:
1046         putstr(*((VALUE *)memory), f, &subsink);
1047         break;
1048       case UPB_TYPE_MESSAGE:
1049         putsubmsg(*((VALUE *)memory), f, &subsink, depth,
1050                   emit_defaults, is_json);
1051         break;
1052 
1053 #undef T
1054 
1055     }
1056   }
1057   upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1058 }
1059 
put_ruby_value(VALUE value,const upb_fielddef * f,VALUE type_class,int depth,upb_sink * sink,bool emit_defaults,bool is_json)1060 static void put_ruby_value(VALUE value,
1061                            const upb_fielddef *f,
1062                            VALUE type_class,
1063                            int depth,
1064                            upb_sink *sink,
1065                            bool emit_defaults,
1066                            bool is_json) {
1067   if (depth > ENCODE_MAX_NESTING) {
1068     rb_raise(rb_eRuntimeError,
1069              "Maximum recursion depth exceeded during encoding.");
1070   }
1071 
1072   upb_selector_t sel = 0;
1073   if (upb_fielddef_isprimitive(f)) {
1074     sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1075   }
1076 
1077   switch (upb_fielddef_type(f)) {
1078     case UPB_TYPE_INT32:
1079       upb_sink_putint32(sink, sel, NUM2INT(value));
1080       break;
1081     case UPB_TYPE_INT64:
1082       upb_sink_putint64(sink, sel, NUM2LL(value));
1083       break;
1084     case UPB_TYPE_UINT32:
1085       upb_sink_putuint32(sink, sel, NUM2UINT(value));
1086       break;
1087     case UPB_TYPE_UINT64:
1088       upb_sink_putuint64(sink, sel, NUM2ULL(value));
1089       break;
1090     case UPB_TYPE_FLOAT:
1091       upb_sink_putfloat(sink, sel, NUM2DBL(value));
1092       break;
1093     case UPB_TYPE_DOUBLE:
1094       upb_sink_putdouble(sink, sel, NUM2DBL(value));
1095       break;
1096     case UPB_TYPE_ENUM: {
1097       if (TYPE(value) == T_SYMBOL) {
1098         value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
1099       }
1100       upb_sink_putint32(sink, sel, NUM2INT(value));
1101       break;
1102     }
1103     case UPB_TYPE_BOOL:
1104       upb_sink_putbool(sink, sel, value == Qtrue);
1105       break;
1106     case UPB_TYPE_STRING:
1107     case UPB_TYPE_BYTES:
1108       putstr(value, f, sink);
1109       break;
1110     case UPB_TYPE_MESSAGE:
1111       putsubmsg(value, f, sink, depth, emit_defaults, is_json);
1112   }
1113 }
1114 
putmap(VALUE map,const upb_fielddef * f,upb_sink * sink,int depth,bool emit_defaults,bool is_json)1115 static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
1116                    int depth, bool emit_defaults, bool is_json) {
1117   Map* self;
1118   upb_sink subsink;
1119   const upb_fielddef* key_field;
1120   const upb_fielddef* value_field;
1121   Map_iter it;
1122 
1123   if (map == Qnil) return;
1124   if (!emit_defaults && Map_length(map) == 0) return;
1125 
1126   self = ruby_to_Map(map);
1127 
1128   upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1129 
1130   assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
1131   key_field = map_field_key(f);
1132   value_field = map_field_value(f);
1133 
1134   for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
1135     VALUE key = Map_iter_key(&it);
1136     VALUE value = Map_iter_value(&it);
1137     upb_status status;
1138 
1139     upb_sink entry_sink;
1140     upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
1141                          &entry_sink);
1142     upb_sink_startmsg(&entry_sink);
1143 
1144     put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink,
1145                    emit_defaults, is_json);
1146     put_ruby_value(value, value_field, self->value_type_class, depth + 1,
1147                    &entry_sink, emit_defaults, is_json);
1148 
1149     upb_sink_endmsg(&entry_sink, &status);
1150     upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
1151   }
1152 
1153   upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1154 }
1155 
1156 static const upb_handlers* msgdef_json_serialize_handlers(
1157     Descriptor* desc, bool preserve_proto_fieldnames);
1158 
putjsonany(VALUE msg_rb,const Descriptor * desc,upb_sink * sink,int depth,bool emit_defaults)1159 static void putjsonany(VALUE msg_rb, const Descriptor* desc,
1160                        upb_sink* sink, int depth, bool emit_defaults) {
1161   upb_status status;
1162   MessageHeader* msg = NULL;
1163   const upb_fielddef* type_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_TYPE);
1164   const upb_fielddef* value_field = upb_msgdef_itof(desc->msgdef, UPB_ANY_VALUE);
1165 
1166   size_t type_url_offset;
1167   VALUE type_url_str_rb;
1168   const upb_msgdef *payload_type = NULL;
1169 
1170   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1171 
1172   upb_sink_startmsg(sink);
1173 
1174   /* Handle type url */
1175   type_url_offset = desc->layout->fields[upb_fielddef_index(type_field)].offset;
1176   type_url_str_rb = DEREF(Message_data(msg), type_url_offset, VALUE);
1177   if (RSTRING_LEN(type_url_str_rb) > 0) {
1178     putstr(type_url_str_rb, type_field, sink);
1179   }
1180 
1181   {
1182     const char* type_url_str = RSTRING_PTR(type_url_str_rb);
1183     size_t type_url_len = RSTRING_LEN(type_url_str_rb);
1184     DescriptorPool* pool = ruby_to_DescriptorPool(generated_pool);
1185 
1186     if (type_url_len <= 20 ||
1187         strncmp(type_url_str, "type.googleapis.com/", 20) != 0) {
1188       rb_raise(rb_eRuntimeError, "Invalid type url: %s", type_url_str);
1189       return;
1190     }
1191 
1192     /* Resolve type url */
1193     type_url_str += 20;
1194     type_url_len -= 20;
1195 
1196     payload_type = upb_symtab_lookupmsg2(
1197         pool->symtab, type_url_str, type_url_len);
1198     if (payload_type == NULL) {
1199       rb_raise(rb_eRuntimeError, "Unknown type: %s", type_url_str);
1200       return;
1201     }
1202   }
1203 
1204   {
1205     uint32_t value_offset;
1206     VALUE value_str_rb;
1207     const char* value_str;
1208     size_t value_len;
1209 
1210     value_offset = desc->layout->fields[upb_fielddef_index(value_field)].offset;
1211     value_str_rb = DEREF(Message_data(msg), value_offset, VALUE);
1212     value_str = RSTRING_PTR(value_str_rb);
1213     value_len = RSTRING_LEN(value_str_rb);
1214 
1215     if (value_len > 0) {
1216       VALUE payload_desc_rb = get_def_obj(payload_type);
1217       Descriptor* payload_desc = ruby_to_Descriptor(payload_desc_rb);
1218       VALUE payload_class = Descriptor_msgclass(payload_desc_rb);
1219       upb_sink subsink;
1220       bool is_wellknown;
1221 
1222       VALUE payload_msg_rb = Message_decode(payload_class, value_str_rb);
1223 
1224       is_wellknown =
1225           upb_msgdef_wellknowntype(payload_desc->msgdef) !=
1226               UPB_WELLKNOWN_UNSPECIFIED;
1227       if (is_wellknown) {
1228         upb_sink_startstr(sink, getsel(value_field, UPB_HANDLER_STARTSTR), 0,
1229                           &subsink);
1230       }
1231 
1232       subsink.handlers =
1233           msgdef_json_serialize_handlers(payload_desc, true);
1234       subsink.closure = sink->closure;
1235       putmsg(payload_msg_rb, payload_desc, &subsink, depth, emit_defaults, true,
1236              is_wellknown);
1237     }
1238   }
1239 
1240   upb_sink_endmsg(sink, &status);
1241 }
1242 
putjsonlistvalue(VALUE msg_rb,const Descriptor * desc,upb_sink * sink,int depth,bool emit_defaults)1243 static void putjsonlistvalue(
1244     VALUE msg_rb, const Descriptor* desc,
1245     upb_sink* sink, int depth, bool emit_defaults) {
1246   upb_status status;
1247   upb_sink subsink;
1248   MessageHeader* msg = NULL;
1249   const upb_fielddef* f = upb_msgdef_itof(desc->msgdef, 1);
1250   uint32_t offset =
1251       desc->layout->fields[upb_fielddef_index(f)].offset +
1252       sizeof(MessageHeader);
1253   VALUE ary;
1254 
1255   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1256 
1257   upb_sink_startmsg(sink);
1258 
1259   ary = DEREF(msg, offset, VALUE);
1260 
1261   if (ary == Qnil || RepeatedField_size(ary) == 0) {
1262     upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
1263     upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
1264   } else {
1265     putary(ary, f, sink, depth, emit_defaults, true);
1266   }
1267 
1268   upb_sink_endmsg(sink, &status);
1269 }
1270 
putmsg(VALUE msg_rb,const Descriptor * desc,upb_sink * sink,int depth,bool emit_defaults,bool is_json,bool open_msg)1271 static void putmsg(VALUE msg_rb, const Descriptor* desc,
1272                    upb_sink *sink, int depth, bool emit_defaults,
1273                    bool is_json, bool open_msg) {
1274   MessageHeader* msg;
1275   upb_msg_field_iter i;
1276   upb_status status;
1277 
1278   if (is_json &&
1279       upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_ANY) {
1280     putjsonany(msg_rb, desc, sink, depth, emit_defaults);
1281     return;
1282   }
1283 
1284   if (is_json &&
1285       upb_msgdef_wellknowntype(desc->msgdef) == UPB_WELLKNOWN_LISTVALUE) {
1286     putjsonlistvalue(msg_rb, desc, sink, depth, emit_defaults);
1287     return;
1288   }
1289 
1290   if (open_msg) {
1291     upb_sink_startmsg(sink);
1292   }
1293 
1294   // Protect against cycles (possible because users may freely reassign message
1295   // and repeated fields) by imposing a maximum recursion depth.
1296   if (depth > ENCODE_MAX_NESTING) {
1297     rb_raise(rb_eRuntimeError,
1298              "Maximum recursion depth exceeded during encoding.");
1299   }
1300 
1301   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1302 
1303   if (desc != msg->descriptor) {
1304     rb_raise(rb_eArgError,
1305              "The type of given msg is '%s', expect '%s'.",
1306              upb_msgdef_fullname(msg->descriptor->msgdef),
1307              upb_msgdef_fullname(desc->msgdef));
1308   }
1309 
1310   for (upb_msg_field_begin(&i, desc->msgdef);
1311        !upb_msg_field_done(&i);
1312        upb_msg_field_next(&i)) {
1313     upb_fielddef *f = upb_msg_iter_field(&i);
1314     bool is_matching_oneof = false;
1315     uint32_t offset =
1316         desc->layout->fields[upb_fielddef_index(f)].offset +
1317         sizeof(MessageHeader);
1318 
1319     if (upb_fielddef_containingoneof(f)) {
1320       uint32_t oneof_case_offset =
1321           desc->layout->fields[upb_fielddef_index(f)].case_offset +
1322           sizeof(MessageHeader);
1323       // For a oneof, check that this field is actually present -- skip all the
1324       // below if not.
1325       if (DEREF(msg, oneof_case_offset, uint32_t) !=
1326           upb_fielddef_number(f)) {
1327         continue;
1328       }
1329       // Otherwise, fall through to the appropriate singular-field handler
1330       // below.
1331       is_matching_oneof = true;
1332     }
1333 
1334     if (is_map_field(f)) {
1335       VALUE map = DEREF(msg, offset, VALUE);
1336       if (map != Qnil || emit_defaults) {
1337         putmap(map, f, sink, depth, emit_defaults, is_json);
1338       }
1339     } else if (upb_fielddef_isseq(f)) {
1340       VALUE ary = DEREF(msg, offset, VALUE);
1341       if (ary != Qnil) {
1342         putary(ary, f, sink, depth, emit_defaults, is_json);
1343       }
1344     } else if (upb_fielddef_isstring(f)) {
1345       VALUE str = DEREF(msg, offset, VALUE);
1346       bool is_default = false;
1347 
1348       if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO2) {
1349         is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;
1350       } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {
1351         is_default = RSTRING_LEN(str) == 0;
1352       }
1353 
1354       if (is_matching_oneof || emit_defaults || !is_default) {
1355         putstr(str, f, sink);
1356       }
1357     } else if (upb_fielddef_issubmsg(f)) {
1358       putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth,
1359                 emit_defaults, is_json);
1360     } else {
1361       upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
1362 
1363 #define T(upbtypeconst, upbtype, ctype, default_value)                          \
1364   case upbtypeconst: {                                                          \
1365       ctype value = DEREF(msg, offset, ctype);                                  \
1366       bool is_default = false;                                                  \
1367       if (upb_fielddef_haspresence(f)) {                                        \
1368         is_default = layout_has(desc->layout, Message_data(msg), f) == Qfalse;  \
1369       } else if (upb_msgdef_syntax(desc->msgdef) == UPB_SYNTAX_PROTO3) {        \
1370         is_default = default_value == value;                                    \
1371       }                                                                         \
1372       if (is_matching_oneof || emit_defaults || !is_default) {                  \
1373         upb_sink_put##upbtype(sink, sel, value);                                \
1374       }                                                                         \
1375     }                                                                           \
1376     break;
1377 
1378       switch (upb_fielddef_type(f)) {
1379         T(UPB_TYPE_FLOAT,  float,  float, 0.0)
1380         T(UPB_TYPE_DOUBLE, double, double, 0.0)
1381         T(UPB_TYPE_BOOL,   bool,   uint8_t, 0)
1382         case UPB_TYPE_ENUM:
1383         T(UPB_TYPE_INT32,  int32,  int32_t, 0)
1384         T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
1385         T(UPB_TYPE_INT64,  int64,  int64_t, 0)
1386         T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
1387 
1388         case UPB_TYPE_STRING:
1389         case UPB_TYPE_BYTES:
1390         case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
1391       }
1392 
1393 #undef T
1394 
1395     }
1396   }
1397 
1398   stringsink* unknown = msg->unknown_fields;
1399   if (unknown != NULL) {
1400     upb_sink_putunknown(sink, unknown->ptr, unknown->len);
1401   }
1402 
1403   if (open_msg) {
1404     upb_sink_endmsg(sink, &status);
1405   }
1406 }
1407 
msgdef_pb_serialize_handlers(Descriptor * desc)1408 static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
1409   if (desc->pb_serialize_handlers == NULL) {
1410     desc->pb_serialize_handlers =
1411         upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
1412   }
1413   return desc->pb_serialize_handlers;
1414 }
1415 
msgdef_json_serialize_handlers(Descriptor * desc,bool preserve_proto_fieldnames)1416 static const upb_handlers* msgdef_json_serialize_handlers(
1417     Descriptor* desc, bool preserve_proto_fieldnames) {
1418   if (preserve_proto_fieldnames) {
1419     if (desc->json_serialize_handlers == NULL) {
1420       desc->json_serialize_handlers =
1421           upb_json_printer_newhandlers(
1422               desc->msgdef, true, &desc->json_serialize_handlers);
1423     }
1424     return desc->json_serialize_handlers;
1425   } else {
1426     if (desc->json_serialize_handlers_preserve == NULL) {
1427       desc->json_serialize_handlers_preserve =
1428           upb_json_printer_newhandlers(
1429               desc->msgdef, false, &desc->json_serialize_handlers_preserve);
1430     }
1431     return desc->json_serialize_handlers_preserve;
1432   }
1433 }
1434 
1435 /*
1436  * call-seq:
1437  *     MessageClass.encode(msg) => bytes
1438  *
1439  * Encodes the given message object to its serialized form in protocol buffers
1440  * wire format.
1441  */
Message_encode(VALUE klass,VALUE msg_rb)1442 VALUE Message_encode(VALUE klass, VALUE msg_rb) {
1443   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1444   Descriptor* desc = ruby_to_Descriptor(descriptor);
1445 
1446   stringsink sink;
1447   stringsink_init(&sink);
1448 
1449   {
1450     const upb_handlers* serialize_handlers =
1451         msgdef_pb_serialize_handlers(desc);
1452 
1453     stackenv se;
1454     upb_pb_encoder* encoder;
1455     VALUE ret;
1456 
1457     stackenv_init(&se, "Error occurred during encoding: %s");
1458     encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
1459 
1460     putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false, false, true);
1461 
1462     ret = rb_str_new(sink.ptr, sink.len);
1463 
1464     stackenv_uninit(&se);
1465     stringsink_uninit(&sink);
1466 
1467     return ret;
1468   }
1469 }
1470 
1471 /*
1472  * call-seq:
1473  *     MessageClass.encode_json(msg, options = {}) => json_string
1474  *
1475  * Encodes the given message object into its serialized JSON representation.
1476  * @param options [Hash] options for the decoder
1477  *  preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase)
1478  *  emit_defaults: set true to emit 0/false values (default is to omit them)
1479  */
Message_encode_json(int argc,VALUE * argv,VALUE klass)1480 VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
1481   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1482   Descriptor* desc = ruby_to_Descriptor(descriptor);
1483   VALUE msg_rb;
1484   VALUE preserve_proto_fieldnames = Qfalse;
1485   VALUE emit_defaults = Qfalse;
1486   stringsink sink;
1487 
1488   if (argc < 1 || argc > 2) {
1489     rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
1490   }
1491 
1492   msg_rb = argv[0];
1493 
1494   if (argc == 2) {
1495     VALUE hash_args = argv[1];
1496     if (TYPE(hash_args) != T_HASH) {
1497       rb_raise(rb_eArgError, "Expected hash arguments.");
1498     }
1499     preserve_proto_fieldnames = rb_hash_lookup2(
1500         hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
1501 
1502     emit_defaults = rb_hash_lookup2(
1503         hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
1504   }
1505 
1506   stringsink_init(&sink);
1507 
1508   {
1509     const upb_handlers* serialize_handlers =
1510         msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
1511     upb_json_printer* printer;
1512     stackenv se;
1513     VALUE ret;
1514 
1515     stackenv_init(&se, "Error occurred during encoding: %s");
1516     printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
1517 
1518     putmsg(msg_rb, desc, upb_json_printer_input(printer), 0,
1519            RTEST(emit_defaults), true, true);
1520 
1521     ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
1522 
1523     stackenv_uninit(&se);
1524     stringsink_uninit(&sink);
1525 
1526     return ret;
1527   }
1528 }
1529 
discard_unknown(VALUE msg_rb,const Descriptor * desc)1530 static void discard_unknown(VALUE msg_rb, const Descriptor* desc) {
1531   MessageHeader* msg;
1532   upb_msg_field_iter it;
1533 
1534   TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
1535 
1536   stringsink* unknown = msg->unknown_fields;
1537   if (unknown != NULL) {
1538     stringsink_uninit(unknown);
1539     msg->unknown_fields = NULL;
1540   }
1541 
1542   for (upb_msg_field_begin(&it, desc->msgdef);
1543        !upb_msg_field_done(&it);
1544        upb_msg_field_next(&it)) {
1545     upb_fielddef *f = upb_msg_iter_field(&it);
1546     uint32_t offset =
1547         desc->layout->fields[upb_fielddef_index(f)].offset +
1548         sizeof(MessageHeader);
1549 
1550     if (upb_fielddef_containingoneof(f)) {
1551       uint32_t oneof_case_offset =
1552           desc->layout->fields[upb_fielddef_index(f)].case_offset +
1553           sizeof(MessageHeader);
1554       // For a oneof, check that this field is actually present -- skip all the
1555       // below if not.
1556       if (DEREF(msg, oneof_case_offset, uint32_t) !=
1557           upb_fielddef_number(f)) {
1558         continue;
1559       }
1560       // Otherwise, fall through to the appropriate singular-field handler
1561       // below.
1562     }
1563 
1564     if (!upb_fielddef_issubmsg(f)) {
1565       continue;
1566     }
1567 
1568     if (is_map_field(f)) {
1569       if (!upb_fielddef_issubmsg(map_field_value(f))) continue;
1570       VALUE map = DEREF(msg, offset, VALUE);
1571       if (map == Qnil) continue;
1572       Map_iter map_it;
1573       for (Map_begin(map, &map_it); !Map_done(&map_it); Map_next(&map_it)) {
1574         VALUE submsg = Map_iter_value(&map_it);
1575         VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1576         const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1577         discard_unknown(submsg, subdesc);
1578       }
1579     } else if (upb_fielddef_isseq(f)) {
1580       VALUE ary = DEREF(msg, offset, VALUE);
1581       if (ary == Qnil) continue;
1582       int size = NUM2INT(RepeatedField_length(ary));
1583       for (int i = 0; i < size; i++) {
1584         void* memory = RepeatedField_index_native(ary, i);
1585         VALUE submsg = *((VALUE *)memory);
1586         VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1587         const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1588         discard_unknown(submsg, subdesc);
1589       }
1590     } else {
1591       VALUE submsg = DEREF(msg, offset, VALUE);
1592       if (submsg == Qnil) continue;
1593       VALUE descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
1594       const Descriptor* subdesc = ruby_to_Descriptor(descriptor);
1595       discard_unknown(submsg, subdesc);
1596     }
1597   }
1598 }
1599 
1600 /*
1601  * call-seq:
1602  *     Google::Protobuf.discard_unknown(msg)
1603  *
1604  * Discard unknown fields in the given message object and recursively discard
1605  * unknown fields in submessages.
1606  */
Google_Protobuf_discard_unknown(VALUE self,VALUE msg_rb)1607 VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
1608   VALUE klass = CLASS_OF(msg_rb);
1609   VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
1610   Descriptor* desc = ruby_to_Descriptor(descriptor);
1611   if (klass == cRepeatedField || klass == cMap) {
1612     rb_raise(rb_eArgError, "Expected proto msg for discard unknown.");
1613   } else {
1614     discard_unknown(msg_rb, desc);
1615   }
1616   return Qnil;
1617 }
1618