Showing posts with label error handling. Show all posts
Showing posts with label error handling. Show all posts

Saturday, May 12, 2012

ZeroMQ and C++ without exceptions

my comment in reply to martin_sustrik.

I wanted to post some code into the comment but I finally gave up. I will post it here instead. Disclaimer: this code has not been compiled.

class foo
{
public:
  ~foo() {}
  foo(foo&& other) {
    guts.a = std::move(other.a); // no-fail
  }
  foo& operator=(foo other) { // no-fail
    using std::swap; 
    swap(guts.a, other.guts.a); 
    return *this;
  } 
  static optional<foo> init() {
    optional<foo> result; 
    type guts = {}; // ~type() cleans up on exit
    guts.a.reset(new(std::nothrow) int(5));
    if (!guts.a) {return result;} // no foo constructed 
    result.reset(foo(guts)); //no-fail move construction
    return std::move(result); // no-fail move of result
  }
  int do() {return guts.a.get();} // a cannot be empty
private:
  struct type { std::unique_ptr<int> a; };
  type guts;
  foo(); // disabled
  foo(const foo&); // disabled
  foo(type&& gutsArg) {guts.a = std::move(gutsArg.a);} // no-fail
};

auto MyFoo = foo::init();
if (!MyFoo) return;
MyFoo->do();

if you want to return a detailed error from init() change init() to return a tuple:

  static std::tuple<error, optional<foo>> init();
and use tie to break the result into local vars:
  optional<foo> MyFoo;
  error MyError;
  std::tie(MyError, MyFoo) = foo::init();

Tuesday, November 1, 2011

FAIL_FAST

In Windows 7 an new weapon in the fight against bugs was released in the form of RaiseFailFastException

In a world where Windows Error Reporting (WER) collects each crash and reports it with a minidump. FAIL_FAST is essential to finding and fixing bugs quickly. Instead of laboring for a repro, just open the minidump and it points to the line of code that failed and usually has enough state to determine the cause.

FAIL_FAST should be used to report bugs in code. Transient or environmental failures like no-memory or access-denied are not suited for reporting via FAIL_FAST, rather things like 'I do not understand this enum value' or 'I did not expect this error value'

#define FAIL_FAST_FILTER() \
  __except(FailFastFilter(GetExceptionInformation())) \
  { \
  } do {} while(0,0)

inline
LONG WINAPI FailFastFilter(
  __in  struct _EXCEPTION_POINTERS* exceptionInfo)
{
  RaiseFailFastException(
    exceptionInfo - > ExceptionRecord,
    exceptionInfo - > ContextRecord,
    0);
  return EXCEPTION_CONTINUE_SEARCH;
}

template<typename Function>
auto FailFastOnThrow(
  Function && function) -> decltype(
      std::forward<Function>(function)())
{
  //
  // __ try must be isolated in its own
  // function in order for the compiler
  // to reason about C++ unwind in the
  // calling and called functions.
  //
  __try {
    return std::forward <Function >(function)();
  }
  FAIL_FAST_FILTER();
}

#define FAIL_FAST_ON_THROW(Function) \
  FailFastOnThrow((Function))

#define FAIL_FAST(Code) \
  FAIL_FAST_ON_THROW(
    [&]{ \
      RaiseException( \
        (Code), \
        EXCEPTION_NONCONTINUABLE, \
        0, \
        nullptr \
      ); \
    } \
  )

Tuesday, October 18, 2011

catch(…) is harmful and should be avoided

A common use of catch(...), even in the STD library implementation, is to free objects or to return to a known state on failure.

catch(...) has no information about the exception and therefore there is no way to reason about whether the code in the catch block will corrupt the process. Thus any code in a catch(...) is a potential danger to the process and the data it manages.

Whenever an exception is thrown and the search for a catch encounters a catch(...) block it must run all the destructors for the code inside the matching try to get the stack back to the correct state to run the catch block. At best this modifies the state, when it doesn't corrupt it. Then the catch block is likely to immediately rethrow the exception with the state at the most relevant part of the stack (where the throw occurred) erased.

