How to get a js stack trace from c++ code?

Hello guys. Does anybody know hot to solve this idea?

For android systems if we make an infinite loop while(true) in javasript code it means we block a GL thread. Then after 5 seconds android will trigger an ANR(application not responding) error.

There is an android library that provides an interface to catch ANRs. At this point i want to get current stack trace from js and just print in to a console. But keep in mind that current js thread is stucked by while(true) loop.

I have found this thing: cocos-engine/ScriptEngine.cpp at 606569f8b27014464c7b623407b39b4b60922f75 · cocos/cocos-engine · GitHub

But it always returns an empty string. stack->GetFrameCount() always is 0.

That depends, if you are invoking ScriptEngine::getCurrentStackTrace in C++ call stack, then it will be empty, only when the C++ code is invoked by JS, you can get the right invocation stack from JS. Like the following call

  • JS function call
    • C++ function
      • ScriptEngine::getCurrentStackTrace

But the scenario you are describing, I don’t think we can get the stack trace correctly unless you can inject code into that infinite loop

@Zakhar you can invoke ScriptEngine::getCurrentStackTrace() to get the js stack. But it should be invoked in the same thread that runs js codes. As you mentioned, the js codes have an infinite loop. Then how can you invoke ScriptEngine::getCurrentStackTrace()? Did you invoke it in another thread, such as Android UI thread? If so, it may crash as JSB related codes should be invoked in the same thread.