encode_decode.c 48 KB

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