HRESULT

Last updated

HRESULT is a computer programming data type that represents the completion status of a function.

Contents

It is used in the source code of applications targeting Microsoft Windows and earlier IBM/Microsoft OS/2 operating systems, but its design does not limit its use to these environments; it can be used in any system supporting 32-bit integers.

The original purpose of HRESULT was to lay out ranges of status codes for both public and Microsoft internal use in order to prevent collisions between status codes in different subsystems of the OS/2 operating system. [ citation needed ]

An HRESULT is designed to simultaneously be both a simple numerical value and a structure of fields indicating severity, facility and status code.

Use of HRESULT is most commonly encountered in COM programming, where it forms the basis for a standardized error handling mechanism, but its use is not limited to COM. For example, it can be used as an alternative to the more traditional use of a boolean pass/fail result.

Data structure

HRESULT is defined in a system header file as a 32-bit, signed integer [1] and is often treated opaquely as an integer, especially in code that consumes a function that returns HRESULT. A HRESULT value consists of the following separate items:

An HRESULT value is a structure with the following bit-fields: [2]

Bit313029282726252423222120191817161514131211109876543210
FieldSRCNXFacilityCode

Numeric representation

An HRESULT value is sometimes displayed as a hexadecimal value with 8 digits.

Examples: [3]

Sometimes an HRESULT value is shown as a signed integer, but this is less common and harder to read.

Name representation

An HRESULT is sometimes represented as an identifier with the format Facility_Severity_Reason: [4]

For example, STG_E_FILENOTFOUND indicates a storage related error, file does not exist.

The facility part is omitted if the facility is 0 (FACILITY_NULL) or for some very common values. For example: S_OK, E_FAIL, E_INVALIDARG.

This representation is easier to read than a numerical format but is less precise since although based on convention there is no definitive algorithm to convert between value and name.

IErrorInfo

The HRESULT was originally defined in the IBM/Microsoft OS/2 operating system as a general-purpose error return code, and subsequently adopted in Windows NT.

Microsoft Visual Basic substantially enhanced the HRESULT error reporting mechanisms, by associating an IErrorInfo object with an HRESULT and storing (a pointer to) an IErrorInfo object in thread-local storage. The IErrorInfo mechanism allows programs to associate a broad variety of information with a particular HRESULT error: the class of the object that raised the error, the interface of the object that raised the error, error text; and a link to a help topic in a help file. In addition, receivers of an HRESULT error can obtain localized text for the error message on demand.

Subsequently, HRESULT, and the associated IErrorInfo mechanism were used as the default error reporting mechanism in COM.

Support of the IErrorInfo mechanism in Windows is highly inconsistent. Older Windows APIs tend to not support it at all, returning HRESULTs without any IErrorInfo data. More modern Windows COM subsystems often provide extensive error information in the message description of the IErrorInfo object. The more advanced features of the IErrorInfo error mechanisms—help links, and on-demand localization—are rarely used.

In the .NET Framework, HRESULT/IErrorInfo error codes are translated into CLR exceptions when transitioning from native to managed code; and CLR exceptions are translated to HRESULT/IErrorInfo error codes when transitioning from managed to native COM code.

Using an HRESULT value

Since HRESULT is defined as a signed integer and since the severity field is the most significant bit, a negative value indicates failure and other values indicate success. The most commonly used success code is S_OK which has value 0. However, in rare circumstances, a function returns a success code with additional information such as S_FALSE which has value 1.

When an HRESULT value is displayed as hexadecimal (generally for debugging purposes) a developer can identify a value as indicating failure when it starts with digit 8 or greater in the 8th and most significant place. Note that if not padded to 8 digits with leading zeroes, a value might mistakenly be seen as failure. For example, 80005 is success even though it starts with 8. If padded to 8 digits this becomes clear: 00080005. This is somewhat contrived since generally success is 0 which is clearly a success code.

Programmatic ways to check for failure status are to test for negative or to use a system-defined macro. [5]

HRESULT hr = func(...); if (hr < 0) ; // failed if (hr >= 0) ; // succeeded if (FAILED(hr)) ; // failed if (SUCCEEDED(hr)) ; // succeeded

Testing for 0 such as (hr) or (!hr) will work most of the time but is incorrect for the rarely used success codes other than S_OK such as S_FALSE.

To obtain the code part of an HRESULT, use the HRESULT_CODE() macro.

Use the ERR.EXE tool to translate a value to the corresponding message text.

The ERRLOOK.EXE tool can be used to display error strings associated with a given HRESULT value. It can be run from a Visual Studio command prompt.

The win32SetErrorInfo associates an HRESULT value with a corresponding IErrorInfo object. GetErrorInfo reads this information.

The win32 FormatMessage can be used to get a human readable description of some non-IErrorInfo HRESULT values.

The winerror.h header file defines some commonly used HRESULT values. HRESULT values are sometimes encoded in the header (.h) files of a subsystem. These values are also defined in the corresponding header files of the Microsoft Windows Platforms SDK or DDK.