This erasure is particularly unwanted when the exception is ultimately not handled and a Windows Error Report is generated with a dump of the state after the unhelpful catch(...) erased the part that would be most important to determine how to fix the bug.

Windows Error Reporting (WER) has changed the way I write code. I try to exit the process quickly (FAIL_FAST) whenever I reach an unexpected state. When there are no catch(...) blocks in the way I get great bugs generated directly from the WER with no repro necessary and I quickly issue a fix.

The good thing is that none of the catch(...) blocks are needed and that the replacements do not corrupt the state when the exception type is not known to the call stack. The common case where you might use catch(...) to free an allocation or restore state can be replaced by an unwinder. In the case where catch(...) is used to suppress an exception it should be replaced with a FAIL_FAST_ON_THROW([]{});. This will not suppress the exception (which as described earlier invites data corruption), instead when an exception that is not expected and handled reaches this barrier a WER will be generated and the process will exit without any corruption.

These boundaries can be enforced using error contract functions:

template<typename Function>
HRESULT HResultErrorContract(Function && function)
{
  HRESULT result = S_OK;
  FAIL_FAST_ON_THROW(
  [&] {
    // any C++ exception that is uncaught or any SEH
    // will cause the process to exit
    try
    {
      unique_hresult hresult = (
        std::forward<Function>(function)());
      result = hresult.get();
    } catch (const std::bad_alloc&) {
      result = E_OUTOFMEMORY;
    } catch (const unique_winerror::exception& e) {
      result = HRESULT_FROM_WIN32(e.get());
    } catch (const unique_hresult::exception& e) {
      result = e.get();
    }
  }
  );
  return result;
}

