Fix Steam init errors in Unity IL2CPP builds #803
+11
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This resolves #802
After running into the above issue (which was also mentioned in pull request #773) and reporting it, I kept digging and eventually found out that the issue lies with the custom string marshaller used to convert the interface versions string into a native C string pointer. As the problem only happens in Unity IL2CPP standalone builds I am unable to analyze it any deeper but I do have a theory what might be happening.
I suspect that the IL2CPP runtime (possibly its GC) is calling cleanup on the custom marshaller too early, causing the native string memory to be released before the SteamAPI_Init function is done reading its contents. This is a classic use-after-free scenario. This freed memory may then be overwritten by other data, explaining the garbage that Steam returns in its error message, as it will be reading that new data from memory expecting it to be part of the interface versions string.
I managed to circumvent the problem by performing the string conversion in-place, so I can control the lifetime of the native string buffer explicitly, ensuring it won't get freed until after SteamAPI_Init returns a result. With this fix in place, the intermittent Steam initialization errors in our Unity IL2CPP builds have gone away entirely.