/*
A single file header-only live reload solution for C, written in C++:
NOTE: The only file that matters in this repository is cr.h
.
This file contains the documentation in markdown, the license, the implementation and the public api. All other files in this repository are supporting files and can be safely ignored.
You can download and install cr using the vcpkg dependency manager:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install cr
The cr port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.
A (thin) host application executable will make use of cr
to manage
live-reloading of the real application in the form of dynamic loadable binary, a host would be something like:
#define CR_HOST // required in the host only and before including cr.h
#include "../cr.h"
int main(int argc, char *argv[]) {
// the host application should initalize a plugin with a context, a plugin
cr_plugin ctx;
// the full path to the live-reloadable application
cr_plugin_open(ctx, "c:/path/to/build/game.dll");
// call the update function at any frequency matters to you, this will give
// the real application a chance to run
while (!cr_plugin_update(ctx)) {
// do anything you need to do on host side (ie. windowing and input stuff?)
}
// at the end do not forget to cleanup the plugin context
cr_plugin_close(ctx);
return 0;
}
While the guest (real application), would be like:
CR_EXPORT int cr_main(struct cr_plugin *ctx, enum cr_op operation) {
assert(ctx);
switch (operation) {
case CR_LOAD: return on_load(...); // loading back from a reload
case CR_UNLOAD: return on_unload(...); // preparing to a new reload
case CR_CLOSE: ...; // the plugin will close and not reload anymore
}
// CR_STEP
return on_update(...);
}
CR_INITIAL_FAILURE
. If the initial plugin crashes, the host must determine the next path, and we will not reload
the broken plugin.cr_plugin_load
in favor to cr_plugin_open
for consistency with cr_plugin_close
. See issue #49.CR_BAD_IMAGE
in case the binary file is stil not ready even if its timestamp changed. This could happen if generating the file (compiler or copying) was slow.CR_BAD_IMAGE
). Now the version is decremented one time in the crash handler and then another time during the rollback and then be bumped again. A rollback due an incomplete image will not incorrectly rollback two versions, it will continue at the same version retrying the load until the image is valid (copy or compiler finished writing to it). This may impact current uses of cr
if the version
info is used during CR_UNLOAD
as it will now be a different value.Two simple samples can be found in the samples
directory.
The first is one is a simple console application that demonstrate some basic static states working between instances and basic crash handling tests. Print to output is used to show what is happening.
The second one demonstrates how to live-reload an opengl application using Dear ImGui. Some state lives in the host side while most of the code is in the guest side.
The samples and tests uses the fips build system. It requires Python and CMake.
$ ./fips build # will generate and build all artifacts
$ ./fips run crTest # To run tests
$ ./fips run imgui_host # To run imgui sample
# open a new console, then modify imgui_guest.cpp
$ ./fips make imgui_guest # to build and force imgui sample live reload
int (*cr_main)(struct cr_plugin *ctx, enum cr_op operation)
This is the function pointer to the dynamic loadable binary entry point function.
Arguments
ctx
pointer to a context that will be passed from host
to the guest
containing valuable information about the current loaded version, failure reason and user data. For more info see cr_plugin
.operation
which operation is being executed, see cr_op
.Return
CR_USER
. 0 or a positive value that will be passed to the
host
process.bool cr_plugin_open(cr_plugin &ctx, const char *fullpath)
Loads and initialize the plugin.
Arguments
ctx
a context that will manage the plugin internal data and user data.fullpath
full path with filename to the loadable binary for the plugin or
NULL
.Return
true
in case of success, false
otherwise.void cr_set_temporary_path(cr_plugin& ctx, const std::string &path)
Sets temporary path to which temporary copies of plugin will be placed. Should be called
immediately after cr_plugin_open()
. If temporary
path is not set, temporary copies of
the file will be copied to the same directory where the original file is located.
Arguments
ctx
a context that will manage the plugin internal data and user data.path
a full path to an existing directory which will be used for storing temporary plugin copies.int cr_plugin_update(cr_plugin &ctx, bool reloadCheck = true)
This function will call the plugin cr_main
function. It should be called as
frequently as the core logic/application needs.
Arguments
ctx
the current plugin context data.reloadCheck
optional: do a disk check (stat()) to see if the dynamic library needs a reload.Return
cr_main
.void cr_plugin_close(cr_plugin &ctx)
Cleanup internal states once the plugin is not required anymore.
Arguments
ctx
the current plugin context data.cr_op
Enum indicating the kind of step that is being executed by the host
:
CR_LOAD
A load caused by reload is being executed, can be used to restore any
saved internal state.CR_STEP
An application update, this is the normal and most frequent operation;CR_UNLOAD
An unload for reloading the plugin will be executed, giving the
application one chance to store any required data;CR_CLOSE
Used when closing the plugin, This works like CR_UNLOAD
but no CR_LOAD
should be expected afterwards;cr_plugin
The plugin instance context struct.
p
opaque pointer for internal cr data;userdata
may be used by the user to pass information between reloads;version
incremetal number for each succeded reload, starting at 1 for the
first load. The version will change during a crash handling process;failure
used by the crash protection system, will hold the last failure error
code that caused a rollback. See cr_failure
for more info on possible values;cr_failure
If a crash in the loadable binary happens, the crash handler will indicate the reason of the crash with one of these:
CR_NONE
No error;CR_SEGFAULT
Segmentation fault. SIGSEGV
on Linux/OSX or
EXCEPTION_ACCESS_VIOLATION
on Windows;CR_ILLEGAL
In case of illegal instruction. SIGILL
on Linux/OSX or
EXCEPTION_ILLEGAL_INSTRUCTION
on Windows;CR_ABORT
Abort, SIGBRT
on Linux/OSX, not used on Windows;CR_MISALIGN
Bus error, SIGBUS
on Linux/OSX or EXCEPTION_DATATYPE_MISALIGNMENT
on Windows;CR_BOUNDS
Is EXCEPTION_ARRAY_BOUNDS_EXCEEDED
, Windows only;CR_STACKOVERFLOW
Is EXCEPTION_STACK_OVERFLOW
, Windows only;CR_STATE_INVALIDATED
Static CR_STATE
management safety failure;CR_BAD_IMAGE
The plugin is not a valid image (i.e. the compiler may still
writing it);CR_OTHER
Other signal, Linux only;CR_USER
User error (for negative values returned from cr_main
);CR_HOST
defineThis define should be used before including the cr.h
in the host
, if CR_HOST
is not defined, cr.h
will work as a public API header file to be used in the
guest
implementation.
Optionally CR_HOST
may also be defined to one of the following values as a way
to configure the safety
operation mode for automatic static state management
(CR_STATE
):
CR_SAFEST
Will validate address and size of the state data sections during
reloads, if anything changes the load will rollback;CR_SAFE
Will validate only the size of the state section, this mean that the
address of the statics may change (and it is best to avoid holding any pointer
to static stuff);CR_UNSAFE
Will validate nothing but that the size of section fits, may not
be necessarelly exact (growing is acceptable but shrinking isn't), this is the
default behavior;CR_DISABLE
Completely disable automatic static state management;CR_STATE
macroUsed to tag a global or local static variable to be saved and restored during a reload.
Usage
static bool CR_STATE bInitialized = false;
You can define these macros before including cr.h in host (CR_HOST) to customize cr.h memory allocations and other behaviours:
CR_MAIN_FUNC
: changes 'cr_main' symbol to user-defined function name. default: #define CR_MAIN_FUNC "cr_main"CR_ASSERT
: override assert. default: #define CA_ASSERT(e) assert(e)CR_REALLOC
: override libc's realloc. default: #define CR_REALLOC(ptr, size) ::realloc(ptr, size)CR_MALLOC
: override libc's malloc. default: #define CR_MALLOC(size) ::malloc(size)CR_FREE
: override libc's free. default: #define CR_FREE(ptr) ::free(ptr)CR_DEBUG
: outputs debug messages in CR_ERROR, CR_LOG and CR_TRACECR_ERROR
: logs debug messages to stderr. default (CR_DEBUG only): #define CR_ERROR(...) fprintf(stderr, VA_ARGS)CR_LOG
: logs debug messages. default (CR_DEBUG only): #define CR_LOG(...) fprintf(stdout, VA_ARGS)CR_TRACE
: prints function calls. default (CR_DEBUG only): #define CR_TRACE(...) fprintf(stdout, "CR_TRACE: %sn", FUNCTION)A: Read about why I made this here.
A: Make sure both your application host and your dll are using the dynamic run-time (/MD or /MDd) as any data allocated in the heap must be freed with the same allocator instance, by sharing the run-time between guest and host you will guarantee the same allocator is being used.
A: Yes. This should work without issues on Windows. On Linux and OSX there may be issues with crash handling
If you had to load the dll before cr
for any reason, Visual Studio may still hold a lock to the PDB. You may be having this issue and the solution is here.
First, be sure that your build system is not interfering by somewhat still linking to your shared library. There are so many things that can go wrong and you need to be sure only cr
will deal with your shared library. On linux, for more info on how to find what is happening, check this issue.
cr
is C
reloader and dealing with C it assume simple things will mostly work.
The problem is how the linker will decide do rearrange things accordingly the amount of changes you do in the code. For incremental and localized changes I never had any issues, in general I hardly had any issues at all by writing normal C code. Now, when things start to become more complex and bordering C++, it becomes riskier. If you need do complex things, I suggest checking RCCPP and reading this PDF and my original blog post about cr
here.
With all these information you'll be able to decide which is better to your use case.
cr
SponsorsFor sponsoring the port of cr
to the MacOSX.
Danny Grein
Rokas Kupstys
Noah Rinehart
Niklas Lundberg
Sepehr Taghdisian
Robert Gabriel Jakabosky
@pixelherodev
Alexander
We welcome ALL contributions, there is no minor things to contribute with, even one letter typo fixes are welcome.
The only things we require is to test thoroughly, maintain code style and keeping documentation up-to-date.
Also, accepting and agreeing to release any contribution under the same license.
The MIT License (MIT)
Copyright (c) 2017 Danny Angelo Carminati Grein
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __CR_H__
#define __CR_H__
//
// Global OS specific defines/customizations
//
#if defined(_WIN32)
#define CR_WINDOWS
#define CR_PLUGIN(name) "" name ".dll"
#elif defined(__linux__)
#define CR_LINUX
#define CR_PLUGIN(name) "lib" name ".so"
#elif defined(__APPLE__)
#define CR_OSX
#define CR_PLUGIN(name) "lib" name ".dylib"
#else
#error "Unknown/unsupported platform, please open an issue if you think this
platform should be supported."
#endif // CR_WINDOWS || CR_LINUX || CR_OSX
//
// Global compiler specific defines/customizations
//
#if defined(_MSC_VER)
#if defined(__cplusplus)
#define CR_EXPORT extern "C" __declspec(dllexport)
#define CR_IMPORT extern "C" __declspec(dllimport)
#else
#define CR_EXPORT __declspec(dllexport)
#define CR_IMPORT __declspec(dllimport)
#endif
#endif // defined(_MSC_VER)
#if defined(__GNUC__) // clang & gcc
#if defined(__cplusplus)
#define CR_EXPORT extern "C" __attribute__((visibility("default")))
#else
#define CR_EXPORT __attribute__((visibility("default")))
#endif
#define CR_IMPORT
#endif // defined(__GNUC__)
#if defined(__MINGW32__)
#undef CR_EXPORT
#if defined(__cplusplus)
#define CR_EXPORT extern "C" __declspec(dllexport)
#else
#define CR_EXPORT __declspec(dllexport)
#endif
#endif
// cr_mode defines how much we validate global state transfer between
// instances. The default is CR_UNSAFE, you can choose another mode by
// defining CR_HOST, ie.: #define CR_HOST CR_SAFEST
enum cr_mode {
CR_SAFEST = 0, // validate address and size of the state section, if
// anything changes the load will rollback
CR_SAFE = 1, // validate only the size of the state section, this means
// that address is assumed to be safe if avoided keeping
// references to global/static states
CR_UNSAFE = 2, // don't validate anything but that the size of the section
// fits, may not be identical though
CR_DISABLE = 3 // completely disable the auto state transfer
};
// cr_op is passed into the guest process to indicate the current operation
// happening so the process can manage its internal data if it needs.
enum cr_op {
CR_LOAD = 0,
CR_STEP = 1,
CR_UNLOAD = 2,
CR_CLOSE = 3,
};
enum cr_failure {
CR_NONE, // No error
CR_SEGFAULT, // SIGSEGV / EXCEPTION_ACCESS_VIOLATION
CR_ILLEGAL, // illegal instruction (SIGILL) / EXCEPTION_ILLEGAL_INSTRUCTION
CR_ABORT, // abort (SIGBRT)
CR_MISALIGN, // bus error (SIGBUS) / EXCEPTION_DATATYPE_MISALIGNMENT
CR_BOUNDS, // EXCEPTION_ARRAY_BOUNDS_EXCEEDED
CR_STACKOVERFLOW, // EXCEPTION_STACK_OVERFLOW
CR_STATE_INVALIDATED, // one or more global data section changed and does
// not safely match basically a failure of
// cr_plugin_validate_sections
CR_BAD_IMAGE, // The binary is not valid - compiler is still writing it
CR_INITIAL_FAILURE, // Plugin version 1 crashed, cannot rollback
CR_OTHER, // Unknown or other signal,
CR_USER = 0x100,
};
struct cr_plugin;
typedef int (*cr_plugin_main_func)(struct cr_plugin *ctx, enum cr_op operation);
// public interface for the plugin context, this has some user facing
// variables that may be used to manage reload feedback.
// - userdata may be used by the user to pass information between reloads
// - version is the reload counter (after loading the first instance it will
// be 1, not 0)
// - failure is the (platform specific) last error code for any crash that may
// happen to cause a rollback reload used by the crash protection system
struct cr_plugin {
void *p;
void *userdata;
unsigned int version;
enum cr_failure failure;
unsigned int next_version;
unsigned int last_working_version;
};
#ifndef CR_HOST
// Guest specific compiler defines/customizations
#if defined(_MSC_VER)
#pragma section(".state", read, write)
#define CR_STATE __declspec(allocate(".state"))
#endif // defined(_MSC_VER)
#if defined(CR_OSX)
#define CR_STATE __attribute__((used, section("__DATA,__state")))
#else
#if defined(__GNUC__) // clang & gcc
#define CR_STATE __attribute__((section(".state")))
#endif // defined(__GNUC__)
#endif
#else // #ifndef CR_HOST
// Overridable macros
#ifndef CR_LOG
# ifdef CR_DEBUG
# include
# define CR_LOG(...) fprintf(stdout, __VA_ARGS__)
# else
# define CR_LOG(...)
# endif
#endif
#ifndef CR_ERROR
# ifdef CR_DEBUG
# include
# define CR_ERROR(...) fprintf(stderr, __VA_ARGS__)
# else
# define CR_ERROR(...)
# endif
#endif
#ifndef CR_TRACE
# ifdef CR_DEBUG
# include
# define CR_TRACE fprintf(stdout, "CR_TRACE: %sn", __FUNCTION__);
# else
# define CR_TRACE
# endif
#endif
#ifndef CR_MAIN_FUNC
# define CR_MAIN_FUNC "cr_main"
#endif
#ifndef CR_ASSERT
# include
# define CR_ASSERT(e) assert(e)
#endif
#ifndef CR_REALLOC
# include
# define CR_REALLOC(ptr, size) ::realloc(ptr, size)
#endif
#ifndef CR_FREE
# include
# define CR_FREE(ptr) ::free(ptr)
#endif
#ifndef CR_MALLOC
# include
# define CR_MALLOC(size) ::malloc(size)
#endif
#if defined(_MSC_VER)
// we should probably push and pop this
# pragma warning(disable:4003) // not enough actual parameters for macro 'identifier'
#endif
#define CR_DO_EXPAND(x) x##1337
#define CR_EXPAND(x) CR_DO_EXPAND(x)
#if CR_EXPAND(CR_HOST) == 1337
#define CR_OP_MODE CR_UNSAFE
#else
#define CR_OP_MODE CR_HOST
#endif
#include
#include // duration for sleep
#include // memcpy
#include
#include // this_thread::sleep_for
#if defined(CR_WINDOWS)
#define CR_PATH_SEPARATOR '\'
#define CR_PATH_SEPARATOR_INVALID '/'
#else
#define CR_PATH_SEPARATOR '/'
#define CR_PATH_SEPARATOR_INVALID '\'
#endif
static void cr_split_path(std::string path, std::string &parent_dir,
std::string &base_name, std::string &ext) {
std::replace(path.begin(), path.end(), CR_PATH_SEPARATOR_INVALID,
CR_PATH_SEPARATOR);
auto sep_pos = path.rfind(CR_PATH_SEPARATOR);
auto dot_pos = path.rfind('.');
if (sep_pos == std::string::npos) {
parent_dir = "";
if (dot_pos == std::string::npos) {
ext = "";
base_name = path;
} else {
ext = path.substr(dot_pos);
base_name = path.substr(0, dot_pos);
}
} else {
parent_dir = path.substr(0, sep_pos + 1);
if (dot_pos == std::string::npos || sep_pos > dot_pos) {
ext = "";
base_name = path.substr(sep_pos + 1);
} else {
ext = path.substr(dot_pos);
base_name = path.substr(sep_pos + 1, dot_pos - sep_pos - 1);
}
}
}
static std::string cr_version_path(const std::string &basepath,
unsigned version,
const std::string &temppath) {
std::string folder, fname, ext;
cr_split_path(basepath, folder, fname, ext);
std::string ver = std::to_string(version);
#if defined(_MSC_VER)
// When patching PDB file path in library file we will drop path and leave only file name.
// Length of path is extra space for version number. Trim file name only if version number
// length exceeds pdb folder path length. This is not relevant on other platforms.
if (ver.size() > folder.size()) {
fname = fname.substr(0, fname.size() - (ver.size() - folder.size() - 1));
}
#endif
if (!temppath.empty()) {
folder = temppath;
}
return folder + fname + ver + ext;
}
namespace cr_plugin_section_type {
enum e { state, bss, count };
}
namespace cr_plugin_section_version {
enum e { backup, current, count };
}
struct cr_plugin_section {
cr_plugin_section_type::e type = {};
intptr_t base = 0;
char *ptr = 0;
int64_t size = 0;
void *data = nullptr;
};
struct cr_plugin_segment {
char *ptr = 0;
int64_t size = 0;
};
// keep track of some internal state about the plugin, should not be messed
// with by user
struct cr_internal {
std::string fullname = {};
std::string temppath = {};
time_t timestamp = {};
void *handle = nullptr;
cr_plugin_main_func main = nullptr;
cr_plugin_segment seg = {};
cr_plugin_section data[cr_plugin_section_type::count]
[cr_plugin_section_version::count] = {};
cr_mode mode = CR_SAFEST;
};
static bool cr_plugin_section_validate(cr_plugin &ctx,
cr_plugin_section_type::e type,
intptr_t vaddr, intptr_t ptr,
int64_t size);
static void cr_plugin_sections_reload(cr_plugin &ctx,
cr_plugin_section_version::e version);
static void cr_plugin_sections_store(cr_plugin &ctx);
static void cr_plugin_sections_backup(cr_plugin &ctx);
static void cr_plugin_reload(cr_plugin &ctx);
static int cr_plugin_unload(cr_plugin &ctx, bool rollback, bool close);
static bool cr_plugin_changed(cr_plugin &ctx);
static bool cr_plugin_rollback(cr_plugin &ctx);
static int cr_plugin_main(cr_plugin &ctx, cr_op operation);
void cr_set_temporary_path(cr_plugin &ctx, const std::string &path) {
auto pimpl = (cr_internal *)ctx.p;
pimpl->temppath = path;
}
#if defined(CR_WINDOWS)
// clang-format off
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include
#include
// clang-format on
#if defined(_MSC_VER)
#pragma comment(lib, "dbghelp.lib")
#endif
using so_handle = HMODULE;
#ifdef UNICODE
# define CR_WINDOWS_ConvertPath(_newpath, _path) std::wstring _newpath(cr_utf8_to_wstring(_path))
static std::wstring cr_utf8_to_wstring(const std::string &str) {
int wlen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0);
wchar_t wpath_small[MAX_PATH];
std::unique_ptr<wchar_t[]> wpath_big;
wchar_t *wpath = wpath_small;
if (wlen > _countof(wpath_small)) {
wpath_big = std::unique_ptr<wchar_t[]>(new wchar_t[wlen]);
wpath = wpath_big.get();
}
if (MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wpath, wlen) != wlen) {
return L"";
}
return wpath;
}
#else
# define CR_WINDOWS_ConvertPath(_newpath, _path) const std::string &_newpath = _path
#endif // UNICODE
static time_t cr_last_write_time(const std::string &path) {
CR_WINDOWS_ConvertPath(_path, path);
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesEx(_path.c_str(), GetFileExInfoStandard, &fad)) {
return -1;
}
if (fad.nFileSizeHigh == 0 && fad.nFileSizeLow == 0) {
return -1;
}
LARGE_INTEGER time;
time.HighPart = fad.ftLastWriteTime.dwHighDateTime;
time.LowPart = fad.ftLastWriteTime.dwLowDateTime;
return static_cast<time_t>(time.QuadPart / 10000000 - 11644473600LL);
}
static bool cr_exists(const std::string &path) {
CR_WINDOWS_ConvertPath(_path, path);
return GetFileAttributes(_path.c_str()) != INVALID_FILE_ATTRIBUTES;
}
static bool cr_copy(const std::string &from, const std::string &to) {
CR_WINDOWS_ConvertPath(_from, from);
CR_WINDOWS_ConvertPath(_to, to);
return CopyFile(_from.c_str(), _to.c_str(), FALSE) ? true : false;
}
static void cr_del(const std::string& path) {
CR_WINDOWS_ConvertPath(_path, path);
DeleteFile(_path.c_str());
}
// If using Microsoft Visual C/C++ compiler we need to do some workaround the
// fact that the compiled binary has a fullpath to the PDB hardcoded inside
// it. This causes a lot of headaches when trying compile while debugging as
// the referenced PDB will be locked by the debugger.
// To solve this problem, we patch the binary to rename the PDB to something
// we know will be unique to our in-flight instance, so when debugging it will
// lock this unique PDB and the compiler will be able to overwrite the
// original one.
#if defined(_MSC_VER)
#include
#include
#include
#include
static std::string cr_replace_extension(const std::string &filepath,
const std::string &ext) {
std::string folder, filename, old_ext;
cr_split_path(filepath, folder, filename, old_ext);
return folder + filename + ext;
}
template <class T>
static T struct_cast(void *ptr, LONG offset = 0) {
return reinterpret_cast<T>(reinterpret_cast<intptr_t>(ptr) + offset);
}
// RSDS Debug Information for PDB files
using DebugInfoSignature = DWORD;
#define CR_RSDS_SIGNATURE 'SDSR'
struct cr_rsds_hdr {
DebugInfoSignature signature;
GUID guid;
long version;
char filename[1];
};
static bool cr_pe_debugdir_rva(PIMAGE_OPTIONAL_HEADER optionalHeader,
DWORD &debugDirRva, DWORD &debugDirSize) {
if (optionalHeader->Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
auto optionalHeader64 =
struct_cast<PIMAGE_OPTIONAL_HEADER64>(optionalHeader);
debugDirRva =
optionalHeader64->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG]
.VirtualAddress;
debugDirSize =
optionalHeader64->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
} else {
auto optionalHeader32 =
struct_cast<PIMAGE_OPTIONAL_HEADER32>(optionalHeader);
debugDirRva =
optionalHeader32->DataDirectory[IMAGE_DIRECTO