Skip to content

openArray on empty seq triggers UB: member access within null pointer #20294

Closed
@planetis-m

Description

@planetis-m

What happened?

This bug is observed a lot in the stdlib where openArray is used instead of seq such as in == or hash.

import hashes
proc main =
  var x: seq[byte]# = @[1, 2, 3]
  block:
    echo hash(x)
  #block:
    #echo x == [1.byte, 2, 3]
  #block:
    #echo $toOpenArray(x, 0, x.len-1)
  #block:
    #var y: seq[byte] = @[]
    #y.add toOpenArray(x, 0, x.len-1)
main()

This is caused because of this code being generated:

T4_ = hash__tdel_7(x.p->data, x.len);

Nim Version

Nim Compiler Version 1.7.1 [Linux: amd64]
Compiled at 2022-08-31
Copyright (c) 2006-2022 by Andreas Rumpf

git hash: 5211a47
active boot switches: -d:release --gc:markAndSweep

Current Standard Output Logs

t.nim:4:39: runtime error: member access within null pointer of type 'tySequence__6H5Oh5UUvVCLiakt9aTwtUQ_Content' (aka 'struct tySequence__6H5Oh5UUvVCLiakt9aTwtUQ_Content')
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior t.nim:4:39 in 
0

Expected Standard Output Logs

0

Possible Solution

cstring(x) converter handles empty strings correctly.

Additional Information

Build command:

nim c --mm:orc -d:useMalloc -t:"-fsanitize=address,undefined" -l:"-fsanitize=address,undefined" -d:nosignalhandler -d:release -g t

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