encode_decode.c 50 KB

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