Fixes to possible GetLastError bugs
GetLastError needs to be called immediately after the function whose
error code it is retrieving. This has been made particularly important
by VS 2015 which sometimes clears the error code when allocating memory.
See bug 528394 for details of the underlying issue.
These changes came from code inspection that looked for patterns that
appeared wrong. None of the issues look critical, although that depends
on what callers do with the error codes.