From 82615de00e877d3a5538508506090cfae721d375 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 | 11 ++++++++++- test/secretbuffer.jl | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/base/secretbuffer.jl b/base/secretbuffer.jl index 02a133be088f0..935c50fb80fd6 100644 --- a/base/secretbuffer.jl +++ b/base/secretbuffer.jl @@ -79,8 +79,17 @@ 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) + if p == C_NULL + throw(ArgumentError("cannot convert NULL to SecretBuffer")) + end s = SecretBuffer(sizehint=len) for i in 1:len write(s, unsafe_load(p, i)) diff --git a/test/secretbuffer.jl b/test/secretbuffer.jl index df67204dd63ba..976c757deea57 100644 --- a/test/secretbuffer.jl +++ b/test/secretbuffer.jl @@ -122,4 +122,11 @@ 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) + null_ptr = Ptr{UInt8}(C_NULL) + @test_throws ArgumentError Base.unsafe_SecretBuffer!(null_ptr) + @test_throws ArgumentError Base.unsafe_SecretBuffer!(null_ptr, 0) + end end