8

This question is similar to one I recently asked about LLVM.

V8 allocates JavaScript objects on a manually-managed heap, memory for which is ultimately obtained from mmap/VirtualAlloc (on Linux/Windows). However, for its internal data structures, V8 uses C++ standard containers such as std::vector. If these containers need to allocate memory, but are unable to, they usually throw std::bad_alloc.

However, V8 is compiled with -fno-exceptions. If exceptions cannot be used, how does V8 handle the situation where the internal data structures are unable to allocate memory? Does it crash? If so, does this take down any process which embeds V8?

Community
  • 1
  • 1
user200783
  • 13,722
  • 12
  • 69
  • 135
  • No, my browser uses "V8" as well as my node.js, as far as I've seen, the crashes go as far as the application containers goes. – Leroy Thompson Aug 02 '16 at 03:09
  • 1
    Check out this thread: https://groups.google.com/forum/#!topic/v8-users/n-dbQX1AvTM. BTW, even the Google C++ style guide says "We do not use C++ exceptions" https://google.github.io/styleguide/cppguide.html#Exceptions – Vladislav Ivanishin Aug 02 '16 at 19:49
  • 3
    @VladislavIvanishin only because of [legacy code](http://stackoverflow.com/questions/5184115/google-c-style-guides-no-exceptions-rule-stl) – jaggedSpire Aug 04 '16 at 14:29

1 Answers1

6

In general even if your code is compiled with -fno-exceptions (then new won't throw std::bad_alloc but it will return nullptr instead) the standard C++ library libstdc++ is compiled with exceptions then new will still throw std::bad_alloc when you're running out-of-memory.

That said, seriously, when you're running out-of-memory to crash as fast as possible is (more often than not) the best thing you can do. If you need some some sort of reliability it's much easier to have a monitor process that will restart your application.

What V8 does? Obviously they overloaded new operator and when allocation fails (malloc() still returns NULL, of course) they call a special function to handle low memory conditions. It dumps some debug information, report this error (you may have a custom error handler) and then (if error handler returns) call FATAL() to quit the application.

Browse source code at api.cc on GitHub. From code, simply:

When V8 cannot allocated memory FatalProcessOutOfMemory is called. The default OOM error handler is called and execution is stopped.

Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
  • 1
    _Obviously they overloaded `new` operator_ - do you know where in the code this overloaded operator is implemented? – user200783 Aug 04 '16 at 07:41
  • Base allocator for _internal_ classes is in allocator.h. There you also find NewArray() used in their own Vector class (same behavior, call FatalProcessOutOfMemory() if malloc() returned null). – Adriano Repetti Aug 04 '16 at 07:55