storage.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. #include <math.h>
  32. #include <ruby/encoding.h>
  33. // -----------------------------------------------------------------------------
  34. // Ruby <-> native slot management.
  35. // -----------------------------------------------------------------------------
  36. #define CHARPTR_AT(msg, ofs) ((char*)msg + ofs)
  37. #define DEREF_OFFSET(msg, ofs, type) *(type*)CHARPTR_AT(msg, ofs)
  38. #define DEREF(memory, type) *(type*)(memory)
  39. size_t native_slot_size(upb_fieldtype_t type) {
  40. switch (type) {
  41. case UPB_TYPE_FLOAT: return 4;
  42. case UPB_TYPE_DOUBLE: return 8;
  43. case UPB_TYPE_BOOL: return 1;
  44. case UPB_TYPE_STRING: return sizeof(VALUE);
  45. case UPB_TYPE_BYTES: return sizeof(VALUE);
  46. case UPB_TYPE_MESSAGE: return sizeof(VALUE);
  47. case UPB_TYPE_ENUM: return 4;
  48. case UPB_TYPE_INT32: return 4;
  49. case UPB_TYPE_INT64: return 8;
  50. case UPB_TYPE_UINT32: return 4;
  51. case UPB_TYPE_UINT64: return 8;
  52. default: return 0;
  53. }
  54. }
  55. static bool is_ruby_num(VALUE value) {
  56. return (TYPE(value) == T_FLOAT ||
  57. TYPE(value) == T_FIXNUM ||
  58. TYPE(value) == T_BIGNUM);
  59. }
  60. void native_slot_check_int_range_precision(const char* name, upb_fieldtype_t type, VALUE val) {
  61. if (!is_ruby_num(val)) {
  62. rb_raise(cTypeError, "Expected number type for integral field '%s' (given %s).",
  63. name, rb_class2name(CLASS_OF(val)));
  64. }
  65. // NUM2{INT,UINT,LL,ULL} macros do the appropriate range checks on upper
  66. // bound; we just need to do precision checks (i.e., disallow rounding) and
  67. // check for < 0 on unsigned types.
  68. if (TYPE(val) == T_FLOAT) {
  69. double dbl_val = NUM2DBL(val);
  70. if (floor(dbl_val) != dbl_val) {
  71. rb_raise(rb_eRangeError,
  72. "Non-integral floating point value assigned to integer field '%s' (given %s).",
  73. name, rb_class2name(CLASS_OF(val)));
  74. }
  75. }
  76. if (type == UPB_TYPE_UINT32 || type == UPB_TYPE_UINT64) {
  77. if (NUM2DBL(val) < 0) {
  78. rb_raise(rb_eRangeError,
  79. "Assigning negative value to unsigned integer field '%s' (given %s).",
  80. name, rb_class2name(CLASS_OF(val)));
  81. }
  82. }
  83. }
  84. VALUE native_slot_encode_and_freeze_string(upb_fieldtype_t type, VALUE value) {
  85. rb_encoding* desired_encoding = (type == UPB_TYPE_STRING) ?
  86. kRubyStringUtf8Encoding : kRubyString8bitEncoding;
  87. VALUE desired_encoding_value = rb_enc_from_encoding(desired_encoding);
  88. // Note: this will not duplicate underlying string data unless necessary.
  89. value = rb_str_encode(value, desired_encoding_value, 0, Qnil);
  90. if (type == UPB_TYPE_STRING &&
  91. rb_enc_str_coderange(value) == ENC_CODERANGE_BROKEN) {
  92. rb_raise(rb_eEncodingError, "String is invalid UTF-8");
  93. }
  94. // Ensure the data remains valid. Since we called #encode a moment ago,
  95. // this does not freeze the string the user assigned.
  96. rb_obj_freeze(value);
  97. return value;
  98. }
  99. void native_slot_set(const char* name,
  100. upb_fieldtype_t type, VALUE type_class,
  101. void* memory, VALUE value) {
  102. native_slot_set_value_and_case(name, type, type_class, memory, value, NULL, 0);
  103. }
  104. void native_slot_set_value_and_case(const char* name,
  105. upb_fieldtype_t type, VALUE type_class,
  106. void* memory, VALUE value,
  107. uint32_t* case_memory,
  108. uint32_t case_number) {
  109. // Note that in order to atomically change the value in memory and the case
  110. // value (w.r.t. Ruby VM calls), we must set the value at |memory| only after
  111. // all Ruby VM calls are complete. The case is then set at the bottom of this
  112. // function.
  113. switch (type) {
  114. case UPB_TYPE_FLOAT:
  115. if (!is_ruby_num(value)) {
  116. rb_raise(cTypeError, "Expected number type for float field '%s' (given %s).",
  117. name, rb_class2name(CLASS_OF(value)));
  118. }
  119. DEREF(memory, float) = NUM2DBL(value);
  120. break;
  121. case UPB_TYPE_DOUBLE:
  122. if (!is_ruby_num(value)) {
  123. rb_raise(cTypeError, "Expected number type for double field '%s' (given %s).",
  124. name, rb_class2name(CLASS_OF(value)));
  125. }
  126. DEREF(memory, double) = NUM2DBL(value);
  127. break;
  128. case UPB_TYPE_BOOL: {
  129. int8_t val = -1;
  130. if (value == Qtrue) {
  131. val = 1;
  132. } else if (value == Qfalse) {
  133. val = 0;
  134. } else {
  135. rb_raise(cTypeError, "Invalid argument for boolean field '%s' (given %s).",
  136. name, rb_class2name(CLASS_OF(value)));
  137. }
  138. DEREF(memory, int8_t) = val;
  139. break;
  140. }
  141. case UPB_TYPE_STRING:
  142. if (CLASS_OF(value) == rb_cSymbol) {
  143. value = rb_funcall(value, rb_intern("to_s"), 0);
  144. } else if (CLASS_OF(value) != rb_cString) {
  145. rb_raise(cTypeError, "Invalid argument for string field '%s' (given %s).",
  146. name, rb_class2name(CLASS_OF(value)));
  147. }
  148. DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
  149. break;
  150. case UPB_TYPE_BYTES: {
  151. if (CLASS_OF(value) != rb_cString) {
  152. rb_raise(cTypeError, "Invalid argument for bytes field '%s' (given %s).",
  153. name, rb_class2name(CLASS_OF(value)));
  154. }
  155. DEREF(memory, VALUE) = native_slot_encode_and_freeze_string(type, value);
  156. break;
  157. }
  158. case UPB_TYPE_MESSAGE: {
  159. if (CLASS_OF(value) == CLASS_OF(Qnil)) {
  160. value = Qnil;
  161. } else if (CLASS_OF(value) != type_class) {
  162. rb_raise(cTypeError,
  163. "Invalid type %s to assign to submessage field '%s'.",
  164. rb_class2name(CLASS_OF(value)), name);
  165. }
  166. DEREF(memory, VALUE) = value;
  167. break;
  168. }
  169. case UPB_TYPE_ENUM: {
  170. int32_t int_val = 0;
  171. if (TYPE(value) == T_STRING) {
  172. value = rb_funcall(value, rb_intern("to_sym"), 0);
  173. } else if (!is_ruby_num(value) && TYPE(value) != T_SYMBOL) {
  174. rb_raise(cTypeError,
  175. "Expected number or symbol type for enum field '%s'.", name);
  176. }
  177. if (TYPE(value) == T_SYMBOL) {
  178. // Ensure that the given symbol exists in the enum module.
  179. VALUE lookup = rb_funcall(type_class, rb_intern("resolve"), 1, value);
  180. if (lookup == Qnil) {
  181. rb_raise(rb_eRangeError, "Unknown symbol value for enum field '%s'.", name);
  182. } else {
  183. int_val = NUM2INT(lookup);
  184. }
  185. } else {
  186. native_slot_check_int_range_precision(name, UPB_TYPE_INT32, value);
  187. int_val = NUM2INT(value);
  188. }
  189. DEREF(memory, int32_t) = int_val;
  190. break;
  191. }
  192. case UPB_TYPE_INT32:
  193. case UPB_TYPE_INT64:
  194. case UPB_TYPE_UINT32:
  195. case UPB_TYPE_UINT64:
  196. native_slot_check_int_range_precision(name, type, value);
  197. switch (type) {
  198. case UPB_TYPE_INT32:
  199. DEREF(memory, int32_t) = NUM2INT(value);
  200. break;
  201. case UPB_TYPE_INT64:
  202. DEREF(memory, int64_t) = NUM2LL(value);
  203. break;
  204. case UPB_TYPE_UINT32:
  205. DEREF(memory, uint32_t) = NUM2UINT(value);
  206. break;
  207. case UPB_TYPE_UINT64:
  208. DEREF(memory, uint64_t) = NUM2ULL(value);
  209. break;
  210. default:
  211. break;
  212. }
  213. break;
  214. default:
  215. break;
  216. }
  217. if (case_memory != NULL) {
  218. *case_memory = case_number;
  219. }
  220. }
  221. VALUE native_slot_get(upb_fieldtype_t type,
  222. VALUE type_class,
  223. const void* memory) {
  224. switch (type) {
  225. case UPB_TYPE_FLOAT:
  226. return DBL2NUM(DEREF(memory, float));
  227. case UPB_TYPE_DOUBLE:
  228. return DBL2NUM(DEREF(memory, double));
  229. case UPB_TYPE_BOOL:
  230. return DEREF(memory, int8_t) ? Qtrue : Qfalse;
  231. case UPB_TYPE_STRING:
  232. case UPB_TYPE_BYTES:
  233. case UPB_TYPE_MESSAGE:
  234. return DEREF(memory, VALUE);
  235. case UPB_TYPE_ENUM: {
  236. int32_t val = DEREF(memory, int32_t);
  237. VALUE symbol = enum_lookup(type_class, INT2NUM(val));
  238. if (symbol == Qnil) {
  239. return INT2NUM(val);
  240. } else {
  241. return symbol;
  242. }
  243. }
  244. case UPB_TYPE_INT32:
  245. return INT2NUM(DEREF(memory, int32_t));
  246. case UPB_TYPE_INT64:
  247. return LL2NUM(DEREF(memory, int64_t));
  248. case UPB_TYPE_UINT32:
  249. return UINT2NUM(DEREF(memory, uint32_t));
  250. case UPB_TYPE_UINT64:
  251. return ULL2NUM(DEREF(memory, uint64_t));
  252. default:
  253. return Qnil;
  254. }
  255. }
  256. void native_slot_init(upb_fieldtype_t type, void* memory) {
  257. switch (type) {
  258. case UPB_TYPE_FLOAT:
  259. DEREF(memory, float) = 0.0;
  260. break;
  261. case UPB_TYPE_DOUBLE:
  262. DEREF(memory, double) = 0.0;
  263. break;
  264. case UPB_TYPE_BOOL:
  265. DEREF(memory, int8_t) = 0;
  266. break;
  267. case UPB_TYPE_STRING:
  268. case UPB_TYPE_BYTES:
  269. DEREF(memory, VALUE) = rb_str_new2("");
  270. rb_enc_associate(DEREF(memory, VALUE), (type == UPB_TYPE_BYTES) ?
  271. kRubyString8bitEncoding : kRubyStringUtf8Encoding);
  272. break;
  273. case UPB_TYPE_MESSAGE:
  274. DEREF(memory, VALUE) = Qnil;
  275. break;
  276. case UPB_TYPE_ENUM:
  277. case UPB_TYPE_INT32:
  278. DEREF(memory, int32_t) = 0;
  279. break;
  280. case UPB_TYPE_INT64:
  281. DEREF(memory, int64_t) = 0;
  282. break;
  283. case UPB_TYPE_UINT32:
  284. DEREF(memory, uint32_t) = 0;
  285. break;
  286. case UPB_TYPE_UINT64:
  287. DEREF(memory, uint64_t) = 0;
  288. break;
  289. default:
  290. break;
  291. }
  292. }
  293. void native_slot_mark(upb_fieldtype_t type, void* memory) {
  294. switch (type) {
  295. case UPB_TYPE_STRING:
  296. case UPB_TYPE_BYTES:
  297. case UPB_TYPE_MESSAGE:
  298. rb_gc_mark(DEREF(memory, VALUE));
  299. break;
  300. default:
  301. break;
  302. }
  303. }
  304. void native_slot_dup(upb_fieldtype_t type, void* to, void* from) {
  305. memcpy(to, from, native_slot_size(type));
  306. }
  307. void native_slot_deep_copy(upb_fieldtype_t type, void* to, void* from) {
  308. switch (type) {
  309. case UPB_TYPE_STRING:
  310. case UPB_TYPE_BYTES: {
  311. VALUE from_val = DEREF(from, VALUE);
  312. DEREF(to, VALUE) = (from_val != Qnil) ?
  313. rb_funcall(from_val, rb_intern("dup"), 0) : Qnil;
  314. break;
  315. }
  316. case UPB_TYPE_MESSAGE: {
  317. VALUE from_val = DEREF(from, VALUE);
  318. DEREF(to, VALUE) = (from_val != Qnil) ?
  319. Message_deep_copy(from_val) : Qnil;
  320. break;
  321. }
  322. default:
  323. memcpy(to, from, native_slot_size(type));
  324. }
  325. }
  326. bool native_slot_eq(upb_fieldtype_t type, void* mem1, void* mem2) {
  327. switch (type) {
  328. case UPB_TYPE_STRING:
  329. case UPB_TYPE_BYTES:
  330. case UPB_TYPE_MESSAGE: {
  331. VALUE val1 = DEREF(mem1, VALUE);
  332. VALUE val2 = DEREF(mem2, VALUE);
  333. VALUE ret = rb_funcall(val1, rb_intern("=="), 1, val2);
  334. return ret == Qtrue;
  335. }
  336. default:
  337. return !memcmp(mem1, mem2, native_slot_size(type));
  338. }
  339. }
  340. // -----------------------------------------------------------------------------
  341. // Map field utilities.
  342. // -----------------------------------------------------------------------------
  343. const upb_msgdef* tryget_map_entry_msgdef(const upb_fielddef* field) {
  344. const upb_msgdef* subdef;
  345. if (upb_fielddef_label(field) != UPB_LABEL_REPEATED ||
  346. upb_fielddef_type(field) != UPB_TYPE_MESSAGE) {
  347. return NULL;
  348. }
  349. subdef = upb_fielddef_msgsubdef(field);
  350. return upb_msgdef_mapentry(subdef) ? subdef : NULL;
  351. }
  352. const upb_msgdef *map_entry_msgdef(const upb_fielddef* field) {
  353. const upb_msgdef* subdef = tryget_map_entry_msgdef(field);
  354. assert(subdef);
  355. return subdef;
  356. }
  357. bool is_map_field(const upb_fielddef *field) {
  358. const upb_msgdef* subdef = tryget_map_entry_msgdef(field);
  359. if (subdef == NULL) return false;
  360. // Map fields are a proto3 feature.
  361. // If we're using proto2 syntax we need to fallback to the repeated field.
  362. return upb_msgdef_syntax(subdef) == UPB_SYNTAX_PROTO3;
  363. }
  364. const upb_fielddef* map_field_key(const upb_fielddef* field) {
  365. const upb_msgdef* subdef = map_entry_msgdef(field);
  366. return map_entry_key(subdef);
  367. }
  368. const upb_fielddef* map_field_value(const upb_fielddef* field) {
  369. const upb_msgdef* subdef = map_entry_msgdef(field);
  370. return map_entry_value(subdef);
  371. }
  372. const upb_fielddef* map_entry_key(const upb_msgdef* msgdef) {
  373. const upb_fielddef* key_field = upb_msgdef_itof(msgdef, MAP_KEY_FIELD);
  374. assert(key_field != NULL);
  375. return key_field;
  376. }
  377. const upb_fielddef* map_entry_value(const upb_msgdef* msgdef) {
  378. const upb_fielddef* value_field = upb_msgdef_itof(msgdef, MAP_VALUE_FIELD);
  379. assert(value_field != NULL);
  380. return value_field;
  381. }
  382. // -----------------------------------------------------------------------------
  383. // Memory layout management.
  384. // -----------------------------------------------------------------------------
  385. bool field_contains_hasbit(MessageLayout* layout,
  386. const upb_fielddef* field) {
  387. return layout->fields[upb_fielddef_index(field)].hasbit !=
  388. MESSAGE_FIELD_NO_HASBIT;
  389. }
  390. static size_t align_up_to(size_t offset, size_t granularity) {
  391. // Granularity must be a power of two.
  392. return (offset + granularity - 1) & ~(granularity - 1);
  393. }
  394. MessageLayout* create_layout(const upb_msgdef* msgdef) {
  395. MessageLayout* layout = ALLOC(MessageLayout);
  396. int nfields = upb_msgdef_numfields(msgdef);
  397. upb_msg_field_iter it;
  398. upb_msg_oneof_iter oit;
  399. size_t off = 0;
  400. layout->fields = ALLOC_N(MessageField, nfields);
  401. size_t hasbit = 0;
  402. for (upb_msg_field_begin(&it, msgdef);
  403. !upb_msg_field_done(&it);
  404. upb_msg_field_next(&it)) {
  405. const upb_fielddef* field = upb_msg_iter_field(&it);
  406. if (upb_fielddef_haspresence(field)) {
  407. layout->fields[upb_fielddef_index(field)].hasbit = hasbit++;
  408. } else {
  409. layout->fields[upb_fielddef_index(field)].hasbit =
  410. MESSAGE_FIELD_NO_HASBIT;
  411. }
  412. }
  413. if (hasbit != 0) {
  414. off += (hasbit + 8 - 1) / 8;
  415. }
  416. for (upb_msg_field_begin(&it, msgdef);
  417. !upb_msg_field_done(&it);
  418. upb_msg_field_next(&it)) {
  419. const upb_fielddef* field = upb_msg_iter_field(&it);
  420. size_t field_size;
  421. if (upb_fielddef_containingoneof(field)) {
  422. // Oneofs are handled separately below.
  423. continue;
  424. }
  425. // Allocate |field_size| bytes for this field in the layout.
  426. field_size = 0;
  427. if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  428. field_size = sizeof(VALUE);
  429. } else {
  430. field_size = native_slot_size(upb_fielddef_type(field));
  431. }
  432. // Align current offset up to |size| granularity.
  433. off = align_up_to(off, field_size);
  434. layout->fields[upb_fielddef_index(field)].offset = off;
  435. layout->fields[upb_fielddef_index(field)].case_offset =
  436. MESSAGE_FIELD_NO_CASE;
  437. off += field_size;
  438. }
  439. // Handle oneofs now -- we iterate over oneofs specifically and allocate only
  440. // one slot per oneof.
  441. //
  442. // We assign all value slots first, then pack the 'case' fields at the end,
  443. // since in the common case (modern 64-bit platform) these are 8 bytes and 4
  444. // bytes respectively and we want to avoid alignment overhead.
  445. //
  446. // Note that we reserve 4 bytes (a uint32) per 'case' slot because the value
  447. // space for oneof cases is conceptually as wide as field tag numbers. In
  448. // practice, it's unlikely that a oneof would have more than e.g. 256 or 64K
  449. // members (8 or 16 bits respectively), so conceivably we could assign
  450. // consecutive case numbers and then pick a smaller oneof case slot size, but
  451. // the complexity to implement this indirection is probably not worthwhile.
  452. for (upb_msg_oneof_begin(&oit, msgdef);
  453. !upb_msg_oneof_done(&oit);
  454. upb_msg_oneof_next(&oit)) {
  455. const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
  456. upb_oneof_iter fit;
  457. // Always allocate NATIVE_SLOT_MAX_SIZE bytes, but share the slot between
  458. // all fields.
  459. size_t field_size = NATIVE_SLOT_MAX_SIZE;
  460. // Align the offset.
  461. off = align_up_to(off, field_size);
  462. // Assign all fields in the oneof this same offset.
  463. for (upb_oneof_begin(&fit, oneof);
  464. !upb_oneof_done(&fit);
  465. upb_oneof_next(&fit)) {
  466. const upb_fielddef* field = upb_oneof_iter_field(&fit);
  467. layout->fields[upb_fielddef_index(field)].offset = off;
  468. }
  469. off += field_size;
  470. }
  471. // Now the case fields.
  472. for (upb_msg_oneof_begin(&oit, msgdef);
  473. !upb_msg_oneof_done(&oit);
  474. upb_msg_oneof_next(&oit)) {
  475. const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
  476. upb_oneof_iter fit;
  477. size_t field_size = sizeof(uint32_t);
  478. // Align the offset.
  479. off = (off + field_size - 1) & ~(field_size - 1);
  480. // Assign all fields in the oneof this same offset.
  481. for (upb_oneof_begin(&fit, oneof);
  482. !upb_oneof_done(&fit);
  483. upb_oneof_next(&fit)) {
  484. const upb_fielddef* field = upb_oneof_iter_field(&fit);
  485. layout->fields[upb_fielddef_index(field)].case_offset = off;
  486. }
  487. off += field_size;
  488. }
  489. layout->size = off;
  490. layout->msgdef = msgdef;
  491. upb_msgdef_ref(layout->msgdef, &layout->msgdef);
  492. return layout;
  493. }
  494. void free_layout(MessageLayout* layout) {
  495. xfree(layout->fields);
  496. upb_msgdef_unref(layout->msgdef, &layout->msgdef);
  497. xfree(layout);
  498. }
  499. VALUE field_type_class(const upb_fielddef* field) {
  500. VALUE type_class = Qnil;
  501. if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
  502. VALUE submsgdesc =
  503. get_def_obj(upb_fielddef_subdef(field));
  504. type_class = Descriptor_msgclass(submsgdesc);
  505. } else if (upb_fielddef_type(field) == UPB_TYPE_ENUM) {
  506. VALUE subenumdesc =
  507. get_def_obj(upb_fielddef_subdef(field));
  508. type_class = EnumDescriptor_enummodule(subenumdesc);
  509. }
  510. return type_class;
  511. }
  512. static void* slot_memory(MessageLayout* layout,
  513. const void* storage,
  514. const upb_fielddef* field) {
  515. return ((uint8_t *)storage) +
  516. layout->fields[upb_fielddef_index(field)].offset;
  517. }
  518. static uint32_t* slot_oneof_case(MessageLayout* layout,
  519. const void* storage,
  520. const upb_fielddef* field) {
  521. return (uint32_t *)(((uint8_t *)storage) +
  522. layout->fields[upb_fielddef_index(field)].case_offset);
  523. }
  524. static void slot_set_hasbit(MessageLayout* layout,
  525. const void* storage,
  526. const upb_fielddef* field) {
  527. size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
  528. assert(hasbit != MESSAGE_FIELD_NO_HASBIT);
  529. ((uint8_t*)storage)[hasbit / 8] |= 1 << (hasbit % 8);
  530. }
  531. static void slot_clear_hasbit(MessageLayout* layout,
  532. const void* storage,
  533. const upb_fielddef* field) {
  534. size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
  535. assert(hasbit != MESSAGE_FIELD_NO_HASBIT);
  536. ((uint8_t*)storage)[hasbit / 8] &= ~(1 << (hasbit % 8));
  537. }
  538. static bool slot_is_hasbit_set(MessageLayout* layout,
  539. const void* storage,
  540. const upb_fielddef* field) {
  541. size_t hasbit = layout->fields[upb_fielddef_index(field)].hasbit;
  542. if (hasbit == MESSAGE_FIELD_NO_HASBIT) {
  543. return false;
  544. }
  545. return DEREF_OFFSET(
  546. (uint8_t*)storage, hasbit / 8, char) & (1 << (hasbit % 8));
  547. }
  548. VALUE layout_has(MessageLayout* layout,
  549. const void* storage,
  550. const upb_fielddef* field) {
  551. assert(field_contains_hasbit(layout, field));
  552. return slot_is_hasbit_set(layout, storage, field) ? Qtrue : Qfalse;
  553. }
  554. void layout_clear(MessageLayout* layout,
  555. const void* storage,
  556. const upb_fielddef* field) {
  557. void* memory = slot_memory(layout, storage, field);
  558. uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
  559. if (field_contains_hasbit(layout, field)) {
  560. slot_clear_hasbit(layout, storage, field);
  561. }
  562. if (upb_fielddef_containingoneof(field)) {
  563. memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
  564. *oneof_case = ONEOF_CASE_NONE;
  565. } else if (is_map_field(field)) {
  566. VALUE map = Qnil;
  567. const upb_fielddef* key_field = map_field_key(field);
  568. const upb_fielddef* value_field = map_field_value(field);
  569. VALUE type_class = field_type_class(value_field);
  570. if (type_class != Qnil) {
  571. VALUE args[3] = {
  572. fieldtype_to_ruby(upb_fielddef_type(key_field)),
  573. fieldtype_to_ruby(upb_fielddef_type(value_field)),
  574. type_class,
  575. };
  576. map = rb_class_new_instance(3, args, cMap);
  577. } else {
  578. VALUE args[2] = {
  579. fieldtype_to_ruby(upb_fielddef_type(key_field)),
  580. fieldtype_to_ruby(upb_fielddef_type(value_field)),
  581. };
  582. map = rb_class_new_instance(2, args, cMap);
  583. }
  584. DEREF(memory, VALUE) = map;
  585. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  586. VALUE ary = Qnil;
  587. VALUE type_class = field_type_class(field);
  588. if (type_class != Qnil) {
  589. VALUE args[2] = {
  590. fieldtype_to_ruby(upb_fielddef_type(field)),
  591. type_class,
  592. };
  593. ary = rb_class_new_instance(2, args, cRepeatedField);
  594. } else {
  595. VALUE args[1] = { fieldtype_to_ruby(upb_fielddef_type(field)) };
  596. ary = rb_class_new_instance(1, args, cRepeatedField);
  597. }
  598. DEREF(memory, VALUE) = ary;
  599. } else {
  600. native_slot_set(upb_fielddef_name(field),
  601. upb_fielddef_type(field), field_type_class(field),
  602. memory, layout_get_default(field));
  603. }
  604. }
  605. VALUE layout_get_default(const upb_fielddef *field) {
  606. switch (upb_fielddef_type(field)) {
  607. case UPB_TYPE_FLOAT: return DBL2NUM(upb_fielddef_defaultfloat(field));
  608. case UPB_TYPE_DOUBLE: return DBL2NUM(upb_fielddef_defaultdouble(field));
  609. case UPB_TYPE_BOOL:
  610. return upb_fielddef_defaultbool(field) ? Qtrue : Qfalse;
  611. case UPB_TYPE_MESSAGE: return Qnil;
  612. case UPB_TYPE_ENUM: {
  613. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(field);
  614. int32_t num = upb_fielddef_defaultint32(field);
  615. const char *label = upb_enumdef_iton(enumdef, num);
  616. if (label) {
  617. return ID2SYM(rb_intern(label));
  618. } else {
  619. return INT2NUM(num);
  620. }
  621. }
  622. case UPB_TYPE_INT32: return INT2NUM(upb_fielddef_defaultint32(field));
  623. case UPB_TYPE_INT64: return LL2NUM(upb_fielddef_defaultint64(field));;
  624. case UPB_TYPE_UINT32: return UINT2NUM(upb_fielddef_defaultuint32(field));
  625. case UPB_TYPE_UINT64: return ULL2NUM(upb_fielddef_defaultuint64(field));
  626. case UPB_TYPE_STRING:
  627. case UPB_TYPE_BYTES: {
  628. size_t size;
  629. const char *str = upb_fielddef_defaultstr(field, &size);
  630. VALUE str_rb = rb_str_new(str, size);
  631. rb_enc_associate(str_rb, (upb_fielddef_type(field) == UPB_TYPE_BYTES) ?
  632. kRubyString8bitEncoding : kRubyStringUtf8Encoding);
  633. rb_obj_freeze(str_rb);
  634. return str_rb;
  635. }
  636. default: return Qnil;
  637. }
  638. }
  639. VALUE layout_get(MessageLayout* layout,
  640. const void* storage,
  641. const upb_fielddef* field) {
  642. void* memory = slot_memory(layout, storage, field);
  643. uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
  644. bool field_set;
  645. if (field_contains_hasbit(layout, field)) {
  646. field_set = slot_is_hasbit_set(layout, storage, field);
  647. } else {
  648. field_set = true;
  649. }
  650. if (upb_fielddef_containingoneof(field)) {
  651. if (*oneof_case != upb_fielddef_number(field)) {
  652. return layout_get_default(field);
  653. }
  654. return native_slot_get(upb_fielddef_type(field),
  655. field_type_class(field),
  656. memory);
  657. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  658. return *((VALUE *)memory);
  659. } else if (!field_set) {
  660. return layout_get_default(field);
  661. } else {
  662. return native_slot_get(upb_fielddef_type(field),
  663. field_type_class(field),
  664. memory);
  665. }
  666. }
  667. static void check_repeated_field_type(VALUE val, const upb_fielddef* field) {
  668. RepeatedField* self;
  669. assert(upb_fielddef_label(field) == UPB_LABEL_REPEATED);
  670. if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
  671. RTYPEDDATA_TYPE(val) != &RepeatedField_type) {
  672. rb_raise(cTypeError, "Expected repeated field array");
  673. }
  674. self = ruby_to_RepeatedField(val);
  675. if (self->field_type != upb_fielddef_type(field)) {
  676. rb_raise(cTypeError, "Repeated field array has wrong element type");
  677. }
  678. if (self->field_type == UPB_TYPE_MESSAGE) {
  679. if (self->field_type_class !=
  680. Descriptor_msgclass(get_def_obj(upb_fielddef_subdef(field)))) {
  681. rb_raise(cTypeError,
  682. "Repeated field array has wrong message class");
  683. }
  684. }
  685. if (self->field_type == UPB_TYPE_ENUM) {
  686. if (self->field_type_class !=
  687. EnumDescriptor_enummodule(get_def_obj(upb_fielddef_subdef(field)))) {
  688. rb_raise(cTypeError,
  689. "Repeated field array has wrong enum class");
  690. }
  691. }
  692. }
  693. static void check_map_field_type(VALUE val, const upb_fielddef* field) {
  694. const upb_fielddef* key_field = map_field_key(field);
  695. const upb_fielddef* value_field = map_field_value(field);
  696. Map* self;
  697. if (!RB_TYPE_P(val, T_DATA) || !RTYPEDDATA_P(val) ||
  698. RTYPEDDATA_TYPE(val) != &Map_type) {
  699. rb_raise(cTypeError, "Expected Map instance");
  700. }
  701. self = ruby_to_Map(val);
  702. if (self->key_type != upb_fielddef_type(key_field)) {
  703. rb_raise(cTypeError, "Map key type does not match field's key type");
  704. }
  705. if (self->value_type != upb_fielddef_type(value_field)) {
  706. rb_raise(cTypeError, "Map value type does not match field's value type");
  707. }
  708. if (upb_fielddef_type(value_field) == UPB_TYPE_MESSAGE ||
  709. upb_fielddef_type(value_field) == UPB_TYPE_ENUM) {
  710. if (self->value_type_class !=
  711. get_def_obj(upb_fielddef_subdef(value_field))) {
  712. rb_raise(cTypeError,
  713. "Map value type has wrong message/enum class");
  714. }
  715. }
  716. }
  717. void layout_set(MessageLayout* layout,
  718. void* storage,
  719. const upb_fielddef* field,
  720. VALUE val) {
  721. void* memory = slot_memory(layout, storage, field);
  722. uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
  723. if (upb_fielddef_containingoneof(field)) {
  724. if (val == Qnil) {
  725. // Assigning nil to a oneof field clears the oneof completely.
  726. *oneof_case = ONEOF_CASE_NONE;
  727. memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
  728. } else {
  729. // The transition between field types for a single oneof (union) slot is
  730. // somewhat complex because we need to ensure that a GC triggered at any
  731. // point by a call into the Ruby VM sees a valid state for this field and
  732. // does not either go off into the weeds (following what it thinks is a
  733. // VALUE but is actually a different field type) or miss an object (seeing
  734. // what it thinks is a primitive field but is actually a VALUE for the new
  735. // field type).
  736. //
  737. // In order for the transition to be safe, the oneof case slot must be in
  738. // sync with the value slot whenever the Ruby VM has been called. Thus, we
  739. // use native_slot_set_value_and_case(), which ensures that both the value
  740. // and case number are altered atomically (w.r.t. the Ruby VM).
  741. native_slot_set_value_and_case(
  742. upb_fielddef_name(field),
  743. upb_fielddef_type(field), field_type_class(field),
  744. memory, val,
  745. oneof_case, upb_fielddef_number(field));
  746. }
  747. } else if (is_map_field(field)) {
  748. check_map_field_type(val, field);
  749. DEREF(memory, VALUE) = val;
  750. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  751. check_repeated_field_type(val, field);
  752. DEREF(memory, VALUE) = val;
  753. } else {
  754. native_slot_set(upb_fielddef_name(field),
  755. upb_fielddef_type(field), field_type_class(field),
  756. memory, val);
  757. }
  758. if (layout->fields[upb_fielddef_index(field)].hasbit !=
  759. MESSAGE_FIELD_NO_HASBIT) {
  760. slot_set_hasbit(layout, storage, field);
  761. }
  762. }
  763. void layout_init(MessageLayout* layout,
  764. void* storage) {
  765. upb_msg_field_iter it;
  766. for (upb_msg_field_begin(&it, layout->msgdef);
  767. !upb_msg_field_done(&it);
  768. upb_msg_field_next(&it)) {
  769. layout_clear(layout, storage, upb_msg_iter_field(&it));
  770. }
  771. }
  772. void layout_mark(MessageLayout* layout, void* storage) {
  773. upb_msg_field_iter it;
  774. for (upb_msg_field_begin(&it, layout->msgdef);
  775. !upb_msg_field_done(&it);
  776. upb_msg_field_next(&it)) {
  777. const upb_fielddef* field = upb_msg_iter_field(&it);
  778. void* memory = slot_memory(layout, storage, field);
  779. uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
  780. if (upb_fielddef_containingoneof(field)) {
  781. if (*oneof_case == upb_fielddef_number(field)) {
  782. native_slot_mark(upb_fielddef_type(field), memory);
  783. }
  784. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  785. rb_gc_mark(DEREF(memory, VALUE));
  786. } else {
  787. native_slot_mark(upb_fielddef_type(field), memory);
  788. }
  789. }
  790. }
  791. void layout_dup(MessageLayout* layout, void* to, void* from) {
  792. upb_msg_field_iter it;
  793. for (upb_msg_field_begin(&it, layout->msgdef);
  794. !upb_msg_field_done(&it);
  795. upb_msg_field_next(&it)) {
  796. const upb_fielddef* field = upb_msg_iter_field(&it);
  797. void* to_memory = slot_memory(layout, to, field);
  798. uint32_t* to_oneof_case = slot_oneof_case(layout, to, field);
  799. void* from_memory = slot_memory(layout, from, field);
  800. uint32_t* from_oneof_case = slot_oneof_case(layout, from, field);
  801. if (upb_fielddef_containingoneof(field)) {
  802. if (*from_oneof_case == upb_fielddef_number(field)) {
  803. *to_oneof_case = *from_oneof_case;
  804. native_slot_dup(upb_fielddef_type(field), to_memory, from_memory);
  805. }
  806. } else if (is_map_field(field)) {
  807. DEREF(to_memory, VALUE) = Map_dup(DEREF(from_memory, VALUE));
  808. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  809. DEREF(to_memory, VALUE) = RepeatedField_dup(DEREF(from_memory, VALUE));
  810. } else {
  811. if (field_contains_hasbit(layout, field)) {
  812. if (!slot_is_hasbit_set(layout, from, field)) continue;
  813. slot_set_hasbit(layout, to, field);
  814. }
  815. native_slot_dup(upb_fielddef_type(field), to_memory, from_memory);
  816. }
  817. }
  818. }
  819. void layout_deep_copy(MessageLayout* layout, void* to, void* from) {
  820. upb_msg_field_iter it;
  821. for (upb_msg_field_begin(&it, layout->msgdef);
  822. !upb_msg_field_done(&it);
  823. upb_msg_field_next(&it)) {
  824. const upb_fielddef* field = upb_msg_iter_field(&it);
  825. void* to_memory = slot_memory(layout, to, field);
  826. uint32_t* to_oneof_case = slot_oneof_case(layout, to, field);
  827. void* from_memory = slot_memory(layout, from, field);
  828. uint32_t* from_oneof_case = slot_oneof_case(layout, from, field);
  829. if (upb_fielddef_containingoneof(field)) {
  830. if (*from_oneof_case == upb_fielddef_number(field)) {
  831. *to_oneof_case = *from_oneof_case;
  832. native_slot_deep_copy(upb_fielddef_type(field), to_memory, from_memory);
  833. }
  834. } else if (is_map_field(field)) {
  835. DEREF(to_memory, VALUE) =
  836. Map_deep_copy(DEREF(from_memory, VALUE));
  837. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  838. DEREF(to_memory, VALUE) =
  839. RepeatedField_deep_copy(DEREF(from_memory, VALUE));
  840. } else {
  841. if (field_contains_hasbit(layout, field)) {
  842. if (!slot_is_hasbit_set(layout, from, field)) continue;
  843. slot_set_hasbit(layout, to, field);
  844. }
  845. native_slot_deep_copy(upb_fielddef_type(field), to_memory, from_memory);
  846. }
  847. }
  848. }
  849. VALUE layout_eq(MessageLayout* layout, void* msg1, void* msg2) {
  850. upb_msg_field_iter it;
  851. for (upb_msg_field_begin(&it, layout->msgdef);
  852. !upb_msg_field_done(&it);
  853. upb_msg_field_next(&it)) {
  854. const upb_fielddef* field = upb_msg_iter_field(&it);
  855. void* msg1_memory = slot_memory(layout, msg1, field);
  856. uint32_t* msg1_oneof_case = slot_oneof_case(layout, msg1, field);
  857. void* msg2_memory = slot_memory(layout, msg2, field);
  858. uint32_t* msg2_oneof_case = slot_oneof_case(layout, msg2, field);
  859. if (upb_fielddef_containingoneof(field)) {
  860. if (*msg1_oneof_case != *msg2_oneof_case ||
  861. (*msg1_oneof_case == upb_fielddef_number(field) &&
  862. !native_slot_eq(upb_fielddef_type(field),
  863. msg1_memory,
  864. msg2_memory))) {
  865. return Qfalse;
  866. }
  867. } else if (is_map_field(field)) {
  868. if (!Map_eq(DEREF(msg1_memory, VALUE),
  869. DEREF(msg2_memory, VALUE))) {
  870. return Qfalse;
  871. }
  872. } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
  873. if (!RepeatedField_eq(DEREF(msg1_memory, VALUE),
  874. DEREF(msg2_memory, VALUE))) {
  875. return Qfalse;
  876. }
  877. } else {
  878. if (slot_is_hasbit_set(layout, msg1, field) !=
  879. slot_is_hasbit_set(layout, msg2, field) ||
  880. !native_slot_eq(upb_fielddef_type(field),
  881. msg1_memory, msg2_memory)) {
  882. return Qfalse;
  883. }
  884. }
  885. }
  886. return Qtrue;
  887. }
  888. VALUE layout_hash(MessageLayout* layout, void* storage) {
  889. upb_msg_field_iter it;
  890. st_index_t h = rb_hash_start(0);
  891. VALUE hash_sym = rb_intern("hash");
  892. for (upb_msg_field_begin(&it, layout->msgdef);
  893. !upb_msg_field_done(&it);
  894. upb_msg_field_next(&it)) {
  895. const upb_fielddef* field = upb_msg_iter_field(&it);
  896. VALUE field_val = layout_get(layout, storage, field);
  897. h = rb_hash_uint(h, NUM2LONG(rb_funcall(field_val, hash_sym, 0)));
  898. }
  899. h = rb_hash_end(h);
  900. return INT2FIX(h);
  901. }
  902. VALUE layout_inspect(MessageLayout* layout, void* storage) {
  903. VALUE str = rb_str_new2("");
  904. upb_msg_field_iter it;
  905. bool first = true;
  906. for (upb_msg_field_begin(&it, layout->msgdef);
  907. !upb_msg_field_done(&it);
  908. upb_msg_field_next(&it)) {
  909. const upb_fielddef* field = upb_msg_iter_field(&it);
  910. VALUE field_val = layout_get(layout, storage, field);
  911. if (!first) {
  912. str = rb_str_cat2(str, ", ");
  913. } else {
  914. first = false;
  915. }
  916. str = rb_str_cat2(str, upb_fielddef_name(field));
  917. str = rb_str_cat2(str, ": ");
  918. str = rb_str_append(str, rb_funcall(field_val, rb_intern("inspect"), 0));
  919. }
  920. return str;
  921. }