protobuf.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 <ruby/version.h>
  32. #include "defs.h"
  33. #include "map.h"
  34. #include "message.h"
  35. #include "repeated_field.h"
  36. VALUE cError;
  37. VALUE cTypeError;
  38. const upb_fielddef* map_field_key(const upb_fielddef* field) {
  39. const upb_msgdef *entry = upb_fielddef_msgsubdef(field);
  40. return upb_msgdef_itof(entry, 1);
  41. }
  42. const upb_fielddef* map_field_value(const upb_fielddef* field) {
  43. const upb_msgdef *entry = upb_fielddef_msgsubdef(field);
  44. return upb_msgdef_itof(entry, 2);
  45. }
  46. // -----------------------------------------------------------------------------
  47. // StringBuilder, for inspect
  48. // -----------------------------------------------------------------------------
  49. struct StringBuilder {
  50. size_t size;
  51. size_t cap;
  52. char *data;
  53. };
  54. typedef struct StringBuilder StringBuilder;
  55. static size_t StringBuilder_SizeOf(size_t cap) {
  56. return sizeof(StringBuilder) + cap;
  57. }
  58. StringBuilder* StringBuilder_New() {
  59. const size_t cap = 128;
  60. StringBuilder* builder = malloc(sizeof(*builder));
  61. builder->size = 0;
  62. builder->cap = cap;
  63. builder->data = malloc(builder->cap);
  64. return builder;
  65. }
  66. void StringBuilder_Free(StringBuilder* b) {
  67. free(b->data);
  68. free(b);
  69. }
  70. void StringBuilder_Printf(StringBuilder* b, const char *fmt, ...) {
  71. size_t have = b->cap - b->size;
  72. size_t n;
  73. va_list args;
  74. va_start(args, fmt);
  75. n = vsnprintf(&b->data[b->size], have, fmt, args);
  76. va_end(args);
  77. if (have <= n) {
  78. while (have <= n) {
  79. b->cap *= 2;
  80. have = b->cap - b->size;
  81. }
  82. b->data = realloc(b->data, StringBuilder_SizeOf(b->cap));
  83. va_start(args, fmt);
  84. n = vsnprintf(&b->data[b->size], have, fmt, args);
  85. va_end(args);
  86. PBRUBY_ASSERT(n < have);
  87. }
  88. b->size += n;
  89. }
  90. VALUE StringBuilder_ToRubyString(StringBuilder* b) {
  91. VALUE ret = rb_str_new(b->data, b->size);
  92. rb_enc_associate(ret, rb_utf8_encoding());
  93. return ret;
  94. }
  95. static void StringBuilder_PrintEnum(StringBuilder* b, int32_t val,
  96. const upb_enumdef* e) {
  97. const char *name = upb_enumdef_iton(e, val);
  98. if (name) {
  99. StringBuilder_Printf(b, ":%s", name);
  100. } else {
  101. StringBuilder_Printf(b, "%" PRId32, val);
  102. }
  103. }
  104. void StringBuilder_PrintMsgval(StringBuilder* b, upb_msgval val,
  105. TypeInfo info) {
  106. switch (info.type) {
  107. case UPB_TYPE_BOOL:
  108. StringBuilder_Printf(b, "%s", val.bool_val ? "true" : "false");
  109. break;
  110. case UPB_TYPE_FLOAT: {
  111. VALUE str = rb_inspect(DBL2NUM(val.float_val));
  112. StringBuilder_Printf(b, "%s", RSTRING_PTR(str));
  113. break;
  114. }
  115. case UPB_TYPE_DOUBLE: {
  116. VALUE str = rb_inspect(DBL2NUM(val.double_val));
  117. StringBuilder_Printf(b, "%s", RSTRING_PTR(str));
  118. break;
  119. }
  120. case UPB_TYPE_INT32:
  121. StringBuilder_Printf(b, "%" PRId32, val.int32_val);
  122. break;
  123. case UPB_TYPE_UINT32:
  124. StringBuilder_Printf(b, "%" PRIu32, val.uint32_val);
  125. break;
  126. case UPB_TYPE_INT64:
  127. StringBuilder_Printf(b, "%" PRId64, val.int64_val);
  128. break;
  129. case UPB_TYPE_UINT64:
  130. StringBuilder_Printf(b, "%" PRIu64, val.uint64_val);
  131. break;
  132. case UPB_TYPE_STRING:
  133. StringBuilder_Printf(b, "\"%.*s\"", (int)val.str_val.size, val.str_val.data);
  134. break;
  135. case UPB_TYPE_BYTES:
  136. StringBuilder_Printf(b, "\"%.*s\"", (int)val.str_val.size, val.str_val.data);
  137. break;
  138. case UPB_TYPE_ENUM:
  139. StringBuilder_PrintEnum(b, val.int32_val, info.def.enumdef);
  140. break;
  141. case UPB_TYPE_MESSAGE:
  142. Message_PrintMessage(b, val.msg_val, info.def.msgdef);
  143. break;
  144. }
  145. }
  146. // -----------------------------------------------------------------------------
  147. // Arena
  148. // -----------------------------------------------------------------------------
  149. void Arena_free(void* data) { upb_arena_free(data); }
  150. static VALUE cArena;
  151. const rb_data_type_t Arena_type = {
  152. "Google::Protobuf::Internal::Arena",
  153. { NULL, Arena_free, NULL },
  154. };
  155. static VALUE Arena_alloc(VALUE klass) {
  156. upb_arena *arena = upb_arena_new();
  157. return TypedData_Wrap_Struct(klass, &Arena_type, arena);
  158. }
  159. upb_arena *Arena_get(VALUE _arena) {
  160. upb_arena *arena;
  161. TypedData_Get_Struct(_arena, upb_arena, &Arena_type, arena);
  162. return arena;
  163. }
  164. VALUE Arena_new() {
  165. return Arena_alloc(cArena);
  166. }
  167. void Arena_register(VALUE module) {
  168. VALUE internal = rb_define_module_under(module, "Internal");
  169. VALUE klass = rb_define_class_under(internal, "Arena", rb_cObject);
  170. rb_define_alloc_func(klass, Arena_alloc);
  171. rb_gc_register_address(&cArena);
  172. cArena = klass;
  173. }
  174. // -----------------------------------------------------------------------------
  175. // Object Cache
  176. // -----------------------------------------------------------------------------
  177. // A pointer -> Ruby Object cache that keeps references to Ruby wrapper
  178. // objects. This allows us to look up any Ruby wrapper object by the address
  179. // of the object it is wrapping. That way we can avoid ever creating two
  180. // different wrapper objects for the same C object, which saves memory and
  181. // preserves object identity.
  182. //
  183. // We use Hash and/or WeakMap for the cache. WeakMap is faster overall
  184. // (probably due to removal being integrated with GC) but doesn't work for Ruby
  185. // <2.7 (see note below). We need Hash for Ruby <2.7 and for cases where we
  186. // need to GC-root the object (notably when the object has been frozen).
  187. #if RUBY_API_VERSION_CODE >= 20700
  188. #define USE_WEAK_MAP 1
  189. #else
  190. #define USE_WEAK_MAP 0
  191. #endif
  192. static VALUE ObjectCache_GetKey(const void* key) {
  193. char buf[sizeof(key)];
  194. memcpy(&buf, &key, sizeof(key));
  195. intptr_t key_int = (intptr_t)key;
  196. PBRUBY_ASSERT((key_int & 3) == 0);
  197. return LL2NUM(key_int >> 2);
  198. }
  199. // Strong object cache, uses regular Hash and GC-roots objects.
  200. // - For Ruby <2.7, used for all objects.
  201. // - For Ruby >=2.7, used only for frozen objects, so we preserve the "frozen"
  202. // bit (since this information is not preserved at the upb level).
  203. VALUE strong_obj_cache = Qnil;
  204. static void StrongObjectCache_Init() {
  205. rb_gc_register_address(&strong_obj_cache);
  206. strong_obj_cache = rb_hash_new();
  207. }
  208. static void StrongObjectCache_Remove(void* key) {
  209. VALUE key_rb = ObjectCache_GetKey(key);
  210. PBRUBY_ASSERT(rb_hash_lookup(strong_obj_cache, key_rb) != Qnil);
  211. rb_hash_delete(strong_obj_cache, key_rb);
  212. }
  213. static VALUE StrongObjectCache_Get(const void* key) {
  214. VALUE key_rb = ObjectCache_GetKey(key);
  215. return rb_hash_lookup(strong_obj_cache, key_rb);
  216. }
  217. static void StrongObjectCache_Add(const void* key, VALUE val,
  218. upb_arena* arena) {
  219. PBRUBY_ASSERT(StrongObjectCache_Get(key) == Qnil);
  220. VALUE key_rb = ObjectCache_GetKey(key);
  221. rb_hash_aset(strong_obj_cache, key_rb, val);
  222. upb_arena_addcleanup(arena, (void*)key, StrongObjectCache_Remove);
  223. }
  224. // Weak object cache. This speeds up the test suite significantly, so we
  225. // presume it speeds up real code also. However we can only use it in Ruby
  226. // >=2.7 due to:
  227. // https://bugs.ruby-lang.org/issues/16035
  228. #if USE_WEAK_MAP
  229. VALUE weak_obj_cache = Qnil;
  230. static void WeakObjectCache_Init() {
  231. rb_gc_register_address(&weak_obj_cache);
  232. VALUE klass = rb_eval_string("ObjectSpace::WeakMap");
  233. weak_obj_cache = rb_class_new_instance(0, NULL, klass);
  234. }
  235. static VALUE WeakObjectCache_Get(const void* key) {
  236. VALUE key_rb = ObjectCache_GetKey(key);
  237. VALUE ret = rb_funcall(weak_obj_cache, rb_intern("[]"), 1, key_rb);
  238. return ret;
  239. }
  240. static void WeakObjectCache_Add(const void* key, VALUE val) {
  241. PBRUBY_ASSERT(WeakObjectCache_Get(key) == Qnil);
  242. VALUE key_rb = ObjectCache_GetKey(key);
  243. rb_funcall(weak_obj_cache, rb_intern("[]="), 2, key_rb, val);
  244. PBRUBY_ASSERT(WeakObjectCache_Get(key) == val);
  245. }
  246. #endif
  247. // Public ObjectCache API.
  248. static void ObjectCache_Init() {
  249. StrongObjectCache_Init();
  250. #if USE_WEAK_MAP
  251. WeakObjectCache_Init();
  252. #endif
  253. }
  254. void ObjectCache_Add(const void* key, VALUE val, upb_arena *arena) {
  255. #if USE_WEAK_MAP
  256. (void)arena;
  257. WeakObjectCache_Add(key, val);
  258. #else
  259. StrongObjectCache_Add(key, val, arena);
  260. #endif
  261. }
  262. // Returns the cached object for this key, if any. Otherwise returns Qnil.
  263. VALUE ObjectCache_Get(const void* key) {
  264. #if USE_WEAK_MAP
  265. return WeakObjectCache_Get(key);
  266. #else
  267. return StrongObjectCache_Get(key);
  268. #endif
  269. }
  270. void ObjectCache_Pin(const void* key, VALUE val, upb_arena *arena) {
  271. #if USE_WEAK_MAP
  272. PBRUBY_ASSERT(WeakObjectCache_Get(key) == val);
  273. // This will GC-root the object, but we'll still use the weak map for
  274. // actual lookup.
  275. StrongObjectCache_Add(key, val, arena);
  276. #else
  277. // Value is already pinned, nothing to do.
  278. #endif
  279. }
  280. /*
  281. * call-seq:
  282. * Google::Protobuf.discard_unknown(msg)
  283. *
  284. * Discard unknown fields in the given message object and recursively discard
  285. * unknown fields in submessages.
  286. */
  287. static VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb) {
  288. const upb_msgdef *m;
  289. upb_msg *msg = Message_GetMutable(msg_rb, &m);
  290. if (!upb_msg_discardunknown(msg, m, 128)) {
  291. rb_raise(rb_eRuntimeError, "Messages nested too deeply.");
  292. }
  293. return Qnil;
  294. }
  295. /*
  296. * call-seq:
  297. * Google::Protobuf.deep_copy(obj) => copy_of_obj
  298. *
  299. * Performs a deep copy of a RepeatedField instance, a Map instance, or a
  300. * message object, recursively copying its members.
  301. */
  302. VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj) {
  303. VALUE klass = CLASS_OF(obj);
  304. if (klass == cRepeatedField) {
  305. return RepeatedField_deep_copy(obj);
  306. } else if (klass == cMap) {
  307. return Map_deep_copy(obj);
  308. } else {
  309. VALUE new_arena_rb = Arena_new();
  310. upb_arena *new_arena = Arena_get(new_arena_rb);
  311. const upb_msgdef *m;
  312. const upb_msg *msg = Message_Get(obj, &m);
  313. upb_msg* new_msg = Message_deep_copy(msg, m, new_arena);
  314. return Message_GetRubyWrapper(new_msg, m, new_arena_rb);
  315. }
  316. }
  317. // -----------------------------------------------------------------------------
  318. // Initialization/entry point.
  319. // -----------------------------------------------------------------------------
  320. // This must be named "Init_protobuf_c" because the Ruby module is named
  321. // "protobuf_c" -- the VM looks for this symbol in our .so.
  322. __attribute__ ((visibility ("default")))
  323. void Init_protobuf_c() {
  324. ObjectCache_Init();
  325. VALUE google = rb_define_module("Google");
  326. VALUE protobuf = rb_define_module_under(google, "Protobuf");
  327. Arena_register(protobuf);
  328. Defs_register(protobuf);
  329. RepeatedField_register(protobuf);
  330. Map_register(protobuf);
  331. Message_register(protobuf);
  332. cError = rb_const_get(protobuf, rb_intern("Error"));
  333. cTypeError = rb_const_get(protobuf, rb_intern("TypeError"));
  334. rb_define_singleton_method(protobuf, "discard_unknown",
  335. Google_Protobuf_discard_unknown, 1);
  336. rb_define_singleton_method(protobuf, "deep_copy",
  337. Google_Protobuf_deep_copy, 1);
  338. }