Skip to content

fix: eliminate bad use-after-free(destroy) pattern #1068

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

Merged
merged 2 commits into from
Aug 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions com.unity.netcode.gameobjects/Runtime/Core/NetworkObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -380,8 +380,20 @@ public static void NetworkHide(List<NetworkObject> networkObjects, ulong clientI
}
}

private bool m_ApplicationQuitting = false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you wanted to avoid the instance memory, you could do this statically:

static class ApplicationQuitHelper
{
    public static bool ApplicationQuitting { get; private set; }

    [RuntimeInitializeOnLoadMethod]
    static void RegisterQuitCallback()
    {
        Application.quitting += ()=> ApplicationQuitting = true;
    }
}


private void OnApplicationQuit()
{
m_ApplicationQuitting = true;
}

private void OnDestroy()
{
if (m_ApplicationQuitting)
{
return;
}

if (NetworkManager != null && NetworkManager.IsListening && NetworkManager.IsServer == false && IsSpawned)
{
throw new NotServerException($"Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call {nameof(Destroy)} or {nameof(Despawn)} on the server/host instead.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -685,8 +685,12 @@ internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObjec
}
}

var gobj = networkObject.gameObject;
if (SpawnedObjects.Remove(networkObject.NetworkObjectId))
{
SpawnedObjectsList.Remove(networkObject);
}

var gobj = networkObject.gameObject;
if (destroyGameObject && gobj != null)
{
if (NetworkManager.PrefabHandler.ContainsHandler(networkObject))
Expand All @@ -698,14 +702,6 @@ internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObjec
UnityEngine.Object.Destroy(gobj);
}
}

// for some reason, we can get down here and SpawnedObjects for this
// networkId will no longer be here, even as we check this at the start
// of the function
if (SpawnedObjects.Remove(networkObject.NetworkObjectId))
{
SpawnedObjectsList.Remove(networkObject);
}
}
}
}