In Part One of this series, I explored the Windows API and built my first process spawner using C++. The objective was simple: create a program that is capable of launching Notepad using the CreateProcessW() function.
After spending some time understanding the function's ten parameters, experimenting with C++ syntax, and overcoming several compiler errors, I eventually had a working executable that successfully launched Notepad.
However, there was something missing from my original implementation.
What happens when CreateProcessW() fails?
My original program didn't check whether Windows had successfully created the process. It simple called CreateProcessW() and continued executing.
If Notepad launched, great. But if something went wrong, the program wouldn't tell me what happened or why.
This raised a few questions:
- What does CreateProcessW() return when it fails?
- How can I determine why Windows couldn't create the process?
- Can I translate Windows error codes into something more meaningful?
In this part, I'll build upon the original process spawner by introducing error handling using three Windows API functions CreateProcessW(), GetLastErrr(), and FormatMessageW().
I'll also deliberately break the program to see how Windows responds when an executable cannot be found.
The goal isn't to make the program more reliable. It's to develop a better understanding of how Windows applications interact with the operating system, particularly when operations don't go according to plan.
The Problem With My Original Code
In Part One, I used the CreateProcessW() function to launch Notepad. Although the program worked as intended, there was one important oversight.
As shown below, I was using the CreateProcessW() without checking its return value.

This meant that while the program could successfully launch Notepad, it had no way of telling me whether the operation failed.
To fix this, I needed to understand what CreateProcessW() actually returns and how I could use that information to determine whether Windows had successfully created the process.

