encode_decode.c 44 KB

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