encode_decode.c 52 KB

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