From f79bca42ee00f73b7831c0400a7e935eadc5ee15 Mon Sep 17 00:00:00 2001 From: Elliot Saba Date: Fri, 10 Jun 2022 18:33:33 +0000 Subject: [PATCH] Throw `ArgumentError` if `unsafe_SecretBuffer!()` is passed NULL Previously, if given a NULL `Cstring` we would blithely call `strlen()` on it, which resulted in a segfault. It is better if we throw an exception instead. --- base/secretbuffer.jl | 8 +++++++- test/secretbuffer.jl | 4 ++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/base/secretbuffer.jl b/base/secretbuffer.jl index 02a133be088f03..29e11faf41ebf8 100644 --- a/base/secretbuffer.jl +++ b/base/secretbuffer.jl @@ -79,7 +79,13 @@ function SecretBuffer!(d::Vector{UInt8}) s end -unsafe_SecretBuffer!(s::Cstring) = unsafe_SecretBuffer!(convert(Ptr{UInt8}, s), Int(ccall(:strlen, Csize_t, (Cstring,), s))) +function unsafe_SecretBuffer!(s::Cstring) + if s == C_NULL + throw(ArgumentError("cannot convert NULL to SecretBuffer")) + end + len = Int(ccall(:strlen, Csize_t, (Cstring,), s)) + unsafe_SecretBuffer!(convert(Ptr{UInt8}, s), len) +end function unsafe_SecretBuffer!(p::Ptr{UInt8}, len=1) s = SecretBuffer(sizehint=len) for i in 1:len diff --git a/test/secretbuffer.jl b/test/secretbuffer.jl index df67204dd63baa..9f0b79932539cf 100644 --- a/test/secretbuffer.jl +++ b/test/secretbuffer.jl @@ -122,4 +122,8 @@ using Test @test hash(sb1, UInt(5)) === hash(sb2, UInt(5)) shred!(sb1); shred!(sb2) end + @testset "NULL initialization" begin + null_ptr = Cstring(C_NULL) + @test_throws ArgumentError Base.unsafe_SecretBuffer!(null_ptr) + end end