HRESULT MyDllExport()
{
  // no exception can get past
  // HResultErrorContract
  return HResultErrorContract(
  [&]() -> unique_hresult {
    // It is safe to throw C++ exceptions
    unique_hresult hresult;
    // RestoreState is only called on failure
    ON_UNWIND(unwindWork, []{ RestoreState(); });
    hresult = Work();
    if (hresult.ok()) {
      unwindWork.Dismiss();
    }
    return hresult;
  }
}

Thursday, October 13, 2011

error contract functions

In code for Windows there are many places that are boundaries across which C++ exceptions cannot safely travel.

The most accurate way to describe the boundaries is to say that C++ exceptions cannot be sent across modules (exe and all and sys are all examples of modules). It may not be completely clear from that statement when a module boundary is crossed. Here are some examples that should help reason about when a module boundary is being crossed. The most straight forward situation is when a function is exported from a dll so that it can be called from a different module. but it can get considerably more abstract when you think of dll methods that return COM interfaces or structs containing function pointers. Then add all the PROC's used in Windows programming. WNDPROC, DLGPROC and so many other PROC's are all functions in one module called from a different module.

Any C++ exceptions that occur in these boundary functions must be stopped before the calling module try's to process them. The problem is that exception types are not always the same in each module. if the calling module try's to process an exception from a different module it could be that the type has different members or that the size of the members is different and the constructors, destructors and other methods compiled into the calling module are the wrong methods for an instance of the type that was constructed in the called module. Crashes or data corruption will ensue.

When building all these boundary functions it becomes important to centralize the catch blocks used to convert exceptions to errors and the FAIL_FAST for uncaught exceptions. Without centralization there is a lot of duplicated code.

With lambdas and perfect-forwarding using r-value references we can build error contract functions that will centralize the boundary contract for errors in one function and apply that contract to many functions. Here is an implementation of a error contract function for use with boundary functions that return HRESULT.

template<typename Function>
HRESULT HResultErrorContract(Function && function)
{
  HRESULT result = S_OK;
  FAIL_FAST_ON_THROW(
  [&] {
    // any C++ exception that is uncaught or any SEH
    // will cause the process to exit
    try
    {
      unique_hresult hresult = (
        std::forward<Function>(function)());
      result = hresult.get();
    } catch (const std::bad_alloc&) {
      result = E_OUTOFMEMORY;
    } catch (const unique_winerror::exception& e) {
      result = HRESULT_FROM_WIN32(e.get());
    } catch (const unique_hresult::exception& e) {
      result = e.get();
    }
  }
  );
  return result;
}

HRESULT MyDllExport()
{
  // no exception can get past
  // HResultErrorContract
  return HResultErrorContract(
  [&]() -> unique_hresult {
    // It is safe to throw C++ exceptions
    unique_hresult hresult;
    hresult = Work();
    return hresult;
  }
}

error contract functions are specific to the module they are used in, they are not candidates for a general shared template library. This is because each module uses different libraries and therefore has different exceptions that must be caught and translated.

Tuesday, October 11, 2011

C++ exception implementation on Windows

On windows c++ exceptions are implemented using an exception facility provided by the OS. The OS exception system (Structured Exception Handling or SEH) does not have the same semantics as C++ exception handling.

Windows SEH works in C or assembly code as well as C++. the C++ compiler and the OS are both involved. SEH is used to report many runtime errors and logic errors in code. Often they are unrecoverable. Access Violation, Stack Overflow, RPC errors, are all reported using SEH exceptions. Here is some code that uses SEH

LONG WINAPI MyExceptionFilter(
  __in  struct _EXCEPTION_POINTERS *ExceptionInfo,
  __in DWORD ExceptionCode
)
{
    // code in an exception filter must be 
    // very robust, careful and have minimal 
    // dependencies. often t\filters are run 
    // at times of extreme duress or with 
    // malicious intent

    //
    // must return one of these three values:

    // EXCEPTION_CONTINUE_EXECUTION
    //   re execute the instruction that 
    //   triggered the exception. if it
    //   fails again the new exception 
    //   will be marked
    //   EXCEPTION_NONCONTINUABLE_EXCEPTION

    // EXCEPTION_CONTINUE_SEARCH
    //   call the next registered 
    //   exception filter

    // EXCEPTION_EXECUTE_HANDLER
    //   run all the finally blocks for
    //   nested try's and then runs the 
    //   __except block and then runs 
    //   the finally block and then 
    //   continues after the __try/
    //   __except/__finally

    return EXCEPTION_CONTINUE_SEARCH;
}

void* ptr = nullptr;
__try
{
  ptr = malloc(1);
  if (!ptr) {
    __leave;
  }
  Work(ptr); // might AV or overflow stack, etc..
  // or explicitly call RaiseException() to 
  // raise an SEH
} __except (
    // registers MyExceptionFilter for any SEH
    // that occurs in the __try
    MyExceptionFilter(
      GetExceptionInformation(),
      GetExceptionCode()))
{
  // MyExceptionFilter returned 
  // EXCEPTION_EXECUTE_HANDLER
}
__finally()
{
  // the stack is unwinding due to a return
  // or an exception that is handled here or
  // up the stack from here
  if (ptr) {
    free(ptr);
  }
}

Hopefully it is obvious that an SEH exception will not cause C++ destructors to be called without some more work. The C++ compiler supports __try/__except/__finally and also supports try/catch, but not in the same function. Also, the C++ compiler will not allow __try/__except/__finally to be used in a function that has a local variable with a destructor.

Disclaimer - this is inaccurate yet provides a mental picture suitable for reasoning about the intersection of SEH and C++. - When the C++ compiler sees a try it inserts a __try, and an __except with a filter that is passed information about the catch clauses and catch blocks and destructors in scope. The C++ compiler replaces each throw with a RaiseException() that stores the exception object in the SEH ExceptionInformation. Then the SEH mechanism calls the registered filter and the filter tries to match the catch block type to the exception object type. If a catch block matches the filter calls the appropriate destructors and the appropriate catch block and then returns EXCEPTION_EXECUTE_HANDLER to continue after the catch block.

The C++ compiler also does not implement throw() semantics. Using what we know we can implement those semantics:

#define FAIL_FAST_FILTER() \
  __except(FailFastFilter(GetExceptionInformation())) \
  { \
  } do {} while(0,0)

inline
LONG WINAPI FailFastFilter(
  __in  struct _EXCEPTION_POINTERS* exceptionInfo)
{
  RaiseFailFastException(
    exceptionInfo - > ExceptionRecord,
    exceptionInfo - > ContextRecord,
    0);
  return EXCEPTION_CONTINUE_SEARCH;
}

template<typename Function>
auto FailFastOnThrow(
  Function && function) -> decltype(
      std::forward<Function>(function)())
{
  //
  // __ try must be isolated in its own
  // function in order for the compiler
  // to reason about C++ unwind in the
  // calling and called functions.
  //
  __try {
    return std::forward <Function >(function)();
  }
  FAIL_FAST_FILTER();
}

#define FAIL_FAST_ON_THROW(Function) \
  FailFastOnThrow((Function))

HRESULT MyDllExport()
{
  HRESULT result = S_OK;
  FAIL_FAST_ON_THROW(
  [&] {
    // any C++ exception that is uncaught or any SEH
    // will cause the process to exit
    try
    {
      unique_hresult hresult;
      hresult = Work();
      result = hresult.get();
    } catch (const std::bad_alloc&) {
      result = E_OUTOFMEMORY;
    } catch (const unique_winerror::exception& e) {
      result = HRESULT_FROM_WIN32(e.get());
    } catch (const unique_hresult::exception& e) {
      result = e.get();
    }
  }
  );
  return result;
}

Next time we will build error contract functions to reduce the amount of code in each export.

Thursday, September 29, 2011

unique_error

I work in places that abjure exceptions in most of the code. I have spent years writing both error-code and exception based error handling and building libraries for both environments. With some simple building blocks error-codes and exceptions can be joined such that each library can be written agnostic to exceptions and allow each caller of the library to choose whether to throw or pass error codes. These also implement certain exception features; such as requiring explicit checking of error codes.

One building block is unique_error.

unique_error serves much the same function as the std::system_error but with additional features and eschewing some things that blocked my adoption of std::system_error. unique_error does not require that all the error values of a type be redefined. It uses traits discovered by ADL to specify the behavior. It terminates the program if an error is set and then not checked. unique_error is also similar to unique_ptr in that it treats an error like a resource.

Here is the complete definition of unique_winerror:

namespace unique_winerror_def
{
struct tag {};

// found by ADL via the tag&& parameter
inline bool unique_error_ok(DWORD winerror, tag &&)
{
  return winerror == ERROR_SUCCESS;
}

// found by ADL via the tag&& parameter
inline DWORD unique_error_default(tag &&)
{
  return ERROR_SUCCESS;
}
}

//
// implementations of these must be included
// in the final module
//
void unique_error_report_initiated(
  DWORD value,
  unique_winerror_def::tag &&);
void unique_error_report_reset(
  DWORD value,
  unique_winerror_def::tag &&);

typedef unique_error<unique_winerror_def::tag>
unique_winerror;

inline unique_winerror make_winerror_if(BOOL is_last_error)
{
  unique_winerror result;
  if (is_last_error) {
    return std::move(result.reset(GetLastError()));
  }
  return std::move(result);
}

inline
unique_winerror::static_error winerror_cast(DWORD raw)
{
  return unique_winerror::cast(raw);
}

Using unique_winerror

CreateEvent example

Starting from a previous post we can now improve the code further:

namespace Win32
{
template<typename Resource, Resource InvalidValue>
std::pair<unique_winerror, Resource>
WinerrorAndResource(Resource resource)
{
  return std::make_pair(
      make_winerror_if(Resource == InvalidValue),
      Resource);
}

namespace Event
{
inline auto EventAndWinerror(
  HANDLE apiResult) -> decltype(
      WinerrorAndResource<HANDLE, nullptr>(
          apiResult))
{
  return WinerrorAndResource<HANDLE, nullptr>(
      apiResult);
}
}
}

// now you can write this
namespace we = Win32::Event;
unique_winerror winerror;
HANDLE event = nullptr;

std::tie(
  winerror,
  event) = we::EventAndWinerror(
      CreateEvent(
          nullptr
          make(we::Reset::Manual),
          make(we::Value::Reset),
          nullptr));
if (!winerror)
{
  return;
}

LoadString example

The complexities of LoadString for arbitrary sized strings is encapsulated here:

inline
unique_winerror
LoadStringRaw(
  HINSTANCE instance,
  UINT id,
  const range<WCHAR*>& space,
  range<WCHAR*>* spaceUsed,
  size_t* spaceRequested)
{
  if (spaceUsed) {
    *spaceUsed = space;
    spaceUsed->advance_end(-space.size());
  }

  if (spaceRequested) {
    *spaceRequested = space.size();
  }

  SetLastError(ERROR_SUCCESS);

  int loadResult = LoadStringW(
      instance,
      id,
      space.begin(),
      space.size());

  auto winerror = make_winerror_if(TRUE);

  if (loadResult >= 0) {
    if ((loadResult + 1) < space.size()) {
      if (winerror.ok()) {
        *spaceUsed = space;
        spaceUsed->advance_end(
          loadResult - space.size());
      }
    } else {
      *spaceRequested = std::max<size_t>(
          3,
          static_cast<size_t>(space.size() * 1.5));

      if (winerror.ok()) {
        winerror = winerror_cast(ERROR_MORE_DATA);
      }
    }
  } else {
    if (winerror.ok()) {
      winerror = winerror_cast(ERROR_UNIDENTIFIED_ERROR);
    }
  }

  return winerror;
}

inline
std::wstring
LoadStdString(
  HINSTANCE instance,
  UINT id,
  size_t sizeLimit = 2048,
  size_t initialSize = 80)
{
  unique_winerror winerror;
  std::wstring result;
  RANGE_NAMESPACE::range<WCHAR*> spaceUsed;
  size_t spaceRequested = initialSize;

  while (spaceRequested < sizeLimit) {
    result.resize(spaceRequested);
    winerror = LoadStringRaw(
        instance,
        id,
        make_range_raw(result),
        &spaceUsed,
        &spaceRequested);
    if (winerror != winerror_cast(ERROR_MORE_DATA)) {
      winerror.throw_if();
      break;
    }
    winerror.suppress();
    continue;
  }

  return std::move(result);
}

std::wstring title;

title = LoadStdString(
    hInstance,
    IDS_APP_TITLE);

Implementation

Maintained here.

template<typename ErrorTag>
class unique_error
{
public:
  typedef unique_error
  this_type;

  typedef ErrorTag
  tag;

  typedef decltype(unique_error_default(tag()))
  type;

  class static_error
  {
  private:
    type value;
  };

  static static_error cast(type raw);
  static this_type make(type raw);
  static this_type make(const static_error& other);

  ~unique_error();

  unique_error();
  unique_error(static_error other);
  unique_error(unique_error && other);
  unique_error(const unique_error& other);

  void swap(unique_error& other);
  unique_error& operator=(unique_error other);

  operator
  typename unspecified_bool<this_type>::type() const;

  this_type& reset();
  this_type& reset(type raw);
  type release();

  type get() const;
  bool try_ok() const;
  bool ok() const;

  const this_type& suppress() const;
  this_type& suppress();

  void throw_if(const std::string& message) const;
  void throw_if(const char* message = NULL) const;

private:
  type value;
  mutable Disposition::type disposition;
};

Tuesday, September 20, 2011

NTSTATUS

NTSTATUS was defined for code native to the Windows NT operating system. It was a part of the very clean separations built between the core OS and the various subsystems where user code was expected to run (POSIX, WIN32, WIN16/DOS, OS/2). Over time it has begun to leak into code in the WIN32 subsystem. One example of leakage is the BCrypt Api's.

Just including ntstatus.h and windows.h together produces errors:

main.cpp
#include <windows.h>
#include <winternl.h>
#include <ntstatus.h>

int main()
{
  return 0;
}

>cl main.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

main.cpp
[redacted]ntstatus.h(147) 
    : warning C4005: 'STATUS_WAIT_0' 
        : macro redefinition
    [redacted]winnt.h(1983) 
        : see previous definition of 'STATUS_WAIT_0'
...

I spent some hours recently tracking down an incantation that would allow ntstatus.h to be included without the errors, the following was the result:

#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS

#include <winternl.h>
#include <ntstatus.h>

NTSTATUS defines 2bits to hold four severity levels, SUCCESS, INFORMATION, WARNING, ERROR.
There are 12bits set aside for Facilities, which are used to create feature-specific error codes. Within each facility is 16bits to define codes specific to that facility.
FACILITY_NULL contains generic codes like STATUS_SUCCESS.
FACILITY_NTWIN32 contains all the WINERROR codes.

Checking NTSTATUS values must be done via the NT_SUCCESS(ntstatus), NT_INFORMATION(ntstatus), NT_WARNING(ntstatus) or NT_ERROR(ntstatus) macros.

NTSTATUS Usage

NTSTATUS ApiReturningNtStatus(HANDLE handle)
{
  if (handle == INVALID_HANDLE_VALUE) {
    return STATUS_INVALID_PARAMETER;
  }
  return STATUS_SUCCESS;
}

NTSTATUS ntstatus = STATUS_SUCCESS;
HANDLE handle = INVALID_HANDLE_VALUE;
ntstatus = ApiReturningNtStatus(handle);
if (!NT_SUCCESS(ntstatus))
{
  printf("ApiReturningNtStatus returned %x", ntstatus);
  exit();
}

Conversions to NTSTATUS

HRESULT = S_OK;
NTSTATUS ntstatus = STATUS_SUCCESS;
if (hr & FACILITY_NT_BIT)
{
  ntstatus = hr & ~FACTILITY_NT_BIT;
} else if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
{
  ntstatus = NTSTATUS_FROM_WIN32(HRESULT_CODE(hr));
} else if (SUCCEEDED(hr))
{
  ntstatus = STATUS_SUCCESS;
} else
{
  ntstatus = STATUS_UNSUCCESSFUL;
}

DWORD winerror = ERROR_SUCCESS;
NTSTATUS ntstatus = STATUS_SUCCESS;
ntstatus = NTSTATUS_FROM_WIN32(winerror);

Conversions from NTSTATUS

NTSTATUS ntstatus = STATUS_SUCCESS;
HRESULT hr = HRESULT_FROM_NT(ntstatus);

NTSTATUS ntstatus = STATUS_SUCCESS;
DWORD winerror = RtlNtStatusToDosError(ntstatus);
if (winerror == ERROR_MR_MID_NOT_FOUND)
{
  // there is no conversion
  return ERROR_UNIDENTIFIED_ERROR;
#if 0
  // The following is common, but doesn't work out well
  // especially when combined with HRESULT_FROM_WIN32
  // and NTSTATUS_FROM_WIN32
  return ntstatus;
#endif
}

Thursday, September 15, 2011

HRESULT

HRESULT is the highest fidelity error code of the three big ones (WINERROR, NTSTATUS and HRESULT). Both of the other error types can be converted, without any information loss, into an HRESULT via HRESULT_FROM_WIN32 and HRESULT_FROM_NT.

HRESULT was defined as the error type for COM functions to return.

HRESULT and NTSTATUS have a similar structure but very different sets of values.
1bit holds 2 severity levels, SUCCESS, ERROR.
1bit is used to allow HRESULT_FROM_NT to store a full NTSTATUS in an HRESULT. The define for this bit is FACILITY_NT_BIT.
There are 12bits set aside for Facilities, which are used to create feature-specific error codes. Within each facility is 16bits to define codes specific to that facility.
FACILITY_NULL contains generic codes like S_OK, E_FAIL and S_FALSE.
FACILITY_WIN32 contains all the WINERROR codes.

Checking HRESULT values must be done via the SUCCEEDED(hr) or FAILED(hr) macros.

HRESULT Usage

HRESULT ApiReturningHresult(HANDLE handle)
{
  if (handle == INVALID_HANDLE_VALUE) {
    return E_HANDLE;
  }
  return S_OK;
}

HRESULT hr = S_OK;
HANDLE handle = INVALID_HANDLE_VALUE;
hr = ApiReturningHresult(handle);
if (FAILED(hr))
{
  printf("ApiReturningHresult returned %x", hr);
  exit();
}

Conversions to HRESULT

NTSTATUS ntstatus = STATUS_SUCCESS;
HRESULT hr = HRESULT_FROM_NT(ntstatus);

DWORD winerror = ERROR_SUCCESS;
HRESULT hr = HRESULT_FROM_WIN32(winerror);

Conversions from HRESULT

HRESULT = S_OK;
NTSTATUS ntstatus = STATUS_SUCCESS;
if (hr & FACILITY_NT_BIT)
{
  ntstatus = hr & ~FACILITY_NT_BIT;
} else if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
{
  ntstatus = NTSTATUS_FROM_WIN32(HRESULT_CODE(hr));
} else if (SUCCEEDED(hr))
{
  ntstatus = STATUS_SUCCESS;
} else
{
  ntstatus = STATUS_UNSUCCESSFUL;
}

HRESULT hr = S_OK;
DWORD winerror = ERROR_SUCCESS;
if (SUCCEEDED(hr))
{
  winerror = S_OK;
} else if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
{
  winerror = HRESULT_CODE(hr);
} else
{
  winerror = ERROR_UNIDENTIFIED_ERROR;
}

Tuesday, September 13, 2011

WINERROR

WINERROR has it's roots in DOS which is why it is also referred to as DosError. RtlNtStatusToDosError() is an example which will be discussed more later. DOS errors were in turn derived from the C standard library errno.

Values of WINERROR are defined in winerror.h and look like ERROR_SUCCESS. They are an enumeration that are expected to fit in the lower 16bits of the 32bit WINERROR type, more on that later. WINERROR values are sometimes returned through the API result, but often an API will return a BOOL or HANDLE and pass any errors to SetLastError() and then return FALSE or an invalid-handle, the caller will retrieve the WINERROR by calling GetLastError(). ERROR_SUCCESS is the only success value for WINERROR.

Api Examples:

DWORD ApiReturningWinerror(HANDLE handle)
{
  if (handle == INVALID_HANDLE_VALUE) {
    return ERROR_INVALID_PARAMETER;
  }
  return ERROR_SUCCESS;
}

DWORD winerror = ERROR_SUCCESS;
HANDLE handle = INVALID_HANDLE_VALUE;
winerror = ApiReturningWinerror(handle);
if (winerror != ERROR_SUCCESS)
{
  printf("ApiReturningWinerror returned %d", winerror);
  exit();
}

BOOL ApiReturningBool(HANDLE handle)
{
  if (handle == INVALID_HANDLE_VALUE) {
    SetLastError(ERROR_INVALID_PARAMETER);
    // The caller should call GetLastError()
    return FALSE;
  }
  // the common pattern is that SetLastError
  // is only called on failure.
  // Thus the caller should NOT call GetLastError()
  return TRUE;
}

DWORD winerror = ERROR_SUCCESS;
HANDLE handle = INVALID_HANDLE_VALUE;
if (!ApiReturningBool(handle))
{
  winerror = GetLastError();
  printf("ApiReturningBool returned %d", winerror);
  exit();
}

Conversions to WINERROR

NTSTATUS ntstatus = STATUS_SUCCESS;
DWORD winerror = RtlNtStatusToDosError(ntstatus);
if (winerror == ERROR_MR_MID_NOT_FOUND)
{
  // there is no conversion
  return ERROR_UNIDENTIFIED_ERROR;
#if 0
  // The following is common, but doesn't work out well
  // especially when combined with HRESULT_FROM_WIN32
  // and NTSTATUS_FROM_WIN32
  return ntstatus;
#endif
}

HRESULT hr = S_OK;
DWORD winerror = ERROR_SUCCESS;
if (SUCCEEDED(hr))
{
  winerror = S_OK;
} else if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
{
  winerror = HRESULT_SCODE(hr);
} else
{
  winerror = ERROR_UNIDENTIFIED_ERROR;
}

Conversions from WINERROR

DWORD winerror = ERROR_SUCCESS;
HRESULT hr = HRESULT_FROM_WIN32(winerror);

DWORD winerror = ERROR_SUCCESS;
NTSTATUS ntstatus = NTSTATUS_FROM_WIN32(winerror);

Both of the FROM_WIN32 macros work by masking only the lower 16bits of the WINERROR value into the resulting NTSTATUS or HRESULT

Thursday, September 8, 2011

error codes in Windows

Differences between and best practices for WINERROR, HRESULT, RPC_STATUS, SECURITY_STATUS and NTSTATUS?

Why would a developer care?

These error types and their values are an often ignored part of the API contract. Using the return value incorrectly has the same type of consequences as using a cast to pass the wrong data type to a parameter of an API, code just doesn't work, and often fails first in the wild.

I recently began running into code like this:

// ERROR_SUCCESS is a WINERROR value
NTSTATUS status = ERROR_SUCCESS;
WCHAR* buffy;

buffy = (WCHAR*)malloc(1);
if (buffy == NULL)
{
  // this is an HRESULT value
  status = E_OUTOFMEMORY;
}

// not only is this a WINERROR value, but HRESULT and
// NTSTATUS have many success values, not just one
if (status != ERROR_SUCCESS)
{
  return status;
}

I went searching for information about what each type is and the relationships between them and how to use them correctly. Here is what I learned.

They are all 32bit values, some signed some unsigned. Some are defined in terms of bit fields and require macros or inline-functions to check their current state. Others are straight enumerations.

One of the complexities is best demonstrated with the HRESULT type. Lets look at the out of memory condition. Here are some of the possible encodings:

ExpressionHRESULT value
E_OUTOFMEMORY0x8007000E
HRESULT_FROM_WIN32(ERROR_OUTOFMEMORY)0x8007000E
HRESULT_FROM_NT(STATUS_NO_MEMORY)0xD0000017
HRESULT_FROM_NT(
NTSTATUS_FROM_WIN32(ERROR_OUTOFMEMORY))
0xD007000E
STG_E_INSUFFICIENTMEMORY0x80030008
NTE_NO_MEMORY0x8009000E

There was some effort to make the values agree across the different expressions.

Many Api's will pick a set of return codes and then build internal maps from all the errors they receive from other Api's to the set they have decided to return. Thus most code calling Api's can expect that only one encoding will be returned.

Primary Windows Error Types

There will be subsequent posts that expand on each of these types. Here is a summary:

WINERROR

Includewinerror.h
TypeDWORD
Structurevalues in the range 0-16384
Successvalue == ERROR_SUCCESS
Failurevalue != ERROR_SUCCESS
ConversionsHRESULT_FROM_WIN32(value)
NTSTATUS_FROM_WIN32(value)

HRESULT

Includewinerror.h
TypeHRESULT
Structure[1bit Severity]
[1bit Reserved]
[1bit Customer]
[1bit FACILITY_NT_BIT]
[12bit Facility]
[16bit Code]
SuccessSUCCEEDED(value)
FailureFAILED(value)
ConversionsHRESULT is a superset
of all the other error types.
They all have lossless conversions
to HRESULT but it doesn't have
lossless conversions to anything else

NTSTATUS

Include
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS

#include <winternl.h>
#include <ntstatus.h>
TypeNTSTATUS
Structure[2bit Severity]
[1bit Customer]
[1bit Reserved]
[12bit Facility]
[16bit Code]
SuccessNT_SUCCESS(value)
Failure!NT_SUCCESS(value)
Other
Tests
NT_INFORMATIONAL(value)
NT_WARNING(value)
NT_ERROR(value)
ConversionsHRESULT_FROM_NT(value)

Derived/Subset Windows Error Types

RPC_STATUS

Includerpcnterr.h
TypeRPC_STATUS
StructureA subset of the WINERROR values, redefined as RPC_S_...
Successvalue == RPC_S_OK
Failurevalue != RPC_S_OK
ConversionsHRESULT_FROM_WIN32(value)
NTSTATUS_FROM_WIN32(value)

SECURITY_STATUS

Includewinerror.h
TypeSECURITY_STATUS or HRESULT
StructureA subset of the HRESULT values (from FACILITY_NULL and FACILITY_SECURITY)
SuccessSUCCEEDED(value)
FailureFAILED(value)
Conversions