sdl icon indicating copy to clipboard operation
sdl copied to clipboard

sdl crashes at runtime when used with V's garbage collector

Open larpon opened this issue 1 year ago • 3 comments

In some cases, with some versions of SDL2, on some different distributions and platforms SDL2 crashes at runtime if applications are built using V's default garbage collector.

Currently, especially the tVintris example is known to cause different kind of crashes on different systems.

A, relatively simple, example MRE that crashes on my system (EndeavourOS, rolling, Arch based SDL v2.30.3 vlang/sdl branch 2.30.0):

module main

import sdl

struct Data1 {
mut:
	a int
}

fn main() {
	mut data1 := []&Data1{cap: 200}
	for i in 0 .. 200 {
		data1 << &Data1{
			a: i
		}
	}

	sdl.init(sdl.init_video)
	window := sdl.create_window('Hello SDL2'.str, 300, 300, 500, 300, 0)
	renderer := sdl.create_renderer(window, -1, u32(sdl.RendererFlags.accelerated) | u32(sdl.RendererFlags.presentvsync))

	mut should_close := false
	mut ticks := 0
	for {
		ticks++
		evt := sdl.Event{}
		for 0 < sdl.poll_event(&evt) {
			match evt.@type {
				.quit { should_close = true }
				else {}
			}
		}

		data1[0].a = ticks
		data1.delete(10)
		data1 << &Data1{
			a: ticks
		}

		println('ticks: ${ticks}')
		if should_close || ticks == 1000 {
			break
		}

		sdl.set_render_draw_color(renderer, 255, 55, 55, 255)
		sdl.render_clear(renderer)
		sdl.render_present(renderer)
	}
	println('Exiting. If this was compiled without `-d sdl_memory_no_gc`, an invalid memory access error should occur')

	sdl.destroy_renderer(renderer)
	sdl.destroy_window(window)
	sdl.quit()
}

We have introduced the compiletime flag: -d sdl_memory_no_gc to mitigate the problem. Usage of this flag also means that the user will have to manage SDL's memory manually by utilizing SDL2's destroy/sdl.free/1 functions.

The output when crashing is often similar to this:

main__main: RUNTIME ERROR: invalid memory access

larpon avatar Jun 15 '24 09:06 larpon

For me, on Ubuntu 20.04 and SDL 2.0.10, the example above compiles and runs cleanly, but v run ~/.vmodules/sdl/examples/tvintris/ exhibits a probably similar crash.

With v -d sdl_memory_no_gc run ~/.vmodules/sdl/examples/tvintris/ everything works without a crash.

spytheman avatar Jun 15 '24 09:06 spytheman

On Arch, with sdl2-2.30.3, it crashes for both the example in the issue, and with tvintris reliably.

spytheman avatar Jun 15 '24 09:06 spytheman

The default has now been changed so you have to opt-in to using the garbage collector. ~~-d sdl_memory_no_gc~~ is thus not a thing anymore. To use SDL with the garbage collecting pass -d sdl_use_gc.

larpon avatar Nov 25 '24 08:11 larpon