Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
planetis-m opened this issue Sep 1, 2022 · 2 comments
Closed

Comments

@planetis-m
Copy link
Contributor

planetis-m commented Sep 1, 2022

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
@planetis-m
Copy link
Contributor Author

Not orc specific happens with the default GC as well.

@planetis-m
Copy link
Contributor Author

This works:

import hashes

template makeOpenArray(x: seq): untyped =
  if x.len > 0: toOpenArray(x, 0, x.len-1)
  else: toOpenArray(cast[ptr UncheckedArray[typeof(x[0])]](nil), 0, -1)

proc main =
  var x: seq[byte]# = @[1, 2, 3]
  block:
    echo hash(x.makeOpenArray)

main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant