|
10 | 10 | /* modified by Michal Rokos <[email protected]> */
|
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)
|
@@ -1092,9 +1142,11 @@ Init_ossl_bn(void)
|
1092 | 1142 | eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError);
|
1093 | 1143 | #endif
|
1094 | 1144 |
|
1095 |
| - if (!(ossl_bn_ctx = BN_CTX_new())) { |
1096 |
| - ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX"); |
1097 |
| - } |
| 1145 | +#ifdef HAVE_RB_EXT_RACTOR_SAFE |
| 1146 | + ossl_bn_ctx_key = rb_ractor_local_storage_ptr_newkey(&ossl_bn_ctx_key_type); |
| 1147 | +#else |
| 1148 | + ossl_bn_ctx_get(); |
| 1149 | +#endif |
1098 | 1150 |
|
1099 | 1151 | eBNError = rb_define_class_under(mOSSL, "BNError", eOSSLError);
|
1100 | 1152 |
|
|
0 commit comments