Stack Overflow Error with QuickJS

When running on Linux I get a Stack Overflow error:
stack overflow at :1

This is on ubuntu 22.04 LTS (x86_64).
The following function produces:

static inline BOOL js_check_stack_overflow(JSRuntime *rt, size_t alloca_size)
{
    uintptr_t sp;
    sp = js_get_stack_pointer() - alloca_size;
    std::cout << "Stack pointer: " << std::hex << sp << ", limit: " << rt->stack_limit << std::dec << ", alloca_size" << alloca_size << "\n";
    return js_unlikely(sp < rt->stack_limit);
}

on Linux:

Stack pointer: 7ffffba4e430, limit: 7ffffff82bf8, alloca_size0

on macOS:

Stack pointer: 16b6ea870, limit: 16b6218a0, alloca_size0

Note this works fine on macOS.

Looking more into it, it appears that __builtin_frame_address(0); is not very portable or reliable.

Are you able to provide any more steps that would help us to reproduce the issue locally?

Do you see this problem in any of the JUCE examples? If not, can you provide a code snippet for a modification to one of the examples that demonstrates the problem?

I found a quick workaround, but would like an official fix. Commenting out CONFIG_STACK_CHECK.

#if ! (defined(EMSCRIPTEN) || _MSC_VER)

/* enable stack limitation */

//#define CONFIG_STACK_CHECK

#endif

Even if you have an empty script it has this issue. Seems to be a common issue with using __builtin_frame_address(0);

Please could you test the JavaScriptDemo, also available in the DemoRunner, and let us know whether you see the problem there?

Is this a headless demo as I do not have X installed on linux (this is only a linux issue).

No, that demo has a GUI. Are you able to provide a basic int main() definition that triggers the issue in a console application?

Here is a simple juce app showing the issue in linux:

/*
  ==============================================================================

    This file contains the basic startup code for a JUCE application.

  ==============================================================================
*/

#include <JuceHeader.h>
#include "MainComponent.h"

//==============================================================================
class javaScriptIssueApplication  : public juce::JUCEApplication
{
public:
    //==============================================================================
    javaScriptIssueApplication() {}

    const juce::String getApplicationName() override       { return ProjectInfo::projectName; }
    const juce::String getApplicationVersion() override    { return ProjectInfo::versionString; }
    bool moreThanOneInstanceAllowed() override             { return true; }

    //==============================================================================
    
    void initialise (const juce::String& commandLine) override
    {
        // This method is where you should put your application's initialisation code..

       // mainWindow.reset (new MainWindow (getApplicationName()));
      //  JavascriptEngine engine;
        juce::String script = "var files = \"somefile.wav\";";
        //auto result = engine.execute(script);
        executeAsync(script, std::bind(&javaScriptIssueApplication::finished,this, std::placeholders::_1));
        
    }
    void executeAsync(const String &code, std::function<void(Result)> callBack){
        //    setVerbose(false);//reset
        String codeCopy(code);
        std::thread t1([this, codeCopy, callBack]{
            auto res = engine.execute(codeCopy);
            callBack(res);
        });
        t1.detach();
    }
    void finished(Result result){
        std::cout << "Script executed with result: " << (result.wasOk() ? "success" : "fail") << "    errorMsg: " << result.getErrorMessage() << std::endl;
        quit();
    }

    void shutdown() override
    {
        // Add your application's shutdown code here..

        mainWindow = nullptr; // (deletes our window)
    }

    //==============================================================================
    void systemRequestedQuit() override
    {
        // This is called when the app is being asked to quit: you can ignore this
        // request and let the app carry on running, or call quit() to allow the app to close.
        quit();
    }

    void anotherInstanceStarted (const juce::String& commandLine) override
    {
        // When another instance of the app is launched while this one is running,
        // this method is invoked, and the commandLine parameter tells you what
        // the other instance's command-line arguments were.
    }

    //==============================================================================
    /*
        This class implements the desktop window that contains an instance of
        our MainComponent class.
    */
    class MainWindow    : public juce::DocumentWindow
    {
    public:
        MainWindow (juce::String name)
            : DocumentWindow (name,
                              juce::Desktop::getInstance().getDefaultLookAndFeel()
                                                          .findColour (juce::ResizableWindow::backgroundColourId),
                              DocumentWindow::allButtons)
        {
            setUsingNativeTitleBar (true);
            setContentOwned (new MainComponent(), true);

           #if JUCE_IOS || JUCE_ANDROID
            setFullScreen (true);
           #else
            setResizable (true, true);
            centreWithSize (getWidth(), getHeight());
           #endif

            setVisible (true);
        }

        void closeButtonPressed() override
        {
            // This is called when the user tries to close this window. Here, we'll just
            // ask the app to quit when this happens, but you can change this to do
            // whatever you need.
            JUCEApplication::getInstance()->systemRequestedQuit();
        }

        /* Note: Be careful if you override any DocumentWindow methods - the base
           class uses a lot of them, so by overriding you might break its functionality.
           It's best to do all your work in your content component instead, but if
           you really have to override any DocumentWindow methods, make sure your
           subclass also calls the superclass's method.
        */

    private:
        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
    };

private:
    std::unique_ptr<MainWindow> mainWindow;
    JavascriptEngine engine;
};

//==============================================================================
// This macro generates the main() routine that launches the app.
START_JUCE_APPLICATION (javaScriptIssueApplication)

Thanks, much appreciated. A test-case always makes it much quicker to track down these kinds of issues.

Thanks again for the example code. I’ve now had a chance to investigate a little.

I noticed that the snippet you posted works with modifications on Linux as long as the JS engine is constructed on the same thread that later calls execute.

I think what’s going on is that QuickJS is storing the ‘top’ of the stack when the engine is constructed, but a secondary thread will have a different stack. We end up comparing frame addresses of two different threads, which doesn’t produce a meaningful result. The program happens to ‘succeed’ on macOS, but I think the stack check is still not working as expected in this case.

Assuming my diagnosis is correct, I can see two potential workarounds: either disable the stack checking as you suggested; or document that any given JSEngine instance is only to be interacted-with from a single thread. I don’t think the latter idea is feasible, so we’ll probably go with the former.

That said, the JS engine doesn’t make any intrinsic thread safety guarantees, so you still need to be careful that all calls to non-const member functions on the JS engine are made serially and exclusively.

Can you modify the code so I can pass in a variable so I do not have to use modified code (ex. JUCE_NO_JS_STACK_CHECK)

We’re planning to disable the stack checking globally in an upcoming commit.

1 Like