encode_decode.c 51 KB

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