encode_decode.c 55 KB

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