encode_decode.c 48 KB

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