Backport crash fixes to Phantom::doExit from master

The relevant bits from these commits were applied:
cf12fc4a236e071382e9e6b9c391b606eac17ea1
a9809996b168a5696b917702ccc3696c70e71233
1e7829db97d5134336d6f9e4961c1cfd1d1bf9d5

https://github.com/ariya/phantomjs/issues/11642