storage.c 37 KB

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