title: Defending against stack overflow by user scripts
body: <p>C++ has limited stack space but no way for functions to check whether there's enough space left for them to run. I don't know what to do about this when writing script bindings.</p>
  
  <p>For example:</p>
  
  <pre><code>class Container : Widget {
    void addChild(WidgetPtr child) { ... }
  
    void draw(Canvas&amp; canvas) {
      for (auto child : m_children) {
        child.draw();
      }
    }
  };
  </code></pre>
  
  <p>A malicious script can do this to crash the program:</p>
  
  <pre><code>var a = new Container()
  for (i = 0; i &lt; 10000000; i++) {
    var b = new Container()
    a.addChild(b)
    a = b
  }
  
  a.draw() // 10000000 nested calls ---&gt; stack overflow
  </code></pre>
  
  <p>There's also callback problem:</p>
  
  <pre><code>void doSomething(std::function&lt;void()&gt; callback) {
    callback();
  }
  </code></pre>
  
  <p>If wrapped using something like this:</p>
  
  <pre><code>ScriptValue doSomething_Wrapper(ScriptArgs args) {
    doSomething([&amp;]() { args[0].callAsFunction(); });
  }
  </code></pre>
  
  <p>Crashed using:</p>
  
  <pre><code>function badCallback() { doSomething(badCallback) }
  doSomething(badCallback)
  
  ...
  doSomething_Wrapper
  doSomething
  ScriptValue::callAsFunction
  ...
  doSomething_Wrapper
  doSomething
  ScriptValue::callAsFunction
  ...
  BOOM!
  </code></pre>
  
  <p>What's the most idiomatic way to defend against this with least inconvenience?</p>
  
  <p>What do browsers written in C++ (Firefox, Chrome) do?</p>
  
  <p>What can I do not to introduce a vulnerability like this by accident?</p>