Fix memory leaks and GMP shutdown sequence.