storage.c 36 KB

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