bugsnag / bugsnag-unity

Automatic error reporting for Unity games
https://docs.bugsnag.com/platforms/unity
MIT License
89 stars 31 forks source link

Race condition around startup can cause null reference exception if application focus changes #781

Closed uncapped-shattuck closed 1 month ago

uncapped-shattuck commented 4 months ago

Describe the bug

There is a race condition between the BugsnagUnity.Bugsnag.InternalClient being initialized to a non-null value and attempting to use the InternalClient indirectly via TimingTrackingBehaviour.OnApplicationFocus - the ctor of BugsnagUnity.Client initializes the timing tracker, which means that focus changes that happen after the timing tracker starts but before the ctor finishes and the assignment completes will cause a null reference exception.

Steps to reproduce

This is a race condition with a very narrow window, so the change of reproducing it is low

  1. Call Bugsnag.Start() in Unity to initialize the client
  2. Alt-tab in and out of the Unity window
  3. If the timing lines up, see a NullReferenceException in BugsnagUnity.Bugsnag.SetApplicationState

Environment

Error messages: ``` NullReferenceException: Object reference not set to an instance of an object at BugsnagUnity.Bugsnag.SetApplicationState (System.Boolean inFocus) [0x00005] in :0 at BugsnagUnity.TimingTrackerBehaviour.OnApplicationFocus (System.Boolean hasFocus) [0x00000] in :0 UnityEngine.DebugLogHandler:Internal_LogException(Exception, Object) UnityEngine.DebugLogHandler:LogException(Exception, Object) BugsnagUnity.BugsnagLogHandler:LogException(Exception, Object) UnityEngine.Logger:LogException(Exception, Object) UnityEngine.Debug:CallOverridenDebugHandler(Exception, Object) UnityEngine.SystemInfo:GetDeviceModel() UnityEngine.SystemInfo:get_deviceModel() BugsnagUnity.Payload.Device:.ctor(Configuration, String) BugsnagUnity.SessionTracker:StartManagedSession() BugsnagUnity.SessionTracker:StartSession() BugsnagUnity.Client:StartInitialSession() BugsnagUnity.Client:.ctor(INativeClient) BugsnagUnity.Bugsnag:Start(Configuration) ... ``` The stack shows that the client was still being constructed (but was past the point of enabling `BugsnagUnity.TimingTrackerBehaviour`) at the time that Unity broadcast an `OnApplicationFocus` method, and ` BugsnagUnity.TimingTrackerBehaviour.OnApplicationFocus` ultimately depends on the client being fully constructed.
clr182 commented 4 months ago

Hi @uncapped-shattuck

Thanks for reaching out and highlighting this issue. We do now have an item on our backlog aimed at investigating this issue further when priority allows.

Once we have more information to share we will be sure to follow up and inform you of any updates.

mclack commented 1 month ago

Hi @uncapped-shattuck

We have now implemented a fix for this in the v8.0.0 release of bugsnag-unity: https://github.com/bugsnag/bugsnag-unity/releases/tag/v8.0.0

Please let us know if you notice any other issues after upgrading to this version.