From 34be0ef1cfbc6ba66d55e304f3f9299a1ba6367c Mon Sep 17 00:00:00 2001 From: K Pamnany Date: Thu, 26 Oct 2023 14:51:32 -0400 Subject: [PATCH] Add GC-safe regions around `ssl_read` and `ssl_write` --- src/ssl.jl | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/ssl.jl b/src/ssl.jl index d4f736e..c7e54a8 100644 --- a/src/ssl.jl +++ b/src/ssl.jl @@ -701,11 +701,23 @@ closed. https://tls.mbed.org/api/ssl_8h.html#aa2c29eeb1deaf5ad9f01a7515006ede5 """ function ssl_read(ctx::SSLContext, ptr, n)::Int + ret = 0 @lockdata ctx begin - return ccall((:mbedtls_ssl_read, libmbedtls), Cint, - (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), - ctx.data, ptr, n) + ccd = Base.cconvert(Ptr{Cvoid}, ctx.data) + cptr = Base.cconvert(Ptr{Cvoid}, ptr) + GC.@preserve ccd cptr begin + # Allow Julia to GC while reading/decrypting + gc_state = @ccall(jl_gc_safe_enter()::Int8) + ret = ccall((:mbedtls_ssl_read, libmbedtls), Cint, + (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), + Base.unsafe_convert(Ptr{Cvoid}, ccd)::Ptr{Cvoid}, + Base.unsafe_convert(Ptr{Cvoid}, cptr)::Ptr{Cvoid}, + n) + # Leave GC-safe region, waiting for GC to complete if it's running + @ccall(jl_gc_safe_leave(gc_state::Int8)::Cvoid) + end end + return ret end """ @@ -726,11 +738,23 @@ connection; the current connection must be closed. https://tls.mbed.org/api/ssl_8h.html#a5bbda87d484de82df730758b475f32e5 """ function ssl_write(ctx::SSLContext, ptr, n)::Int + ret = 0 @lockdata ctx begin - return ccall((:mbedtls_ssl_write, libmbedtls), Cint, - (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), - ctx.data, ptr, n) + ccd = Base.cconvert(Ptr{Cvoid}, ctx.data) + cptr = Base.cconvert(Ptr{Cvoid}, ptr) + GC.@preserve ccd cptr begin + # Allow Julia to GC while writing/encrypting + gc_state = @ccall(jl_gc_safe_enter()::Int8) + ret = ccall((:mbedtls_ssl_write, libmbedtls), Cint, + (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t), + Base.unsafe_convert(Ptr{Cvoid}, ccd)::Ptr{Cvoid}, + Base.unsafe_convert(Ptr{Cvoid}, cptr)::Ptr{Cvoid}, + n) + # Leave GC-safe region, waiting for GC to complete if it's running + @ccall(jl_gc_safe_leave(gc_state::Int8)::Cvoid) + end end + return ret end """