|
10 | 10 | /* modified by Michal Rokos <m.rokos@sh.cvut.cz> */ |
11 | 11 | #include "ossl.h" |
12 | 12 |
|
| 13 | +#if HAVE_RB_EXT_RACTOR_SAFE |
| 14 | +#include <ruby/ractor.h> |
| 15 | +#endif |
| 16 | + |
13 | 17 | #define NewBN(klass) \ |
14 | 18 | TypedData_Wrap_Struct((klass), &ossl_bn_type, 0) |
15 | 19 | #define SetBN(obj, bn) do { \ |
@@ -150,12 +154,58 @@ ossl_bn_value_ptr(volatile VALUE *ptr) |
150 | 154 | /* |
151 | 155 | * Private |
152 | 156 | */ |
153 | | -/* |
154 | | - * BN_CTX - is used in more difficult math. ops |
155 | | - * (Why just 1? Because Ruby itself isn't thread safe, |
156 | | - * we don't need to care about threads) |
157 | | - */ |
158 | | -BN_CTX *ossl_bn_ctx; |
| 157 | + |
| 158 | +#if HAVE_RB_EXT_RACTOR_SAFE |
| 159 | +void |
| 160 | +ossl_bn_ctx_free(void *ptr) |
| 161 | +{ |
| 162 | + BN_CTX *ctx = (BN_CTX *)ptr; |
| 163 | + BN_CTX_free(ctx); |
| 164 | +} |
| 165 | + |
| 166 | +struct rb_ractor_local_storage_type ossl_bn_ctx_key_type = { |
| 167 | + NULL, // mark |
| 168 | + ossl_bn_ctx_free, |
| 169 | +}; |
| 170 | + |
| 171 | +rb_ractor_local_key_t ossl_bn_ctx_key; |
| 172 | + |
| 173 | +BN_CTX * |
| 174 | +ossl_bn_ctx_get(void) |
| 175 | +{ |
| 176 | + // stored in ractor local storage |
| 177 | + |
| 178 | + BN_CTX *ctx = rb_ractor_local_storage_ptr(ossl_bn_ctx_key); |
| 179 | + if (!ctx) { |
| 180 | + if (!(ctx = BN_CTX_new())) { |
| 181 | + ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX"); |
| 182 | + } |
| 183 | + rb_ractor_local_storage_ptr_set(ossl_bn_ctx_key, ctx); |
| 184 | + } |
| 185 | + return ctx; |
| 186 | +} |
| 187 | +#else |
| 188 | +// for ruby 2.x |
| 189 | +static BN_CTX *gv_ossl_bn_ctx; |
| 190 | + |
| 191 | +BN_CTX * |
| 192 | +ossl_bn_ctx_get(void) |
| 193 | +{ |
| 194 | + if (gv_ossl_bn_ctx == NULL) { |
| 195 | + if (!(gv_ossl_bn_ctx = BN_CTX_new())) { |
| 196 | + ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX"); |
| 197 | + } |
| 198 | + } |
| 199 | + return gv_ossl_bn_ctx; |
| 200 | +} |
| 201 | + |
| 202 | +void |
| 203 | +ossl_bn_ctx_free(void) |
| 204 | +{ |
| 205 | + BN_CTX_free(gv_ossl_bn_ctx); |
| 206 | + gv_ossl_bn_ctx = NULL; |
| 207 | +} |
| 208 | +#endif |
159 | 209 |
|
160 | 210 | static VALUE |
161 | 211 | ossl_bn_alloc(VALUE klass) |
@@ -1102,9 +1152,11 @@ Init_ossl_bn(void) |
1102 | 1152 | eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError); |
1103 | 1153 | #endif |
1104 | 1154 |
|
1105 | | - if (!(ossl_bn_ctx = BN_CTX_new())) { |
1106 | | - ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX"); |
1107 | | - } |
| 1155 | +#ifdef HAVE_RB_EXT_RACTOR_SAFE |
| 1156 | + ossl_bn_ctx_key = rb_ractor_local_storage_ptr_newkey(&ossl_bn_ctx_key_type); |
| 1157 | +#else |
| 1158 | + ossl_bn_ctx_get(); |
| 1159 | +#endif |
1108 | 1160 |
|
1109 | 1161 | eBNError = rb_define_class_under(mOSSL, "BNError", eOSSLError); |
1110 | 1162 |
|
|
0 commit comments