encode_decode.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. #include "protobuf.h"
  31. // This function is equivalent to rb_str_cat(), but unlike the real
  32. // rb_str_cat(), it doesn't leak memory in some versions of Ruby.
  33. // For more information, see:
  34. // https://bugs.ruby-lang.org/issues/11328
  35. VALUE noleak_rb_str_cat(VALUE rb_str, const char *str, long len) {
  36. char *p;
  37. size_t oldlen = RSTRING_LEN(rb_str);
  38. rb_str_modify_expand(rb_str, len);
  39. p = RSTRING_PTR(rb_str);
  40. memcpy(p + oldlen, str, len);
  41. rb_str_set_len(rb_str, oldlen + len);
  42. return rb_str;
  43. }
  44. // -----------------------------------------------------------------------------
  45. // Parsing.
  46. // -----------------------------------------------------------------------------
  47. #define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
  48. // Creates a handlerdata that simply contains the offset for this field.
  49. static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
  50. size_t* hd_ofs = ALLOC(size_t);
  51. *hd_ofs = ofs;
  52. upb_handlers_addcleanup(h, hd_ofs, xfree);
  53. return hd_ofs;
  54. }
  55. typedef struct {
  56. size_t ofs;
  57. const upb_msgdef *md;
  58. } submsg_handlerdata_t;
  59. // Creates a handlerdata that contains offset and submessage type information.
  60. static const void *newsubmsghandlerdata(upb_handlers* h, uint32_t ofs,
  61. const upb_fielddef* f) {
  62. submsg_handlerdata_t *hd = ALLOC(submsg_handlerdata_t);
  63. hd->ofs = ofs;
  64. hd->md = upb_fielddef_msgsubdef(f);
  65. upb_handlers_addcleanup(h, hd, xfree);
  66. return hd;
  67. }
  68. typedef struct {
  69. size_t ofs; // union data slot
  70. size_t case_ofs; // oneof_case field
  71. uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
  72. const upb_msgdef *md; // msgdef, for oneof submessage handler
  73. } oneof_handlerdata_t;
  74. static const void *newoneofhandlerdata(upb_handlers *h,
  75. uint32_t ofs,
  76. uint32_t case_ofs,
  77. const upb_fielddef *f) {
  78. oneof_handlerdata_t *hd = ALLOC(oneof_handlerdata_t);
  79. hd->ofs = ofs;
  80. hd->case_ofs = case_ofs;
  81. // We reuse the field tag number as a oneof union discriminant tag. Note that
  82. // we don't expose these numbers to the user, so the only requirement is that
  83. // we have some unique ID for each union case/possibility. The field tag
  84. // numbers are already present and are easy to use so there's no reason to
  85. // create a separate ID space. In addition, using the field tag number here
  86. // lets us easily look up the field in the oneof accessor.
  87. hd->oneof_case_num = upb_fielddef_number(f);
  88. if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
  89. hd->md = upb_fielddef_msgsubdef(f);
  90. } else {
  91. hd->md = NULL;
  92. }
  93. upb_handlers_addcleanup(h, hd, xfree);
  94. return hd;
  95. }
  96. // A handler that starts a repeated field. Gets the Repeated*Field instance for
  97. // this field (such an instance always exists even in an empty message).
  98. static void *startseq_handler(void* closure, const void* hd) {
  99. MessageHeader* msg = closure;
  100. const size_t *ofs = hd;
  101. return (void*)DEREF(msg, *ofs, VALUE);
  102. }
  103. // Handlers that append primitive values to a repeated field.
  104. #define DEFINE_APPEND_HANDLER(type, ctype) \
  105. static bool append##type##_handler(void *closure, const void *hd, \
  106. ctype val) { \
  107. VALUE ary = (VALUE)closure; \
  108. RepeatedField_push_native(ary, &val); \
  109. return true; \
  110. }
  111. DEFINE_APPEND_HANDLER(bool, bool)
  112. DEFINE_APPEND_HANDLER(int32, int32_t)
  113. DEFINE_APPEND_HANDLER(uint32, uint32_t)
  114. DEFINE_APPEND_HANDLER(float, float)
  115. DEFINE_APPEND_HANDLER(int64, int64_t)
  116. DEFINE_APPEND_HANDLER(uint64, uint64_t)
  117. DEFINE_APPEND_HANDLER(double, double)
  118. // Appends a string to a repeated field.
  119. static void* appendstr_handler(void *closure,
  120. const void *hd,
  121. size_t size_hint) {
  122. VALUE ary = (VALUE)closure;
  123. VALUE str = rb_str_new2("");
  124. rb_enc_associate(str, kRubyStringUtf8Encoding);
  125. RepeatedField_push_native(ary, &str);
  126. return (void*)str;
  127. }
  128. // Appends a 'bytes' string to a repeated field.
  129. static void* appendbytes_handler(void *closure,
  130. const void *hd,
  131. size_t size_hint) {
  132. VALUE ary = (VALUE)closure;
  133. VALUE str = rb_str_new2("");
  134. rb_enc_associate(str, kRubyString8bitEncoding);
  135. RepeatedField_push_native(ary, &str);
  136. return (void*)str;
  137. }
  138. // Sets a non-repeated string field in a message.
  139. static void* str_handler(void *closure,
  140. const void *hd,
  141. size_t size_hint) {
  142. MessageHeader* msg = closure;
  143. const size_t *ofs = hd;
  144. VALUE str = rb_str_new2("");
  145. rb_enc_associate(str, kRubyStringUtf8Encoding);
  146. DEREF(msg, *ofs, VALUE) = str;
  147. return (void*)str;
  148. }
  149. // Sets a non-repeated 'bytes' field in a message.
  150. static void* bytes_handler(void *closure,
  151. const void *hd,
  152. size_t size_hint) {
  153. MessageHeader* msg = closure;
  154. const size_t *ofs = hd;
  155. VALUE str = rb_str_new2("");
  156. rb_enc_associate(str, kRubyString8bitEncoding);
  157. DEREF(msg, *ofs, VALUE) = str;
  158. return (void*)str;
  159. }
  160. static size_t stringdata_handler(void* closure, const void* hd,
  161. const char* str, size_t len,
  162. const upb_bufhandle* handle) {
  163. VALUE rb_str = (VALUE)closure;
  164. noleak_rb_str_cat(rb_str, str, len);
  165. return len;
  166. }
  167. static bool stringdata_end_handler(void* closure, const void* hd) {
  168. MessageHeader* msg = closure;
  169. const size_t *ofs = hd;
  170. VALUE rb_str = DEREF(msg, *ofs, VALUE);
  171. rb_obj_freeze(rb_str);
  172. return true;
  173. }
  174. static bool appendstring_end_handler(void* closure, const void* hd) {
  175. VALUE ary = (VALUE)closure;
  176. int size = RepeatedField_size(ary);
  177. VALUE* last = RepeatedField_index_native(ary, size - 1);
  178. VALUE rb_str = *last;
  179. rb_obj_freeze(rb_str);
  180. return true;
  181. }
  182. // Appends a submessage to a repeated field (a regular Ruby array for now).
  183. static void *appendsubmsg_handler(void *closure, const void *hd) {
  184. VALUE ary = (VALUE)closure;
  185. const submsg_handlerdata_t *submsgdata = hd;
  186. VALUE subdesc =
  187. get_def_obj((void*)submsgdata->md);
  188. VALUE subklass = Descriptor_msgclass(subdesc);
  189. MessageHeader* submsg;
  190. VALUE submsg_rb = rb_class_new_instance(0, NULL, subklass);
  191. RepeatedField_push(ary, submsg_rb);
  192. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  193. return submsg;
  194. }
  195. // Sets a non-repeated submessage field in a message.
  196. static void *submsg_handler(void *closure, const void *hd) {
  197. MessageHeader* msg = closure;
  198. const submsg_handlerdata_t* submsgdata = hd;
  199. VALUE subdesc =
  200. get_def_obj((void*)submsgdata->md);
  201. VALUE subklass = Descriptor_msgclass(subdesc);
  202. VALUE submsg_rb;
  203. MessageHeader* submsg;
  204. if (DEREF(msg, submsgdata->ofs, VALUE) == Qnil) {
  205. DEREF(msg, submsgdata->ofs, VALUE) =
  206. rb_class_new_instance(0, NULL, subklass);
  207. }
  208. submsg_rb = DEREF(msg, submsgdata->ofs, VALUE);
  209. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  210. return submsg;
  211. }
  212. // Handler data for startmap/endmap handlers.
  213. typedef struct {
  214. size_t ofs;
  215. upb_fieldtype_t key_field_type;
  216. upb_fieldtype_t value_field_type;
  217. // We know that we can hold this reference because the handlerdata has the
  218. // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
  219. // a reference to the upb_msgdef, which in turn has references to its subdefs.
  220. const upb_def* value_field_subdef;
  221. } map_handlerdata_t;
  222. // Temporary frame for map parsing: at the beginning of a map entry message, a
  223. // submsg handler allocates a frame to hold (i) a reference to the Map object
  224. // into which this message will be inserted and (ii) storage slots to
  225. // temporarily hold the key and value for this map entry until the end of the
  226. // submessage. When the submessage ends, another handler is called to insert the
  227. // value into the map.
  228. typedef struct {
  229. VALUE map;
  230. const map_handlerdata_t* handlerdata;
  231. char key_storage[NATIVE_SLOT_MAX_SIZE];
  232. char value_storage[NATIVE_SLOT_MAX_SIZE];
  233. } map_parse_frame_t;
  234. static void MapParseFrame_mark(void* _self) {
  235. map_parse_frame_t* frame = _self;
  236. // This shouldn't strictly be necessary since this should be rooted by the
  237. // message itself, but it can't hurt.
  238. rb_gc_mark(frame->map);
  239. native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
  240. native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
  241. }
  242. void MapParseFrame_free(void* self) {
  243. xfree(self);
  244. }
  245. rb_data_type_t MapParseFrame_type = {
  246. "MapParseFrame",
  247. { MapParseFrame_mark, MapParseFrame_free, NULL },
  248. };
  249. static map_parse_frame_t* map_push_frame(VALUE map,
  250. const map_handlerdata_t* handlerdata) {
  251. map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
  252. frame->handlerdata = handlerdata;
  253. frame->map = map;
  254. native_slot_init(handlerdata->key_field_type, &frame->key_storage);
  255. native_slot_init(handlerdata->value_field_type, &frame->value_storage);
  256. Map_set_frame(map,
  257. TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
  258. return frame;
  259. }
  260. // Handler to begin a map entry: allocates a temporary frame. This is the
  261. // 'startsubmsg' handler on the msgdef that contains the map field.
  262. static void *startmapentry_handler(void *closure, const void *hd) {
  263. MessageHeader* msg = closure;
  264. const map_handlerdata_t* mapdata = hd;
  265. VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
  266. return map_push_frame(map_rb, mapdata);
  267. }
  268. // Handler to end a map entry: inserts the value defined during the message into
  269. // the map. This is the 'endmsg' handler on the map entry msgdef.
  270. static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
  271. map_parse_frame_t* frame = closure;
  272. const map_handlerdata_t* mapdata = hd;
  273. VALUE key = native_slot_get(
  274. mapdata->key_field_type, Qnil,
  275. &frame->key_storage);
  276. VALUE value_field_typeclass = Qnil;
  277. VALUE value;
  278. if (mapdata->value_field_type == UPB_TYPE_MESSAGE ||
  279. mapdata->value_field_type == UPB_TYPE_ENUM) {
  280. value_field_typeclass = get_def_obj(mapdata->value_field_subdef);
  281. }
  282. value = native_slot_get(
  283. mapdata->value_field_type, value_field_typeclass,
  284. &frame->value_storage);
  285. Map_index_set(frame->map, key, value);
  286. Map_set_frame(frame->map, Qnil);
  287. return true;
  288. }
  289. // Allocates a new map_handlerdata_t given the map entry message definition. If
  290. // the offset of the field within the parent message is also given, that is
  291. // added to the handler data as well. Note that this is called *twice* per map
  292. // field: once in the parent message handler setup when setting the startsubmsg
  293. // handler and once in the map entry message handler setup when setting the
  294. // key/value and endmsg handlers. The reason is that there is no easy way to
  295. // pass the handlerdata down to the sub-message handler setup.
  296. static map_handlerdata_t* new_map_handlerdata(
  297. size_t ofs,
  298. const upb_msgdef* mapentry_def,
  299. Descriptor* desc) {
  300. const upb_fielddef* key_field;
  301. const upb_fielddef* value_field;
  302. map_handlerdata_t* hd = ALLOC(map_handlerdata_t);
  303. hd->ofs = ofs;
  304. key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
  305. assert(key_field != NULL);
  306. hd->key_field_type = upb_fielddef_type(key_field);
  307. value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
  308. assert(value_field != NULL);
  309. hd->value_field_type = upb_fielddef_type(value_field);
  310. hd->value_field_subdef = upb_fielddef_subdef(value_field);
  311. return hd;
  312. }
  313. // Handlers that set primitive values in oneofs.
  314. #define DEFINE_ONEOF_HANDLER(type, ctype) \
  315. static bool oneof##type##_handler(void *closure, const void *hd, \
  316. ctype val) { \
  317. const oneof_handlerdata_t *oneofdata = hd; \
  318. DEREF(closure, oneofdata->case_ofs, uint32_t) = \
  319. oneofdata->oneof_case_num; \
  320. DEREF(closure, oneofdata->ofs, ctype) = val; \
  321. return true; \
  322. }
  323. DEFINE_ONEOF_HANDLER(bool, bool)
  324. DEFINE_ONEOF_HANDLER(int32, int32_t)
  325. DEFINE_ONEOF_HANDLER(uint32, uint32_t)
  326. DEFINE_ONEOF_HANDLER(float, float)
  327. DEFINE_ONEOF_HANDLER(int64, int64_t)
  328. DEFINE_ONEOF_HANDLER(uint64, uint64_t)
  329. DEFINE_ONEOF_HANDLER(double, double)
  330. #undef DEFINE_ONEOF_HANDLER
  331. // Handlers for strings in a oneof.
  332. static void *oneofstr_handler(void *closure,
  333. const void *hd,
  334. size_t size_hint) {
  335. MessageHeader* msg = closure;
  336. const oneof_handlerdata_t *oneofdata = hd;
  337. VALUE str = rb_str_new2("");
  338. rb_enc_associate(str, kRubyStringUtf8Encoding);
  339. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  340. oneofdata->oneof_case_num;
  341. DEREF(msg, oneofdata->ofs, VALUE) = str;
  342. return (void*)str;
  343. }
  344. static void *oneofbytes_handler(void *closure,
  345. const void *hd,
  346. size_t size_hint) {
  347. MessageHeader* msg = closure;
  348. const oneof_handlerdata_t *oneofdata = hd;
  349. VALUE str = rb_str_new2("");
  350. rb_enc_associate(str, kRubyString8bitEncoding);
  351. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  352. oneofdata->oneof_case_num;
  353. DEREF(msg, oneofdata->ofs, VALUE) = str;
  354. return (void*)str;
  355. }
  356. static bool oneofstring_end_handler(void* closure, const void* hd) {
  357. MessageHeader* msg = closure;
  358. const oneof_handlerdata_t *oneofdata = hd;
  359. rb_obj_freeze(DEREF(msg, oneofdata->ofs, VALUE));
  360. return true;
  361. }
  362. // Handler for a submessage field in a oneof.
  363. static void *oneofsubmsg_handler(void *closure,
  364. const void *hd) {
  365. MessageHeader* msg = closure;
  366. const oneof_handlerdata_t *oneofdata = hd;
  367. uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
  368. VALUE subdesc =
  369. get_def_obj((void*)oneofdata->md);
  370. VALUE subklass = Descriptor_msgclass(subdesc);
  371. VALUE submsg_rb;
  372. MessageHeader* submsg;
  373. if (oldcase != oneofdata->oneof_case_num ||
  374. DEREF(msg, oneofdata->ofs, VALUE) == Qnil) {
  375. DEREF(msg, oneofdata->ofs, VALUE) =
  376. rb_class_new_instance(0, NULL, subklass);
  377. }
  378. // Set the oneof case *after* allocating the new class instance -- otherwise,
  379. // if the Ruby GC is invoked as part of a call into the VM, it might invoke
  380. // our mark routines, and our mark routines might see the case value
  381. // indicating a VALUE is present and expect a valid VALUE. See comment in
  382. // layout_set() for more detail: basically, the change to the value and the
  383. // case must be atomic w.r.t. the Ruby VM.
  384. DEREF(msg, oneofdata->case_ofs, uint32_t) =
  385. oneofdata->oneof_case_num;
  386. submsg_rb = DEREF(msg, oneofdata->ofs, VALUE);
  387. TypedData_Get_Struct(submsg_rb, MessageHeader, &Message_type, submsg);
  388. return submsg;
  389. }
  390. // Set up handlers for a repeated field.
  391. static void add_handlers_for_repeated_field(upb_handlers *h,
  392. const upb_fielddef *f,
  393. size_t offset) {
  394. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  395. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  396. upb_handlers_setstartseq(h, f, startseq_handler, &attr);
  397. upb_handlerattr_uninit(&attr);
  398. switch (upb_fielddef_type(f)) {
  399. #define SET_HANDLER(utype, ltype) \
  400. case utype: \
  401. upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
  402. break;
  403. SET_HANDLER(UPB_TYPE_BOOL, bool);
  404. SET_HANDLER(UPB_TYPE_INT32, int32);
  405. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  406. SET_HANDLER(UPB_TYPE_ENUM, int32);
  407. SET_HANDLER(UPB_TYPE_FLOAT, float);
  408. SET_HANDLER(UPB_TYPE_INT64, int64);
  409. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  410. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  411. #undef SET_HANDLER
  412. case UPB_TYPE_STRING:
  413. case UPB_TYPE_BYTES: {
  414. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  415. upb_handlers_setstartstr(h, f, is_bytes ?
  416. appendbytes_handler : appendstr_handler,
  417. NULL);
  418. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  419. upb_handlers_setendstr(h, f, appendstring_end_handler, NULL);
  420. break;
  421. }
  422. case UPB_TYPE_MESSAGE: {
  423. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  424. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
  425. upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
  426. upb_handlerattr_uninit(&attr);
  427. break;
  428. }
  429. }
  430. }
  431. // Set up handlers for a singular field.
  432. static void add_handlers_for_singular_field(upb_handlers *h,
  433. const upb_fielddef *f,
  434. size_t offset) {
  435. switch (upb_fielddef_type(f)) {
  436. case UPB_TYPE_BOOL:
  437. case UPB_TYPE_INT32:
  438. case UPB_TYPE_UINT32:
  439. case UPB_TYPE_ENUM:
  440. case UPB_TYPE_FLOAT:
  441. case UPB_TYPE_INT64:
  442. case UPB_TYPE_UINT64:
  443. case UPB_TYPE_DOUBLE:
  444. upb_msg_setscalarhandler(h, f, offset, -1);
  445. break;
  446. case UPB_TYPE_STRING:
  447. case UPB_TYPE_BYTES: {
  448. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  449. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  450. upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
  451. upb_handlers_setstartstr(h, f,
  452. is_bytes ? bytes_handler : str_handler,
  453. &attr);
  454. upb_handlers_setstring(h, f, stringdata_handler, &attr);
  455. upb_handlers_setendstr(h, f, stringdata_end_handler, &attr);
  456. upb_handlerattr_uninit(&attr);
  457. break;
  458. }
  459. case UPB_TYPE_MESSAGE: {
  460. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  461. upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
  462. upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
  463. upb_handlerattr_uninit(&attr);
  464. break;
  465. }
  466. }
  467. }
  468. // Adds handlers to a map field.
  469. static void add_handlers_for_mapfield(upb_handlers* h,
  470. const upb_fielddef* fielddef,
  471. size_t offset,
  472. Descriptor* desc) {
  473. const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
  474. map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
  475. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  476. upb_handlers_addcleanup(h, hd, xfree);
  477. upb_handlerattr_sethandlerdata(&attr, hd);
  478. upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
  479. upb_handlerattr_uninit(&attr);
  480. }
  481. // Adds handlers to a map-entry msgdef.
  482. static void add_handlers_for_mapentry(const upb_msgdef* msgdef,
  483. upb_handlers* h,
  484. Descriptor* desc) {
  485. const upb_fielddef* key_field = map_entry_key(msgdef);
  486. const upb_fielddef* value_field = map_entry_value(msgdef);
  487. map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
  488. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  489. upb_handlers_addcleanup(h, hd, xfree);
  490. upb_handlerattr_sethandlerdata(&attr, hd);
  491. upb_handlers_setendmsg(h, endmap_handler, &attr);
  492. add_handlers_for_singular_field(
  493. h, key_field,
  494. offsetof(map_parse_frame_t, key_storage));
  495. add_handlers_for_singular_field(
  496. h, value_field,
  497. offsetof(map_parse_frame_t, value_storage));
  498. }
  499. // Set up handlers for a oneof field.
  500. static void add_handlers_for_oneof_field(upb_handlers *h,
  501. const upb_fielddef *f,
  502. size_t offset,
  503. size_t oneof_case_offset) {
  504. upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
  505. upb_handlerattr_sethandlerdata(
  506. &attr, newoneofhandlerdata(h, offset, oneof_case_offset, f));
  507. switch (upb_fielddef_type(f)) {
  508. #define SET_HANDLER(utype, ltype) \
  509. case utype: \
  510. upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
  511. break;
  512. SET_HANDLER(UPB_TYPE_BOOL, bool);
  513. SET_HANDLER(UPB_TYPE_INT32, int32);
  514. SET_HANDLER(UPB_TYPE_UINT32, uint32);
  515. SET_HANDLER(UPB_TYPE_ENUM, int32);
  516. SET_HANDLER(UPB_TYPE_FLOAT, float);
  517. SET_HANDLER(UPB_TYPE_INT64, int64);
  518. SET_HANDLER(UPB_TYPE_UINT64, uint64);
  519. SET_HANDLER(UPB_TYPE_DOUBLE, double);
  520. #undef SET_HANDLER
  521. case UPB_TYPE_STRING:
  522. case UPB_TYPE_BYTES: {
  523. bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
  524. upb_handlers_setstartstr(h, f, is_bytes ?
  525. oneofbytes_handler : oneofstr_handler,
  526. &attr);
  527. upb_handlers_setstring(h, f, stringdata_handler, NULL);
  528. upb_handlers_setendstr(h, f, oneofstring_end_handler, &attr);
  529. break;
  530. }
  531. case UPB_TYPE_MESSAGE: {
  532. upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
  533. break;
  534. }
  535. }
  536. upb_handlerattr_uninit(&attr);
  537. }
  538. static void add_handlers_for_message(const void *closure, upb_handlers *h) {
  539. const upb_msgdef* msgdef = upb_handlers_msgdef(h);
  540. Descriptor* desc = ruby_to_Descriptor(get_def_obj((void*)msgdef));
  541. upb_msg_field_iter i;
  542. // If this is a mapentry message type, set up a special set of handlers and
  543. // bail out of the normal (user-defined) message type handling.
  544. if (upb_msgdef_mapentry(msgdef)) {
  545. add_handlers_for_mapentry(msgdef, h, desc);
  546. return;
  547. }
  548. // Ensure layout exists. We may be invoked to create handlers for a given
  549. // message if we are included as a submsg of another message type before our
  550. // class is actually built, so to work around this, we just create the layout
  551. // (and handlers, in the class-building function) on-demand.
  552. if (desc->layout == NULL) {
  553. desc->layout = create_layout(desc->msgdef);
  554. }
  555. for (upb_msg_field_begin(&i, desc->msgdef);
  556. !upb_msg_field_done(&i);
  557. upb_msg_field_next(&i)) {
  558. const upb_fielddef *f = upb_msg_iter_field(&i);
  559. size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
  560. sizeof(MessageHeader);
  561. if (upb_fielddef_containingoneof(f)) {
  562. size_t oneof_case_offset =
  563. desc->layout->fields[upb_fielddef_index(f)].case_offset +
  564. sizeof(MessageHeader);
  565. add_handlers_for_oneof_field(h, f, offset, oneof_case_offset);
  566. } else if (is_map_field(f)) {
  567. add_handlers_for_mapfield(h, f, offset, desc);
  568. } else if (upb_fielddef_isseq(f)) {
  569. add_handlers_for_repeated_field(h, f, offset);
  570. } else {
  571. add_handlers_for_singular_field(h, f, offset);
  572. }
  573. }
  574. }
  575. // Creates upb handlers for populating a message.
  576. static const upb_handlers *new_fill_handlers(Descriptor* desc,
  577. const void* owner) {
  578. // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
  579. // handlers, reuse subdef handlers so that e.g. if we already parse
  580. // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
  581. // parse A-with-field-of-type-B-with-field-of-type-C.
  582. return upb_handlers_newfrozen(desc->msgdef, owner,
  583. add_handlers_for_message, NULL);
  584. }
  585. // Constructs the handlers for filling a message's data into an in-memory
  586. // object.
  587. const upb_handlers* get_fill_handlers(Descriptor* desc) {
  588. if (!desc->fill_handlers) {
  589. desc->fill_handlers =
  590. new_fill_handlers(desc, &desc->fill_handlers);
  591. }
  592. return desc->fill_handlers;
  593. }
  594. // Constructs the upb decoder method for parsing messages of this type.
  595. // This is called from the message class creation code.
  596. const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
  597. const void* owner) {
  598. const upb_handlers* handlers = get_fill_handlers(desc);
  599. upb_pbdecodermethodopts opts;
  600. upb_pbdecodermethodopts_init(&opts, handlers);
  601. return upb_pbdecodermethod_new(&opts, owner);
  602. }
  603. static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
  604. if (desc->fill_method == NULL) {
  605. desc->fill_method = new_fillmsg_decodermethod(
  606. desc, &desc->fill_method);
  607. }
  608. return desc->fill_method;
  609. }
  610. static const upb_json_parsermethod *msgdef_jsonparsermethod(Descriptor* desc) {
  611. if (desc->json_fill_method == NULL) {
  612. desc->json_fill_method =
  613. upb_json_parsermethod_new(desc->msgdef, &desc->json_fill_method);
  614. }
  615. return desc->json_fill_method;
  616. }
  617. // Stack-allocated context during an encode/decode operation. Contains the upb
  618. // environment and its stack-based allocator, an initial buffer for allocations
  619. // to avoid malloc() when possible, and a template for Ruby exception messages
  620. // if any error occurs.
  621. #define STACK_ENV_STACKBYTES 4096
  622. typedef struct {
  623. upb_env env;
  624. const char* ruby_error_template;
  625. char allocbuf[STACK_ENV_STACKBYTES];
  626. } stackenv;
  627. static void stackenv_init(stackenv* se, const char* errmsg);
  628. static void stackenv_uninit(stackenv* se);
  629. // Callback invoked by upb if any error occurs during parsing or serialization.
  630. static bool env_error_func(void* ud, const upb_status* status) {
  631. stackenv* se = ud;
  632. // Free the env -- rb_raise will longjmp up the stack past the encode/decode
  633. // function so it would not otherwise have been freed.
  634. stackenv_uninit(se);
  635. // TODO(haberman): have a way to verify that this is actually a parse error,
  636. // instead of just throwing "parse error" unconditionally.
  637. rb_raise(cParseError, se->ruby_error_template, upb_status_errmsg(status));
  638. // Never reached: rb_raise() always longjmp()s up the stack, past all of our
  639. // code, back to Ruby.
  640. return false;
  641. }
  642. static void stackenv_init(stackenv* se, const char* errmsg) {
  643. se->ruby_error_template = errmsg;
  644. upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
  645. upb_env_seterrorfunc(&se->env, env_error_func, se);
  646. }
  647. static void stackenv_uninit(stackenv* se) {
  648. upb_env_uninit(&se->env);
  649. }
  650. /*
  651. * call-seq:
  652. * MessageClass.decode(data) => message
  653. *
  654. * Decodes the given data (as a string containing bytes in protocol buffers wire
  655. * format) under the interpretration given by this message class's definition
  656. * and returns a message object with the corresponding field values.
  657. */
  658. VALUE Message_decode(VALUE klass, VALUE data) {
  659. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  660. Descriptor* desc = ruby_to_Descriptor(descriptor);
  661. VALUE msgklass = Descriptor_msgclass(descriptor);
  662. VALUE msg_rb;
  663. MessageHeader* msg;
  664. if (TYPE(data) != T_STRING) {
  665. rb_raise(rb_eArgError, "Expected string for binary protobuf data.");
  666. }
  667. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  668. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  669. {
  670. const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
  671. const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
  672. stackenv se;
  673. upb_sink sink;
  674. upb_pbdecoder* decoder;
  675. stackenv_init(&se, "Error occurred during parsing: %s");
  676. upb_sink_reset(&sink, h, msg);
  677. decoder = upb_pbdecoder_create(&se.env, method, &sink);
  678. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  679. upb_pbdecoder_input(decoder));
  680. stackenv_uninit(&se);
  681. }
  682. return msg_rb;
  683. }
  684. /*
  685. * call-seq:
  686. * MessageClass.decode_json(data) => message
  687. *
  688. * Decodes the given data (as a string containing bytes in protocol buffers wire
  689. * format) under the interpretration given by this message class's definition
  690. * and returns a message object with the corresponding field values.
  691. */
  692. VALUE Message_decode_json(VALUE klass, VALUE data) {
  693. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  694. Descriptor* desc = ruby_to_Descriptor(descriptor);
  695. VALUE msgklass = Descriptor_msgclass(descriptor);
  696. VALUE msg_rb;
  697. MessageHeader* msg;
  698. if (TYPE(data) != T_STRING) {
  699. rb_raise(rb_eArgError, "Expected string for JSON data.");
  700. }
  701. // TODO(cfallin): Check and respect string encoding. If not UTF-8, we need to
  702. // convert, because string handlers pass data directly to message string
  703. // fields.
  704. msg_rb = rb_class_new_instance(0, NULL, msgklass);
  705. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  706. {
  707. const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
  708. stackenv se;
  709. upb_sink sink;
  710. upb_json_parser* parser;
  711. stackenv_init(&se, "Error occurred during parsing: %s");
  712. upb_sink_reset(&sink, get_fill_handlers(desc), msg);
  713. parser = upb_json_parser_create(&se.env, method, &sink);
  714. upb_bufsrc_putbuf(RSTRING_PTR(data), RSTRING_LEN(data),
  715. upb_json_parser_input(parser));
  716. stackenv_uninit(&se);
  717. }
  718. return msg_rb;
  719. }
  720. // -----------------------------------------------------------------------------
  721. // Serializing.
  722. // -----------------------------------------------------------------------------
  723. //
  724. // The code below also comes from upb's prototype Ruby binding, developed by
  725. // haberman@.
  726. /* stringsink *****************************************************************/
  727. // This should probably be factored into a common upb component.
  728. typedef struct {
  729. upb_byteshandler handler;
  730. upb_bytessink sink;
  731. char *ptr;
  732. size_t len, size;
  733. } stringsink;
  734. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  735. stringsink *sink = _sink;
  736. sink->len = 0;
  737. return sink;
  738. }
  739. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  740. size_t len, const upb_bufhandle *handle) {
  741. stringsink *sink = _sink;
  742. size_t new_size = sink->size;
  743. UPB_UNUSED(hd);
  744. UPB_UNUSED(handle);
  745. while (sink->len + len > new_size) {
  746. new_size *= 2;
  747. }
  748. if (new_size != sink->size) {
  749. sink->ptr = realloc(sink->ptr, new_size);
  750. sink->size = new_size;
  751. }
  752. memcpy(sink->ptr + sink->len, ptr, len);
  753. sink->len += len;
  754. return len;
  755. }
  756. void stringsink_init(stringsink *sink) {
  757. upb_byteshandler_init(&sink->handler);
  758. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  759. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  760. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  761. sink->size = 32;
  762. sink->ptr = malloc(sink->size);
  763. sink->len = 0;
  764. }
  765. void stringsink_uninit(stringsink *sink) {
  766. free(sink->ptr);
  767. }
  768. /* msgvisitor *****************************************************************/
  769. // TODO: If/when we support proto2 semantics in addition to the current proto3
  770. // semantics, which means that we have true field presence, we will want to
  771. // modify msgvisitor so that it emits all present fields rather than all
  772. // non-default-value fields.
  773. static void putmsg(VALUE msg, const Descriptor* desc,
  774. upb_sink *sink, int depth, bool emit_defaults);
  775. static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
  776. upb_selector_t ret;
  777. bool ok = upb_handlers_getselector(f, type, &ret);
  778. UPB_ASSERT(ok);
  779. return ret;
  780. }
  781. static void putstr(VALUE str, const upb_fielddef *f, upb_sink *sink) {
  782. upb_sink subsink;
  783. if (str == Qnil) return;
  784. assert(BUILTIN_TYPE(str) == RUBY_T_STRING);
  785. // We should be guaranteed that the string has the correct encoding because
  786. // we ensured this at assignment time and then froze the string.
  787. if (upb_fielddef_type(f) == UPB_TYPE_STRING) {
  788. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyStringUtf8Encoding);
  789. } else {
  790. assert(rb_enc_from_index(ENCODING_GET(str)) == kRubyString8bitEncoding);
  791. }
  792. upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), RSTRING_LEN(str),
  793. &subsink);
  794. upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), RSTRING_PTR(str),
  795. RSTRING_LEN(str), NULL);
  796. upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
  797. }
  798. static void putsubmsg(VALUE submsg, const upb_fielddef *f, upb_sink *sink,
  799. int depth, bool emit_defaults) {
  800. upb_sink subsink;
  801. VALUE descriptor;
  802. Descriptor* subdesc;
  803. if (submsg == Qnil) return;
  804. descriptor = rb_ivar_get(submsg, descriptor_instancevar_interned);
  805. subdesc = ruby_to_Descriptor(descriptor);
  806. upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
  807. putmsg(submsg, subdesc, &subsink, depth + 1, emit_defaults);
  808. upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  809. }
  810. static void putary(VALUE ary, const upb_fielddef *f, upb_sink *sink,
  811. int depth, bool emit_defaults) {
  812. upb_sink subsink;
  813. upb_fieldtype_t type = upb_fielddef_type(f);
  814. upb_selector_t sel = 0;
  815. int size;
  816. if (ary == Qnil) return;
  817. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  818. if (upb_fielddef_isprimitive(f)) {
  819. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  820. }
  821. size = NUM2INT(RepeatedField_length(ary));
  822. for (int i = 0; i < size; i++) {
  823. void* memory = RepeatedField_index_native(ary, i);
  824. switch (type) {
  825. #define T(upbtypeconst, upbtype, ctype) \
  826. case upbtypeconst: \
  827. upb_sink_put##upbtype(&subsink, sel, *((ctype *)memory)); \
  828. break;
  829. T(UPB_TYPE_FLOAT, float, float)
  830. T(UPB_TYPE_DOUBLE, double, double)
  831. T(UPB_TYPE_BOOL, bool, int8_t)
  832. case UPB_TYPE_ENUM:
  833. T(UPB_TYPE_INT32, int32, int32_t)
  834. T(UPB_TYPE_UINT32, uint32, uint32_t)
  835. T(UPB_TYPE_INT64, int64, int64_t)
  836. T(UPB_TYPE_UINT64, uint64, uint64_t)
  837. case UPB_TYPE_STRING:
  838. case UPB_TYPE_BYTES:
  839. putstr(*((VALUE *)memory), f, &subsink);
  840. break;
  841. case UPB_TYPE_MESSAGE:
  842. putsubmsg(*((VALUE *)memory), f, &subsink, depth, emit_defaults);
  843. break;
  844. #undef T
  845. }
  846. }
  847. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  848. }
  849. static void put_ruby_value(VALUE value,
  850. const upb_fielddef *f,
  851. VALUE type_class,
  852. int depth,
  853. upb_sink *sink,
  854. bool emit_defaults) {
  855. upb_selector_t sel = 0;
  856. if (upb_fielddef_isprimitive(f)) {
  857. sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  858. }
  859. switch (upb_fielddef_type(f)) {
  860. case UPB_TYPE_INT32:
  861. upb_sink_putint32(sink, sel, NUM2INT(value));
  862. break;
  863. case UPB_TYPE_INT64:
  864. upb_sink_putint64(sink, sel, NUM2LL(value));
  865. break;
  866. case UPB_TYPE_UINT32:
  867. upb_sink_putuint32(sink, sel, NUM2UINT(value));
  868. break;
  869. case UPB_TYPE_UINT64:
  870. upb_sink_putuint64(sink, sel, NUM2ULL(value));
  871. break;
  872. case UPB_TYPE_FLOAT:
  873. upb_sink_putfloat(sink, sel, NUM2DBL(value));
  874. break;
  875. case UPB_TYPE_DOUBLE:
  876. upb_sink_putdouble(sink, sel, NUM2DBL(value));
  877. break;
  878. case UPB_TYPE_ENUM: {
  879. if (TYPE(value) == T_SYMBOL) {
  880. value = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  881. }
  882. upb_sink_putint32(sink, sel, NUM2INT(value));
  883. break;
  884. }
  885. case UPB_TYPE_BOOL:
  886. upb_sink_putbool(sink, sel, value == Qtrue);
  887. break;
  888. case UPB_TYPE_STRING:
  889. case UPB_TYPE_BYTES:
  890. putstr(value, f, sink);
  891. break;
  892. case UPB_TYPE_MESSAGE:
  893. putsubmsg(value, f, sink, depth, emit_defaults);
  894. }
  895. }
  896. static void putmap(VALUE map, const upb_fielddef *f, upb_sink *sink,
  897. int depth, bool emit_defaults) {
  898. Map* self;
  899. upb_sink subsink;
  900. const upb_fielddef* key_field;
  901. const upb_fielddef* value_field;
  902. Map_iter it;
  903. if (map == Qnil) return;
  904. self = ruby_to_Map(map);
  905. upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
  906. assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
  907. key_field = map_field_key(f);
  908. value_field = map_field_value(f);
  909. for (Map_begin(map, &it); !Map_done(&it); Map_next(&it)) {
  910. VALUE key = Map_iter_key(&it);
  911. VALUE value = Map_iter_value(&it);
  912. upb_status status;
  913. upb_sink entry_sink;
  914. upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
  915. &entry_sink);
  916. upb_sink_startmsg(&entry_sink);
  917. put_ruby_value(key, key_field, Qnil, depth + 1, &entry_sink, emit_defaults);
  918. put_ruby_value(value, value_field, self->value_type_class, depth + 1,
  919. &entry_sink, emit_defaults);
  920. upb_sink_endmsg(&entry_sink, &status);
  921. upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
  922. }
  923. upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
  924. }
  925. static void putmsg(VALUE msg_rb, const Descriptor* desc,
  926. upb_sink *sink, int depth, bool emit_defaults) {
  927. MessageHeader* msg;
  928. upb_msg_field_iter i;
  929. upb_status status;
  930. upb_sink_startmsg(sink);
  931. // Protect against cycles (possible because users may freely reassign message
  932. // and repeated fields) by imposing a maximum recursion depth.
  933. if (depth > ENCODE_MAX_NESTING) {
  934. rb_raise(rb_eRuntimeError,
  935. "Maximum recursion depth exceeded during encoding.");
  936. }
  937. TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
  938. for (upb_msg_field_begin(&i, desc->msgdef);
  939. !upb_msg_field_done(&i);
  940. upb_msg_field_next(&i)) {
  941. upb_fielddef *f = upb_msg_iter_field(&i);
  942. bool is_matching_oneof = false;
  943. uint32_t offset =
  944. desc->layout->fields[upb_fielddef_index(f)].offset +
  945. sizeof(MessageHeader);
  946. if (upb_fielddef_containingoneof(f)) {
  947. uint32_t oneof_case_offset =
  948. desc->layout->fields[upb_fielddef_index(f)].case_offset +
  949. sizeof(MessageHeader);
  950. // For a oneof, check that this field is actually present -- skip all the
  951. // below if not.
  952. if (DEREF(msg, oneof_case_offset, uint32_t) !=
  953. upb_fielddef_number(f)) {
  954. continue;
  955. }
  956. // Otherwise, fall through to the appropriate singular-field handler
  957. // below.
  958. is_matching_oneof = true;
  959. }
  960. if (is_map_field(f)) {
  961. VALUE map = DEREF(msg, offset, VALUE);
  962. if (map != Qnil || emit_defaults) {
  963. putmap(map, f, sink, depth, emit_defaults);
  964. }
  965. } else if (upb_fielddef_isseq(f)) {
  966. VALUE ary = DEREF(msg, offset, VALUE);
  967. if (ary != Qnil) {
  968. putary(ary, f, sink, depth, emit_defaults);
  969. }
  970. } else if (upb_fielddef_isstring(f)) {
  971. VALUE str = DEREF(msg, offset, VALUE);
  972. if (is_matching_oneof || emit_defaults || RSTRING_LEN(str) > 0) {
  973. putstr(str, f, sink);
  974. }
  975. } else if (upb_fielddef_issubmsg(f)) {
  976. putsubmsg(DEREF(msg, offset, VALUE), f, sink, depth, emit_defaults);
  977. } else {
  978. upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
  979. #define T(upbtypeconst, upbtype, ctype, default_value) \
  980. case upbtypeconst: { \
  981. ctype value = DEREF(msg, offset, ctype); \
  982. if (is_matching_oneof || emit_defaults || value != default_value) { \
  983. upb_sink_put##upbtype(sink, sel, value); \
  984. } \
  985. } \
  986. break;
  987. switch (upb_fielddef_type(f)) {
  988. T(UPB_TYPE_FLOAT, float, float, 0.0)
  989. T(UPB_TYPE_DOUBLE, double, double, 0.0)
  990. T(UPB_TYPE_BOOL, bool, uint8_t, 0)
  991. case UPB_TYPE_ENUM:
  992. T(UPB_TYPE_INT32, int32, int32_t, 0)
  993. T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
  994. T(UPB_TYPE_INT64, int64, int64_t, 0)
  995. T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
  996. case UPB_TYPE_STRING:
  997. case UPB_TYPE_BYTES:
  998. case UPB_TYPE_MESSAGE: rb_raise(rb_eRuntimeError, "Internal error.");
  999. }
  1000. #undef T
  1001. }
  1002. }
  1003. upb_sink_endmsg(sink, &status);
  1004. }
  1005. static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
  1006. if (desc->pb_serialize_handlers == NULL) {
  1007. desc->pb_serialize_handlers =
  1008. upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
  1009. }
  1010. return desc->pb_serialize_handlers;
  1011. }
  1012. static const upb_handlers* msgdef_json_serialize_handlers(
  1013. Descriptor* desc, bool preserve_proto_fieldnames) {
  1014. if (preserve_proto_fieldnames) {
  1015. if (desc->json_serialize_handlers == NULL) {
  1016. desc->json_serialize_handlers =
  1017. upb_json_printer_newhandlers(
  1018. desc->msgdef, true, &desc->json_serialize_handlers);
  1019. }
  1020. return desc->json_serialize_handlers;
  1021. } else {
  1022. if (desc->json_serialize_handlers_preserve == NULL) {
  1023. desc->json_serialize_handlers_preserve =
  1024. upb_json_printer_newhandlers(
  1025. desc->msgdef, false, &desc->json_serialize_handlers_preserve);
  1026. }
  1027. return desc->json_serialize_handlers_preserve;
  1028. }
  1029. }
  1030. /*
  1031. * call-seq:
  1032. * MessageClass.encode(msg) => bytes
  1033. *
  1034. * Encodes the given message object to its serialized form in protocol buffers
  1035. * wire format.
  1036. */
  1037. VALUE Message_encode(VALUE klass, VALUE msg_rb) {
  1038. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1039. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1040. stringsink sink;
  1041. stringsink_init(&sink);
  1042. {
  1043. const upb_handlers* serialize_handlers =
  1044. msgdef_pb_serialize_handlers(desc);
  1045. stackenv se;
  1046. upb_pb_encoder* encoder;
  1047. VALUE ret;
  1048. stackenv_init(&se, "Error occurred during encoding: %s");
  1049. encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
  1050. putmsg(msg_rb, desc, upb_pb_encoder_input(encoder), 0, false);
  1051. ret = rb_str_new(sink.ptr, sink.len);
  1052. stackenv_uninit(&se);
  1053. stringsink_uninit(&sink);
  1054. return ret;
  1055. }
  1056. }
  1057. /*
  1058. * call-seq:
  1059. * MessageClass.encode_json(msg) => json_string
  1060. *
  1061. * Encodes the given message object into its serialized JSON representation.
  1062. */
  1063. VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) {
  1064. VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned);
  1065. Descriptor* desc = ruby_to_Descriptor(descriptor);
  1066. VALUE msg_rb;
  1067. VALUE preserve_proto_fieldnames = Qfalse;
  1068. VALUE emit_defaults = Qfalse;
  1069. stringsink sink;
  1070. if (argc < 1 || argc > 2) {
  1071. rb_raise(rb_eArgError, "Expected 1 or 2 arguments.");
  1072. }
  1073. msg_rb = argv[0];
  1074. if (argc == 2) {
  1075. VALUE hash_args = argv[1];
  1076. if (TYPE(hash_args) != T_HASH) {
  1077. rb_raise(rb_eArgError, "Expected hash arguments.");
  1078. }
  1079. preserve_proto_fieldnames = rb_hash_lookup2(
  1080. hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse);
  1081. emit_defaults = rb_hash_lookup2(
  1082. hash_args, ID2SYM(rb_intern("emit_defaults")), Qfalse);
  1083. }
  1084. stringsink_init(&sink);
  1085. {
  1086. const upb_handlers* serialize_handlers =
  1087. msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames));
  1088. upb_json_printer* printer;
  1089. stackenv se;
  1090. VALUE ret;
  1091. stackenv_init(&se, "Error occurred during encoding: %s");
  1092. printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink);
  1093. putmsg(msg_rb, desc, upb_json_printer_input(printer), 0, RTEST(emit_defaults));
  1094. ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding());
  1095. stackenv_uninit(&se);
  1096. stringsink_uninit(&sink);
  1097. return ret;
  1098. }
  1099. }