forked from fungos/cr
-
Notifications
You must be signed in to change notification settings - Fork 3
/
cr.h
1424 lines (1206 loc) · 46.1 KB
/
cr.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
# cr.h
A single file header-only live reload solution for C, written in C++:
- simple public API, 3 functions only to use (and only one to export);
- works and tested on Linux and Windows;
- automatic crash protection;
- automatic static state transfer;
- based on dynamic reloadable binary (.so/.dll);
- MIT licensed;
- requires C++17 (filesystem support);
### Build Status:
|Platform|Build Status|
|--------|------|
|Linux|[![Build Status](https://travis-ci.org/fungos/cr.svg?branch=master)](https://travis-ci.org/fungos/cr)|
|Windows|[![Build status](https://ci.appveyor.com/api/projects/status/jf0dq97w9b7b5ihi?svg=true)](https://ci.appveyor.com/project/fungos/cr)|
Note that the only file that matters 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.
### Example
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:
```c
#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_load(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:
```c
CR_EXPORT int cr_main(struct cr_plugin *ctx, enum cr_op operation) {
assert(ctx);
switch (operation) {
case CR_LOAD: return on_load(...);
case CR_UNLOAD: return on_unload(...);
}
// CR_STEP
return on_update(...);
}
```
### Samples
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](https://github.com/ocornut/imgui). Some state lives in the host
side while most of the code is in the guest side.
![imgui sample](https://i.imgur.com/Nq6s0GP.gif)
#### Running Samples and Tests
The samples and tests uses the [fips build system](https://github.com/floooh/fips). 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
```
### Documentation
#### `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
- A negative value indicating an error, forcing a rollback to happen and failure
being set to `CR_USER`. 0 or a positive value that will be passed to the
`host` process.
#### `bool cr_plugin_load(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.
#### `int cr_plugin_update(cr_plugin &ctx)`
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.
Return
- -1 if a failure happened during an update;
- -2 if a failure happened during a load or unload;
- anything else is returned directly from the plugin `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 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 will be executed, giving the application one chance to
store any required data.
- `CR_CLOSE` Like `CR_UNLOAD` but no `CR_LOAD` should be expected;
#### `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;
- `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 or
`EXCEPTION_ACCESS_VIOLATION` on Windows;
- `CR_ILLEGAL` In case of illegal instruction. `SIGILL` on Linux or
`EXCEPTION_ILLEGAL_INSTRUCTION` on Windows;
- `CR_ABORT` Abort, `SIGBRT` on Linux, not used on Windows;
- `CR_MISALIGN` Bus error, `SIGBUS` on Linux 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_OTHER` Other signal, Linux only;
- `CR_USER` User error (for negative values returned from `cr_main`);
#### `CR_HOST` define
This 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` macro
Used to tag a global or local static variable to be saved and restored during a reload.
Usage
`static bool CR_STATE bInitialized = false;`
### FAQ / Troubleshooting
#### Q: Why?
A: Read about why I made this [here](https://fungos.github.io/blog/2017/11/20/cr.h-a-simple-c-hot-reload-header-only-library/).
#### Q: My application asserts/crash when freeing heap data allocated inside the dll, what is happening?
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.
#### Q: Can we load multiples plugins at the same time?
A: Yes. This should work without issues on Windows. On Linux, there may be
issues with signal handling with the crash protection as it does not have the
plugin context to know which one crashed. This should be fixed in a near future.
### 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.
### Source
<details>
<summary>View Source Code</summary>
```c
*/
#ifndef __CR_H__
#define __CR_H__
// 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 sectio changed and does
// not safely match basically a failure of
// cr_plugin_validate_sections
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;
};
#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__)
#ifndef CR_HOST
// Some helpers required in the guest side.
#pragma section(".state", read, write)
#if defined(_MSC_VER)
// GCC: __attribute__((section(".state")))
#define CR_STATE __declspec(allocate(".state"))
#endif // defined(_MSC_VER)
#if defined(__GNUC__) // clang & gcc
#define CR_STATE __attribute__((section(".state")))
#endif // defined(__GNUC__)
#else // #ifndef CR_HOST
#pragma warning(disable:4003) // macro args
#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 <cassert> // assert
#include <chrono> // duration for sleep
#include <experimental/filesystem> // fs::path and utils
#include <system_error> // filesystem errors
#include <thread> // this_thread::sleep_for
namespace fs = std::experimental::filesystem;
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 {
fs::path fullname = {};
fs::file_time_type 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 void 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);
#if defined(_WIN32)
// clang-format off
#include <windows.h>
#include <dbghelp.h>
// clang-format on
#pragma comment(lib, "dbghelp.lib")
#define CR_STR "%ls"
#define CR_INT "%ld"
// 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 <crtdbg.h>
#include <limits.h>
#include <stdio.h>
#include <tchar.h>
using so_handle = HMODULE;
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_DIRECTORY_ENTRY_DEBUG]
.VirtualAddress;
debugDirSize =
optionalHeader32->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
}
if (debugDirRva == 0 && debugDirSize == 0) {
return true;
} else if (debugDirRva == 0 || debugDirSize == 0) {
return false;
}
return true;
}
static bool cr_pe_fileoffset_rva(PIMAGE_NT_HEADERS ntHeaders, DWORD rva,
DWORD &fileOffset) {
bool found = false;
auto *sectionHeader = IMAGE_FIRST_SECTION(ntHeaders);
for (int i = 0; i < ntHeaders->FileHeader.NumberOfSections;
i++, sectionHeader++) {
auto sectionSize = sectionHeader->Misc.VirtualSize;
if ((rva >= sectionHeader->VirtualAddress) &&
(rva < sectionHeader->VirtualAddress + sectionSize)) {
found = true;
break;
}
}
if (!found) {
return false;
}
const int diff = static_cast<int>(sectionHeader->VirtualAddress -
sectionHeader->PointerToRawData);
fileOffset = rva - diff;
return true;
}
static char *cr_pdb_find(LPBYTE imageBase, PIMAGE_DEBUG_DIRECTORY debugDir) {
assert(debugDir && imageBase);
LPBYTE debugInfo = imageBase + debugDir->PointerToRawData;
const auto debugInfoSize = debugDir->SizeOfData;
if (debugInfo == 0 || debugInfoSize == 0) {
return nullptr;
}
if (IsBadReadPtr(debugInfo, debugInfoSize)) {
return nullptr;
}
if (debugInfoSize < sizeof(DebugInfoSignature)) {
return nullptr;
}
if (debugDir->Type == IMAGE_DEBUG_TYPE_CODEVIEW) {
auto signature = *(DWORD *)debugInfo;
if (signature == CR_RSDS_SIGNATURE) {
auto *info = (cr_rsds_hdr *)(debugInfo);
if (IsBadReadPtr(debugInfo, sizeof(cr_rsds_hdr))) {
return nullptr;
}
if (IsBadStringPtrA((const char *)info->filename, UINT_MAX)) {
return nullptr;
}
return info->filename;
}
}
return nullptr;
}
static bool cr_pdb_replace(const fs::path &filename, const fs::path &pdbname,
char *pdbnamebuf, int pdbnamelen) {
assert(pdbnamebuf);
HANDLE fp = nullptr;
HANDLE filemap = nullptr;
LPVOID mem = 0;
bool result = false;
do {
fp = CreateFile(filename.string().c_str(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if ((fp == INVALID_HANDLE_VALUE) || (fp == nullptr)) {
break;
}
filemap = CreateFileMapping(fp, nullptr, PAGE_READWRITE, 0, 0, nullptr);
if (filemap == nullptr) {
break;
}
mem = MapViewOfFile(filemap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (mem == nullptr) {
break;
}
auto dosHeader = struct_cast<PIMAGE_DOS_HEADER>(mem);
if (dosHeader == 0) {
break;
}
if (IsBadReadPtr(dosHeader, sizeof(IMAGE_DOS_HEADER))) {
break;
}
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
break;
}
auto ntHeaders =
struct_cast<PIMAGE_NT_HEADERS>(dosHeader, dosHeader->e_lfanew);
if (ntHeaders == 0) {
break;
}
if (IsBadReadPtr(ntHeaders, sizeof(ntHeaders->Signature))) {
break;
}
if (ntHeaders->Signature != IMAGE_NT_SIGNATURE) {
break;
}
if (IsBadReadPtr(&ntHeaders->FileHeader, sizeof(IMAGE_FILE_HEADER))) {
break;
}
if (IsBadReadPtr(&ntHeaders->OptionalHeader,
ntHeaders->FileHeader.SizeOfOptionalHeader)) {
break;
}
if (ntHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC &&
ntHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
break;
}
auto sectionHeaders = IMAGE_FIRST_SECTION(ntHeaders);
if (IsBadReadPtr(sectionHeaders,
ntHeaders->FileHeader.NumberOfSections *
sizeof(IMAGE_SECTION_HEADER))) {
break;
}
DWORD debugDirRva = 0;
DWORD debugDirSize = 0;
if (!cr_pe_debugdir_rva(&ntHeaders->OptionalHeader, debugDirRva,
debugDirSize)) {
break;
}
if (debugDirRva == 0 || debugDirSize == 0) {
break;
}
DWORD debugDirOffset = 0;
if (!cr_pe_fileoffset_rva(ntHeaders, debugDirRva, debugDirOffset)) {
break;
}
auto debugDir =
struct_cast<PIMAGE_DEBUG_DIRECTORY>(mem, debugDirOffset);
if (debugDir == 0) {
break;
}
if (IsBadReadPtr(debugDir, debugDirSize)) {
break;
}
if (debugDirSize < sizeof(IMAGE_DEBUG_DIRECTORY)) {
break;
}
int numEntries = debugDirSize / sizeof(IMAGE_DEBUG_DIRECTORY);
if (numEntries == 0) {
break;
}
for (int i = 1; i <= numEntries; i++, debugDir++) {
char *pdb = cr_pdb_find((LPBYTE)mem, debugDir);
if (pdb && strlen(pdb) >= strlen(pdbname.string().c_str())) {
auto len = strlen(pdb);
memcpy_s(pdbnamebuf, pdbnamelen, pdb, len);
std::memset(pdb, '\0', len);
memcpy_s(pdb, len, pdbname.string().c_str(),
strlen(pdbname.string().c_str()));
result = true;
}
}
} while (0);
if (mem != nullptr) {
UnmapViewOfFile(mem);
}
if (filemap != nullptr) {
CloseHandle(filemap);
}
if ((fp != nullptr) && (fp != INVALID_HANDLE_VALUE)) {
CloseHandle(fp);
}
return result;
}
bool static cr_pdb_process(const fs::path &filename, const fs::path &pdbname) {
char orig_pdb[MAX_PATH];
memset(orig_pdb, 0, sizeof(orig_pdb));
bool result = cr_pdb_replace(filename, pdbname.filename(), orig_pdb,
sizeof(orig_pdb));
result &=
static_cast<bool>(CopyFile(orig_pdb, pdbname.string().c_str(), 0));
return result;
}
#endif // _MSC_VER
static void cr_pe_section_save(cr_plugin &ctx, cr_plugin_section_type::e type,
int64_t vaddr, int64_t base,
IMAGE_SECTION_HEADER &shdr) {
const auto version = cr_plugin_section_version::current;
auto p = (cr_internal *)ctx.p;
auto data = &p->data[type][version];
const size_t old_size = data->size;
data->base = base;
data->ptr = (char *)vaddr;
data->size = shdr.SizeOfRawData;
data->data = realloc(data->data, shdr.SizeOfRawData);
if (old_size < shdr.SizeOfRawData) {
memset((char *)data->data + old_size, '\0',
shdr.SizeOfRawData - old_size);
}
}
static bool cr_plugin_validate_sections(cr_plugin &ctx, so_handle handle,
const fs::path &imagefile,
bool rollback) {
(void)imagefile;
assert(handle);
auto p = (cr_internal *)ctx.p;
if (p->mode == CR_DISABLE) {
return true;
}
auto ntHeaders = ImageNtHeader(handle);
auto base = ntHeaders->OptionalHeader.ImageBase;
auto sectionHeaders = (IMAGE_SECTION_HEADER *)(ntHeaders + 1);
bool result = true;
for (int i = 0; i < ntHeaders->FileHeader.NumberOfSections; ++i) {
auto sectionHeader = sectionHeaders[i];
const int64_t size = sectionHeader.SizeOfRawData;
if (!strcmp((const char *)sectionHeader.Name, ".state")) {
if (ctx.version || rollback) {
result &= cr_plugin_section_validate(
ctx, cr_plugin_section_type::state,
base + sectionHeader.VirtualAddress, base, size);
}
if (result) {
auto sec = cr_plugin_section_type::state;
cr_pe_section_save(ctx, sec,
base + sectionHeader.VirtualAddress, base,
sectionHeader);
}
} else if (!strcmp((const char *)sectionHeader.Name, ".bss")) {
if (ctx.version || rollback) {
result &= cr_plugin_section_validate(
ctx, cr_plugin_section_type::bss,
base + sectionHeader.VirtualAddress, base, size);
}
if (result) {
auto sec = cr_plugin_section_type::bss;
cr_pe_section_save(ctx, sec,
base + sectionHeader.VirtualAddress, base,
sectionHeader);
}
}
}
return result;
}
static void cr_so_unload(cr_plugin &ctx) {
auto p = (cr_internal *)ctx.p;
assert(p->handle);
FreeLibrary((HMODULE)p->handle);
}
static so_handle cr_so_load(cr_plugin &ctx, const fs::path &filename) {
auto new_dll = LoadLibrary(filename.string().c_str());
if (!new_dll) {
fprintf(stderr, "Couldn't load plugin: %d\n", GetLastError());
}
return new_dll;
}
static cr_plugin_main_func cr_so_symbol(so_handle handle) {
assert(handle);
auto new_main = (cr_plugin_main_func)GetProcAddress(handle, "cr_main");
if (!new_main) {
fprintf(stderr, "Couldn't find plugin entry point: %d\n",
GetLastError());
}
return new_main;
}
static void cr_plat_init() {
}
static int cr_seh_filter(cr_plugin &ctx, unsigned long seh) {
if (ctx.version == 1) {
return EXCEPTION_CONTINUE_SEARCH;
}
switch (seh) {
case EXCEPTION_ACCESS_VIOLATION:
ctx.failure = CR_SEGFAULT;
return EXCEPTION_EXECUTE_HANDLER;
case EXCEPTION_ILLEGAL_INSTRUCTION:
ctx.failure = CR_ILLEGAL;
return EXCEPTION_EXECUTE_HANDLER;
case EXCEPTION_DATATYPE_MISALIGNMENT:
ctx.failure = CR_MISALIGN;
return EXCEPTION_EXECUTE_HANDLER;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
ctx.failure = CR_BOUNDS;
return EXCEPTION_EXECUTE_HANDLER;
case EXCEPTION_STACK_OVERFLOW:
ctx.failure = CR_STACKOVERFLOW;
return EXCEPTION_EXECUTE_HANDLER;
default:
break;
}
return EXCEPTION_CONTINUE_SEARCH;
}
static int cr_plugin_main(cr_plugin &ctx, cr_op operation) {
auto p = (cr_internal *)ctx.p;
__try {
if (p->main) {
return p->main(&ctx, operation);
}
} __except (cr_seh_filter(ctx, GetExceptionCode())) {
return -1;
}
return 0;
}
#endif // _WIN32
#if defined(__unix__)
#include <csignal>
#include <cstring>
#include <dlfcn.h>
#include <elf.h>
#include <fcntl.h>
#include <link.h>
#include <setjmp.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/ucontext.h>
#include <unistd.h>
#define CR_STR "%s"
#define CR_INT "%d"
using so_handle = void *;
// unix,internal
// a helper function to validate that an area of memory is empty
// this is used to validate that the data in the .bss haven't changed
// and that we are safe to discard it and uses the new one.
bool cr_is_empty(const void *const buf, int64_t len) {
assert(buf);
bool r = false;
auto c = (const char *const)buf;
for (int i = 0; i < len; ++i) {
r |= c[i];
}
return !r;
}
// unix,internal
// save section informations to be used during load/unload when copying
// around global state (from .bss and .state binary sections).
// vaddr = is the in memory loaded address of the segment-section
// base = is the in file section address
// shdr = the in file section header
template <class H>
void cr_elf_section_save(cr_plugin &ctx, cr_plugin_section_type::e type,
int64_t vaddr, int64_t base, H shdr) {
const auto version = cr_plugin_section_version::current;
auto p = (cr_internal *)ctx.p;
auto data = &p->data[type][version];
const size_t old_size = data->size;
data->base = base;
data->ptr = (char *)vaddr;
data->size = shdr.sh_size;
data->data = realloc(data->data, shdr.sh_size);
if (old_size < shdr.sh_size) {
memset((char *)data->data + old_size, '\0', shdr.sh_size - old_size);
}
}
// unix,internal
// validates that the sections being loaded are compatible with the previous
// one accordingly with desired `cr_mode` mode. If this is a first load, a
// validation is not necessary. At the same time it will initialize the
// section tracking information and alloc the required temporary space to use
// during unload.
template <class H>
bool cr_elf_validate_sections(cr_plugin &ctx, bool rollback, H shdr, int shnum,
const char *sh_strtab_p) {
assert(sh_strtab_p);
auto p = (cr_internal *)ctx.p;
bool result = true;
for (int i = 0; i < shnum; ++i) {
const char *name = sh_strtab_p + shdr[i].sh_name;
auto sectionHeader = shdr[i];
const int64_t addr = sectionHeader.sh_addr;
const int64_t size = sectionHeader.sh_size;
const int64_t base = (intptr_t)p->seg.ptr + p->seg.size;
if (!strcmp(name, ".state")) {
const int64_t vaddr = base - size;
auto sec = cr_plugin_section_type::state;
if (ctx.version || rollback) {
result &=
cr_plugin_section_validate(ctx, sec, vaddr, addr, size);
}
if (result) {
cr_elf_section_save(ctx, sec, vaddr, addr, sectionHeader);
}
} else if (!strcmp(name, ".bss")) {
// .bss goes past segment filesz, but it may be just padding
const int64_t vaddr = base;
auto sec = cr_plugin_section_type::bss;
if (ctx.version || rollback) {
// this is kinda hack to skip bss validation if our data is zero
// this means we don't care scrapping it, and helps skipping
// validating a .bss that serves only as padding in the segment.
if (!cr_is_empty(p->data[sec][0].data, p->data[sec][0].size)) {
result &=
cr_plugin_section_validate(ctx, sec, vaddr, addr, size);
}
}
if (result) {
cr_elf_section_save(ctx, sec, vaddr, addr, sectionHeader);
}
}
}
return result;
}
struct cr_ld_data {
cr_plugin *ctx = nullptr;
int64_t data_segment_address = 0;
int64_t data_segment_size = 0;
const char *fullname = nullptr;
};
// Iterate over all loaded shared objects and then for each one, iterates
// over each segment.
// So we find our plugin by filename and try to find the segment that
// contains our data sections (.state and .bss) to find their virtual
// addresses.
// We search segments with type PT_LOAD (1), meaning it is a loadable
// segment (anything that really matters ie. .text, .data, .bss, etc...)
// The segment where the p_memsz is bigger than p_filesz is the segment
// that contains the section .bss (if there is one or there is padding).
// Also, the segment will have sensible p_flags value (PF_W for exemple).
//
// Some useful references:
// http://www.skyfree.org/linux/references/ELF_Format.pdf
// https://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries/
static int cr_dl_header_handler(struct dl_phdr_info *info, size_t size,
void *data) {
assert(info && data);
auto p = (cr_ld_data *)data;
auto ctx = p->ctx;
if (strcasecmp(info->dlpi_name, p->fullname)) {
return 0;
}
for (int i = 0; i < info->dlpi_phnum; i++) {
auto phdr = info->dlpi_phdr[i];
if (phdr.p_type != PT_LOAD) {
continue;
}
// assume the first writable segment is the one that contains our
// sections this may not be true I imagine, but if this becomes an
// issue we fix it by comparing against section addresses, but this
// will require some rework on the code flow.
if (phdr.p_flags & PF_W) {
auto pimpl = (cr_internal *)ctx->p;
pimpl->seg.ptr = (char *)(info->dlpi_addr + phdr.p_vaddr);
pimpl->seg.size = phdr.p_filesz;
break;
}
}
return 0;
}
static bool cr_plugin_validate_sections(cr_plugin &ctx, so_handle handle,
const fs::path &imagefile,
bool rollback) {
assert(handle);
cr_ld_data data;
data.ctx = &ctx;
auto pimpl = (cr_internal *)ctx.p;
if (pimpl->mode == CR_DISABLE) {
return true;
}
data.fullname = imagefile.c_str();
dl_iterate_phdr(cr_dl_header_handler, (void *)&data);