improve error checking. set error code on error, and check malloc return.
add missing unlock in one case. ok lteo miod
check stack push return and make some effort to clean up. ok beck miod