AvImd
AvImd

Reputation: 75

Which WinAPI function set last error to ERROR_SUCCESS if no error occured?

There is a large legacy codebase which seems to fail in some hard to reproduce and investigate situation.

It calls some WinAPI function, say, CopyFile, and instead of checking the return code, checks GetLastError() value. I know this is wrong, but it would be really nice to know whether non-null last error value originates from this call or something that happened earlier. If I was sure that CopyFile sets last error to ERROR_SUCCESS in case everything went well, it would be enough to conclude that this specific call failed.

MSDN mentions that some functions do this and some do not but does not tell specifically which ones do. Is there some unofficial list/reference which covers this question?

Upvotes: 1

Views: 911

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596156

GetLastError() usage is documented on a per-function basis. There is no single master list that documents which functions act which way in regards to GetLastError(). If any given function is not documented as setting the last error, do not use GetLastError() to check the last error after the function exits.

Most functions that do set the last error do not set it on success, only on failure, and are documented as such.

Functions that do set the last error on success are documented as such, and will also document which success conditions set the last error to which value. This is typically used in cases where a function's return value is ambiguous as to whether the function succeeded or failed, so GetLastError() is used to differentiate. For instance, most functions return 0 on failure, but some functions may return 0 on success and failure. In such cases, if GetLastError() then returns 0 (or a defined success code) then the function succeeded, otherwise the function failed. GetTLSValue() is one example of this.

A notable exception to this are functions that create named kernel objects (CreateMutex(), CreateEvent(), CreateSemaphore(), etc). They return a non-zero value on success, but also GetLastError() will return either 0 or ERROR_ALREADY_EXISTS depending on whether the function returns a handle to a newly-created object or an existing object. This is documented accordingly for each function.

Upvotes: 7

Related Questions