Origin of name

The name HRESULT appears to mean "result handle" since many other Windows types use H to mean handle. For example, HMODULE is a module handle which means an HMODULE value refers to a module resource. However, an HRESULT value does not refer to a resource so it is not a handle. According to Raymond Chen "in the old days it really was a handle to an object that contained rich error information ... The COM team decided that the cost/benefit simply wasn’t worth it, so the HRESULT turned into a simple number. But the name stuck." [6]

Related Research Articles

In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler; the details of how this is done depend on whether it is a hardware or software exception and how the software exception is implemented.

The Portable Executable (PE) format is a file format for executables, object code, DLLs and others used in 32-bit and 64-bit versions of Windows operating systems, and in UEFI environments. The PE format is a data structure that encapsulates the information necessary for the Windows OS loader to manage the wrapped executable code. This includes dynamic library references for linking, API export and import tables, resource management data and thread-local storage (TLS) data. On NT operating systems, the PE format is used for EXE, DLL, SYS, MUI and other file types. The Unified Extensible Firmware Interface (UEFI) specification states that PE is the standard executable format in EFI environments.

<span class="mw-page-title-main">Windows API</span> Microsofts core set of application programming interfaces on Windows

The Windows API, informally WinAPI, is the foundational application programming interface (API) that allows a computer program to access the features of the Microsoft Windows operating system in which the program is running.

The C preprocessor is the macro preprocessor for several computer programming languages, such as C, Objective-C, C++, and a variety of Fortran languages. The preprocessor provides inclusion of header files, macro expansions, conditional compilation, and line control.

The BMP file format or bitmap, is a raster graphics image file format used to store bitmap digital images, independently of the display device, especially on Microsoft Windows and OS/2 operating systems.

<span class="mw-page-title-main">Microsoft Foundation Class Library</span> Windows OS object-oriented library

Microsoft Foundation Class Library (MFC) is a C++ object-oriented library for developing desktop applications for Windows.

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

In computer programming, a magic number is any of the following:

In computing, the exit status, or exit code, of a terminated process is an integer number that is made available to its parent process. In DOS, this may be referred to as an errorlevel.

In computing, syslog is a standard for message logging. It allows separation of the software that generates messages, the system that stores them, and the software that reports and analyzes them. Each message is labeled with a facility code, indicating the type of system generating the message, and is assigned a severity level.

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.

In computer programming, a semipredicate problem occurs when a subroutine intended to return a useful value can fail, but the signalling of failure uses an otherwise valid return value. The problem is that the caller of the subroutine cannot tell what the result means in this case.

The Microsoft Windows family of operating systems employ some specific exception handling mechanisms.

This article describes the calling conventions used when programming x86 architecture microprocessors.

<span class="mw-page-title-main">Object Manager (Windows)</span>

Object Manager is a subsystem implemented as part of the Windows Executive which manages Windows resources. Resources, which are surfaced as logical objects, each reside in a namespace for categorization. Resources can be physical devices, files or folders on volumes, Registry entries or even running processes. All objects representing resources have an Object Type property and other metadata about the resource. Object Manager is a shared resource, and all subsystems that deal with the resources have to pass through the Object Manager.

Component Object Model (COM) is a binary-interface standard for software components introduced by Microsoft in 1993. It is used to enable inter-process communication (IPC) object creation in a large range of programming languages. COM is the basis for several other Microsoft technologies and frameworks, including OLE, OLE Automation, Browser Helper Object, ActiveX, COM+, DCOM, the Windows shell, DirectX, UMDF and Windows Runtime.

In computing, an error code is a numeric or alphanumeric code that indicates the nature of an error and, when possible, why it occurred. Error codes can be reported to end users of software, returned from communication protocols, or used within programs as a method of representing anomalous conditions.

Windows Runtime (WinRT) is a platform-agnostic component and application architecture first introduced in Windows 8 and Windows Server 2012 in 2012. It is implemented in C++ and officially supports development in C++, Rust/WinRT, Python/WinRT, JavaScript-TypeScript, and the managed code languages C# and Visual Basic (.NET) (VB.NET).

Swift is a high-level general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

References

  1. QuinnRadich. "Windows Data Types (BaseTsd.h) - Win32 apps". docs.microsoft.com. Retrieved 2022-07-10.
  2. "[MS-ERREF]: HRESULT". docs.microsoft.com. Retrieved 2022-07-10.
  3. "[MS-ERREF]: Win32 Error Codes". docs.microsoft.com. Retrieved 2022-07-10.
  4. stevewhims. "Structure of COM Error Codes - Win32 apps". docs.microsoft.com. Retrieved 2022-07-11.
  5. stevewhims. "Using Macros for Error Handling - Win32 apps". docs.microsoft.com. Retrieved 2022-07-10.
  6. Chen, Raymond (2018-01-17). "Why does HRESULT begin with H when it's not a handle to anything?". The Old New Thing. Retrieved 2022-07-11.