Valgrind and static analyzer fixes.

* Properly cleanup `hash` on exit.
* Variables that should not be placed in registers either marked as `volatile` or accessed through `ACCESS_ONCE` macro;
* Do not depend on OS implementation of `dirname()`;
* Various cleanups and comment fixes.