This function return a Bool, which is a nonzero value that indicates success, whilst zero indicates failure.
Capturing the Return Value of CreateProcessW()
The first thing I needed to understand was how CreateProcessW() communicates whether an operation has succeeded or failed.
Looking through Microsoft's documentation, I found out that CreateProcessW() returns a BOOL value.
Unlike the standard C++ BOOl type, BOOL is a Windows-defined type. A return value of zero (FALSE) indicates that the function failed, whereas a nonzero value indicates success.
In my original version, I was calling CreateProcessW() without doing anything with its return value.
To address this, I introduced a variable called success:
BOOL success = CreateProcessW(
NULL,
w,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi
);It's a relatively small change, but it makes an important difference.
Previously, the program simply requested that Windows create a process. Now, the result of that request is stored in the success variable, allowing me to check whether the operation completed successfully.
The process can be visualised as follows:
CreateProcessW() → Return value → success variable
However, simply storing the return value doesn't automatically handle failures. The program still needs to examine the value and decide what to do when something goes wrong.
This brings me to the next step, introducing a conditional statement to detect when process creation fails.
Checking for Failure Using if (!success)
Now that I had captured the return value of CreateProcessW() in a variable called success, the next step was to make the program respond when process creation failed.
To achieve this, I introduced an if statement.
In C++, an if statement allows a program to execute a particular block of code only when a specified condition evaluates to true.
For my process spawner, I wanted the program to display an error message whenever CreateProcessW() failed.
I added the following code immediately after the function call:
if (!success)
{
std::cout << "Failed to create process\n";
}The important part here is the condition:
!successThe exclamation mark (!) is the logical NOT operator in C++. It reverses the truth value of an expression.
Since CreateProcessW() returns zero when it fails, !success evaluates to true when process creation is unsuccessful.
This means that if Windows successfully launches Notepad, the condition is false and the program skips the error-handling block.
However, if Windows fails to create the process, the condition becomes true and the program executes the code inside the curly braces.
This was my first step towards making the process spawner more reliable. Rather than silently continuing after a failed operation, the program could now recognise that something had gone wrong and inform the user.
There was still one problem, though.
While the program could now tell me that process creation had failed, it couldn't explain why.
Was the executable missing? Was access denied? Had I supplied an invalid parameter?
To answer those questions, I needed another Windows API function: GetLastError().
Understanding Windows Error Codes with GetLastError()
Now that my program could detect when CreateProcessW() failed, I wanted to understand why the failure had occurred.
Fortunately, Windows provides a function specifically designed to retrieve error information from the calling thread: GetLastError().
According to Microsoft's documentation, the function has the following signature:
DWORD GetLastError();Unlike CreateProcessW(), which requires ten parameters, GetLastError() doesn't require any.
The function returns a DWORD, a Windows-defined 32-bit unsigned integer type, containing the calling thread's last-error code.
One important detail is that GetLastError() doesn't necessarily return an error from the most recently executed function. Instead, it retrieves the last-error value maintained by Windows for the calling thread. For this reason, it should be called immediately after an API failure when the documentation indicates that additional error information is available.
To incorporate this into my program, I added the following line inside the existing if (!success) block:
DWORD error = GetLastError();This stores the Windows error code in a variable called error, which I could then display using std::cout.
if (!success)
{
DWORD error = GetLastError();
std::cout << "Failed to create process. Windows error code: "
<< error << "\n";
}Testing the Error Handling
To test whether my changes worked, I deliberately modified the executable name in my original program.
Instead of:
wchar_t w[] = L"notepad.exe";I changed it to:
wchar_t w[] = L"doesnotexist.exe";After recompiling and executing the program, Windows was unable to locate the specified executable.
This time, however, my program detected the failure and displayed the following output:
Notepad Spawner Starting...
Failed to create process. Windows error code: 2The error code returned was 2, which corresponds to the Windows system error ERROR_FILE_NOT_FOUND.
In other words, Windows was telling me that it couldn't find the executable I had requested.
This demonstrated that the error-handling logic was working as intended. Rather than silently failing, my program could now retrieve and display the reason for the unsuccessful API operation.
However, there was still room for improvement.
Although error code 2 was useful, it wasn't particularly descriptive without knowing what that number represented. A user would otherwise need to look up the error code manually to understand what had gone wrong.
I wanted the program to display the actual Windows error message instead.
This led me to another Windows API function: FormatMessageW().
Translating Windows Error Codes with FormatMessageW()
At this point, my program could successfully detect when CreateProcessW() failed and retrieve the corresponding Windows error code using GetLastError().
However, the output was still limited to a numerical value.
For example:
Failed to create process. Windows error code: 2Although error code 2 corresponds to ERROR_FILE_NOT_FOUND, I wanted the program to provide a more meaningful explanation without requiring the user to look up the error manually.
This is where FormatMessageW() comes in.
What is FormatMessageW()?
FormatMessageW() is a Windows API function that can retrieve and format message strings, including descriptions associated with Windows system error codes.
The W suffix indicates that the function uses Unicode wide-character strings.
By supplying the error code returned by GetLastError(), I could ask Windows to retrieve its corresponding human-readable description.
The function takes seven parameters, which initially seemed intimidating. However, as with CreateProcessW() in Part 1, breaking them down individually made the function easier to understand.
Understanding the Parameters
| Parameter | My Value | Purpose |
|---|---|---|
dwFlags | FORMAT_MESSAGE_FROM_SYSTEM | Retrieve the message from Windows' system message table |
lpSource | NULL | No custom message source required |
dwMessageId | error | The error code returned by GetLastError() |
dwLanguageId | 0 | Allow Windows to select an appropriate message language |
lpBuffer | message | Buffer where Windows writes the resulting text |
nSize | 256 | Maximum buffer size in wide characters |
Arguments | NULL | No additional formatting arguments supplied |
For this example, I also needed to ensure that no formatting inserts were required. I therefore used FORMAT_MESSAGE_IGNORE_INSERTS alongside FORMAT_MESSAGE_FROM_SYSTEM.
Creating a Buffer for the Error Message
Before calling FormatMessageW(), I needed somewhere to store the message returned by Windows.
I created a wide-character array containing 256 elements:
wchar_t message[256];This allocates enough space for up to 256 wide characters, including the terminating null character.
The buffer is passed to FormatMessageW(), allowing Windows to write the resulting message directly into it.
Calling FormatMessageW()
With the buffer created and the parameters identified, I added the following code after retrieving the error:
wchar_t message[256]{};
DWORD charactersWritten = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
0,
message,
256,
NULL
);The | operator combines the two formatting flags.
The function returns the number of characters written to the buffer, excluding the terminating null character. If it returns zero, the formatting operation itself has failed.
Displaying the Error Message
The final step was to display the contents of the message buffer.
Previously, I had been using std::cout to print text to the console. However, because FormatMessageW() writes wide characters, I used std::wcout instead.
if (charactersWritten != 0)
{
std::wcout << message;
}One mistake I initially made was writing:
std::wcout << L"message";This printed the literal word message rather than the contents of my variable.
Removing the quotation marks corrected the problem:
std::wcout << message;It was a small mistake, but it reinforced an important distinction between string literals and variables in C++.
The Final Result
After recompiling and running the program with the deliberately invalid executable name, the output now looked like this:
Notepad Spawner Starting...
Failed to create process. Windows error code: 2
The system cannot find the file specified.This was exactly what I wanted to achieve.
The program could now detect a failed Windows API operation, retrieve its error code, and display a meaningful description of the problem.
More importantly, I had gained a better understanding of how Windows applications can handle errors rather than simply assuming that every API call will work.
Conclusion: Making Sense of Windows API Failures
In Part 1, I successfully created a basic Windows process spawner using C++ and CreateProcessW(). However, the original implementation had one significant limitation: it assumed that process creation would always succeed.
Throughout Part 2, I've improved the program by introducing error handling and exploring how Windows communicates failures to applications.
I've learned how to:
- Capture the return value of
CreateProcessW()using aBOOLvariable. - Use conditional statements to detect unsuccessful operations.
- Retrieve Windows error codes using
GetLastError(). - Translate numerical error codes into human-readable messages using
FormatMessageW(). - Deliberately trigger failures to test whether my error-handling logic works as expected.
Although these changes might seem relatively minor, they've helped me develop a better understanding of how Windows applications interact with the operating system.
Why Does This Matter for Malware Analysis?
One of my main reasons for learning Windows programming is to improve my ability to analyse malicious software and understand the Windows API calls I encounter during reverse engineering.
When examining an unfamiliar executable in tools such as Ghidra or x64dbg, recognising functions like CreateProcessW(), GetLastError(), and FormatMessageW() can provide useful context about what the program is attempting to accomplish.
For example, a program might attempt to create another process, check whether the operation succeeded, and execute a different code path depending on the result.
Understanding these interactions makes it easier to follow a program's execution flow and investigate why it behaves differently under certain conditions.
Of course, these APIs are not inherently malicious. They're used by legitimate Windows applications every day. Their relevance during malware analysis comes from understanding how they're being used and what the program does next.
What's Next? Understanding Processes, Threads and Handles
Although my process spawner now includes basic error handling, there's still an important part of the origina