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

Potential issue with standard main loop in NDK samples #1094

Open
SysReset opened this issue Jan 30, 2025 · 1 comment
Open

Potential issue with standard main loop in NDK samples #1094

SysReset opened this issue Jan 30, 2025 · 1 comment

Comments

@SysReset
Copy link

The main loop used in many Android NDK samples follows this standard structure:

void android_main(android_app* state)
{
    ...

    while (!state->destroyRequested) {
        android_poll_source* source = nullptr;
        int result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, (void**)&source);
        if (result == ALOOPER_POLL_ERROR)
            break;

        if (source != nullptr)
            source->process(state, source);

        // Issue: This code is executed even after state->destroyRequested is set to true
        if (g_engine.IsReady())
            g_engine.DrawFrame();
    }

    ...
}

Issue:
state->destroyRequested is set to true in source->process(state, source) when a "destroy" event occurs. However, the code continues executing after state->destroyRequested is set which can lead to undefined behavior, e.g. accessing released resources.

Potential Fix:

android_poll_source* source;
while (ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, reinterpret_cast<void**>(&source)) != ALOOPER_POLL_ERROR) {
    if (source != nullptr) {
        source->process(state, source);

        // Exit loop immediately after destroy is requested
        if (state->destroyRequested != 0)
            break;
    }

    if (g_engine.IsReady())
        g_engine.DrawFrame();
}
@DanAlbert
Copy link
Member

I'm waiting to hear back from someone in Android that should know more, but is this actually a problem? Where's it documented that the loop must exit immediately?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants