storage.c 37 KB

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