encode_decode.c 54 KB

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