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

Mixed union upcast is broken in interpreter on Alpine Linux #15041

Closed
HertzDevil opened this issue Sep 26, 2024 · 1 comment · Fixed by #15042
Closed

Mixed union upcast is broken in interpreter on Alpine Linux #15041

HertzDevil opened this issue Sep 26, 2024 · 1 comment · Fixed by #15042
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. platform:linux-musl topic:compiler:interpreter

Comments

@HertzDevil
Copy link
Contributor

HertzDevil commented Sep 26, 2024

record Foo, x : Int32, y : Void*

x = Foo.new(1, Pointer(Void).new(0xdeadbeef))
x          # => Foo(@x=1, @y=Pointer(Void)@0xdeadbeef)
(x || nil) # => Foo(@x=1, @y=Pointer(Void)@0x1)
(x || 1)   # => Foo(@x=1, @y=Pointer(Void)@0x1)

This happens on any value that is larger than a pointer, e.g. {1, 2_i64}, StaticArray[1, 2, 3], and 123_i128 too.

Extracted from #15034 (comment)

@HertzDevil HertzDevil added kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:compiler:interpreter labels Sep 26, 2024
@HertzDevil
Copy link
Contributor Author

This is a consequence of memcpy:

x = Slice.new(16, &.itself)
x.to_unsafe.copy_to(x.to_unsafe + 6, 10)
x # => Slice[0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3]

The interpreter upcasts a value to a mixed union by placing it on top of the stack, and then copying the data portion to a higher position to reserve space for the type ID. Hence, when the size of the value exceeds that of the type ID, the copy_to here would occur between two overlapping ranges:

tmp_stack = stack
stack_grow_by(union_size - from_size)
(tmp_stack - from_size).copy_to(tmp_stack - from_size + type_id_bytesize, from_size)
(tmp_stack - from_size).as(Int64*).value = type_id.to_i64!

This is undefined behavior in both ISO C and POSIX. Instead move_to must be used here (and most likely in a few other places too).

@HertzDevil HertzDevil changed the title Mixed union upcast is broken in interpreter on Alpine Docker image Mixed union upcast is broken in interpreter on Alpine Linux Sep 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. platform:linux-musl topic:compiler:interpreter
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant