Skip to content

Bugs caused by lack of GC.@preserveability of pointers to InineString #90

@jakobnissen

Description

@jakobnissen

Our saga begin with this bug:

julia> readline(IOBuffer(codeunits(String7("wq"))))
"0;"

Digging down, we hit this bug:

julia> function foo(s)
           GC.@preserve s findfirst(==(0x0a), codeunits(s))
       end
foo (generic function with 1 method)

julia> s = String7("abc\nss\n")
"abc\nss\n"

julia> foo(s) === nothing
true

Which is caused by:

julia> s = String7("abc\nss\n")
"abc\nss\n"

julia> function foo(s)
           u = reinterpret(UInt, s)
           GC.@preserve s begin
               p = pointer(codeunits(s))
               p2 = @ccall memchr(p::Ptr{UInt8}, 0x0a::Cchar, 7::Csize_t)::Ptr{Nothing}
               p2 == C_NULL ? nothing : p2 - p + 1
           end
       end
foo (generic function with 1 method)

julia> foo(s) === nothing
true

Which I believe ultimately is caused by the lack of GC.@preserve in the pointer function.

To check it, let's compare:

julia> function foo(s)
           GC.@preserve s begin
               p = pointer(codeunits(s))
               p2 = @ccall memchr(p::Ptr{UInt8}, 0x0a::Cchar, 7::Csize_t)::Ptr{Nothing}
               p2 == C_NULL ? nothing : p2 - p + 1
           end
       end
foo (generic function with 1 method)

julia> function bar(s)
           r = Ref(bswap(reinterpret(UInt, s)))
           GC.@preserve r begin
               p = Ptr{UInt8}(pointer_from_objref(r))
               p2 = @ccall memchr(p::Ptr{UInt8}, 0x0a::Cchar, 7::Csize_t)::Ptr{Nothing}
               p2 == C_NULL ? nothing : p2 - p + 1
           end
       end
bar (generic function with 1 method)

julia> foo(s)

julia> bar(s)
0x0000000000000004

Note that foo and bar do the same thing - the definition of pointer(codeunits(::InlineString)) is just inlined into bar. The only difference is that in bar, the Ref is GC.@preserved, which it isn't in foo

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions